Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Allow settings references in product and page mutations (#6596)
Iga Karbowiak9430c5292b8b
diff --git a/saleor/attribute/__init__.py b/saleor/attribute/__init__.pyindex a1690307a8..6cdd392eb9 100644--- a/saleor/attribute/__init__.py+++ b/saleor/attribute/__init__.py@@ -24,6 +24,8 @@ class AttributeType:class AttributeEntityType:- PAGE = "page"+ """Type of a reference entity type. Must match the name of the graphql type."""++ PAGE = "Page"CHOICES = [(PAGE, "Page")]diff --git a/saleor/attribute/migrations/0004_auto_20201203_1115.py b/saleor/attribute/migrations/0004_auto_20201204_1325.pysimilarity index 87%rename from saleor/attribute/migrations/0004_auto_20201203_1115.pyrename to saleor/attribute/migrations/0004_auto_20201204_1325.pyindex 739c20b0b3..5c2e708c0a 100644--- a/saleor/attribute/migrations/0004_auto_20201203_1115.py+++ b/saleor/attribute/migrations/0004_auto_20201204_1325.py@@ -1,4 +1,4 @@-# Generated by Django 3.1.3 on 2020-12-03 11:15+# Generated by Django 3.1.3 on 2020-12-04 13:25from django.db import migrations, models@@ -14,7 +14,7 @@ class Migration(migrations.Migration):model_name="attribute",name="entity_type",field=models.CharField(- blank=True, choices=[("page", "Page")], max_length=50, null=True+ blank=True, choices=[("Page", "Page")], max_length=50, null=True),),migrations.AlterField(diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.pyindex ccc72e2af3..fb273b7149 100644--- a/saleor/graphql/attribute/tests/test_utils.py+++ b/saleor/graphql/attribute/tests/test_utils.py@@ -25,6 +25,7 @@ def test_validate_attributes_input_for_product(values=["a"],file_url=None,content_type=None,+ references=[],),),(@@ -34,6 +35,7 @@ def test_validate_attributes_input_for_product(values=["b"],file_url=None,content_type=None,+ references=[],),),]@@ -68,6 +70,7 @@ def test_validate_attributes_input_for_product_no_values_given(values=[],file_url=None,content_type=None,+ references=[],),),(@@ -77,6 +80,7 @@ def test_validate_attributes_input_for_product_no_values_given(values=[],file_url=None,content_type=None,+ references=[],),),]@@ -119,6 +123,7 @@ def test_validate_attributes_input_for_product_too_many_values_given(values=["abc", "efg"],file_url=None,content_type=None,+ references=[],),),(@@ -128,6 +133,7 @@ def test_validate_attributes_input_for_product_too_many_values_given(values=["a", "b"],file_url=None,content_type=None,+ references=[],),),]@@ -169,6 +175,7 @@ def test_validate_attributes_input_for_product_empty_values_given(values=["a", None],file_url=None,content_type=None,+ references=[],),),(@@ -178,6 +185,7 @@ def test_validate_attributes_input_for_product_empty_values_given(values=[" "],file_url=None,content_type=None,+ references=[],),),]@@ -220,6 +228,7 @@ def test_validate_attributes_input_for_product_lack_of_required_attribute(values=["a"],file_url=None,content_type=None,+ references=[],),),]@@ -261,6 +270,7 @@ def test_validate_attributes_input_for_product_multiply_errors(values=[None],file_url=None,content_type=None,+ references=[],),),(@@ -270,6 +280,7 @@ def test_validate_attributes_input_for_product_multiply_errors(values=["a", "b"],file_url=None,content_type=None,+ references=[],),),]@@ -312,6 +323,7 @@ def test_validate_attributes_input_for_page(values=["a"],file_url=None,content_type=None,+ references=[],),),(@@ -321,6 +333,7 @@ def test_validate_attributes_input_for_page(values=["b"],file_url=None,content_type=None,+ references=[],),),]@@ -355,6 +368,7 @@ def test_validate_attributes_input_for_page_no_values_given(values=[],file_url=None,content_type=None,+ references=[],),),(@@ -364,6 +378,7 @@ def test_validate_attributes_input_for_page_no_values_given(values=[],file_url=None,content_type=None,+ references=[],),),]@@ -406,6 +421,7 @@ def test_validate_attributes_input_for_page_too_many_values_given(values=["abc", "efg"],file_url=None,content_type=None,+ references=[],),),(@@ -415,6 +431,7 @@ def test_validate_attributes_input_for_page_too_many_values_given(values=["a", "b"],file_url=None,content_type=None,+ references=[],),),]@@ -456,6 +473,7 @@ def test_validate_attributes_input_for_page_empty_values_given(values=["a", None],file_url=None,content_type=None,+ references=[],),),(@@ -465,6 +483,7 @@ def test_validate_attributes_input_for_page_empty_values_given(values=[" "],file_url=None,content_type=None,+ references=[],),),]@@ -507,6 +526,7 @@ def test_validate_attributes_input_for_page_lack_of_required_attribute(values=["a"],file_url=None,content_type=None,+ references=[],),),]@@ -545,6 +565,7 @@ def test_validate_attributes_input_for_page_multiply_errors(values=[None],file_url=None,content_type=None,+ references=[],),),(@@ -554,6 +575,7 @@ def test_validate_attributes_input_for_page_multiply_errors(values=["a", "b"],file_url=None,content_type=None,+ references=[],),),]@@ -594,6 +616,7 @@ def test_validate_attributes_input(weight_attribute, color_attribute, product_tyvalues=["a"],file_url=None,content_type=None,+ references=[],),),(@@ -603,6 +626,7 @@ def test_validate_attributes_input(weight_attribute, color_attribute, product_tyvalues=["b"],file_url=None,content_type=None,+ references=[],),),]@@ -636,6 +660,7 @@ def test_validate_attributes_input_no_values_given(values=[],file_url=None,content_type=None,+ references=[],),),(@@ -645,6 +670,7 @@ def test_validate_attributes_input_no_values_given(values=[],file_url=None,content_type=None,+ references=[],),),]@@ -686,6 +712,7 @@ def test_validate_not_required_variant_selection_attributes_input_no_values_givevalues=[],file_url=None,content_type=None,+ references=[],),),(@@ -695,6 +722,7 @@ def test_validate_not_required_variant_selection_attributes_input_no_values_givevalues=[],file_url=None,content_type=None,+ references=[],),),]@@ -728,6 +756,7 @@ def test_validate_attributes_input_too_many_values_given(values=["abc", "efg"],file_url=None,content_type=None,+ references=[],),),(@@ -737,6 +766,7 @@ def test_validate_attributes_input_too_many_values_given(values=["a", "b"],file_url=None,content_type=None,+ references=[],),),]@@ -776,6 +806,7 @@ def test_validate_attributes_input_empty_values_given(values=[None],file_url=None,content_type=None,+ references=[],),),(@@ -785,6 +816,7 @@ def test_validate_attributes_input_empty_values_given(values=[" "],file_url=None,content_type=None,+ references=[],),),]@@ -824,6 +856,7 @@ def test_validate_attributes_input_multiply_errors(values=[None],file_url=None,content_type=None,+ references=[],),),(@@ -833,6 +866,7 @@ def test_validate_attributes_input_multiply_errors(values=["a", "b"],file_url=None,content_type=None,+ references=[],),),]@@ -874,6 +908,7 @@ def test_validate_attributes_with_file_input_type_for_product(values=["a"],file_url=None,content_type=None,+ references=[],),),(@@ -883,6 +918,7 @@ def test_validate_attributes_with_file_input_type_for_product(values=[],file_url="test_file.jpeg",content_type="image/jpeg",+ references=[],),),]@@ -917,6 +953,7 @@ def test_validate_attributes_with_file_input_type_for_product_no_file_given(values=["a"],file_url=None,content_type=None,+ references=[],),),(@@ -926,6 +963,7 @@ def test_validate_attributes_with_file_input_type_for_product_no_file_given(values=[],file_url="",content_type="image/jpeg",+ references=[],),),]@@ -965,6 +1003,7 @@ def test_validate_not_required_attrs_with_file_input_type_for_product_no_file_givalues=["a"],file_url=None,content_type=None,+ references=[],),),(@@ -974,6 +1013,7 @@ def test_validate_not_required_attrs_with_file_input_type_for_product_no_file_givalues=[],file_url="",content_type="image/jpeg",+ references=[],),),]@@ -1008,6 +1048,7 @@ def test_validate_attributes_with_file_input_type_for_product_empty_file_value(values=["a"],file_url=None,content_type=None,+ references=[],),),(@@ -1017,6 +1058,7 @@ def test_validate_attributes_with_file_input_type_for_product_empty_file_value(values=[],file_url=" ",content_type="image/jpeg",+ references=[],),),]diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.pyindex 6ca1f1d89c..5095888495 100644--- a/saleor/graphql/attribute/types.py+++ b/saleor/graphql/attribute/types.py@@ -2,7 +2,7 @@ import reimport graphene-from ...attribute import models+from ...attribute import AttributeInputType, modelsfrom ..core.connection import CountableDjangoObjectTypefrom ..core.types import Filefrom ..decorators import (@@ -12,7 +12,7 @@ from ..decorators import (from ..meta.types import ObjectWithMetadatafrom ..translations.fields import TranslationFieldfrom ..translations.types import AttributeTranslation, AttributeValueTranslation-from .dataloaders import AttributeValuesByAttributeIdLoader+from .dataloaders import AttributesByAttributeId, AttributeValuesByAttributeIdLoaderfrom .descriptions import AttributeDescriptions, AttributeValueDescriptionsfrom .enums import (AttributeEntityTypeEnum,@@ -49,6 +49,7 @@ class AttributeValue(CountableDjangoObjectType):AttributeValueTranslation, type_name="attribute value")input_type = AttributeInputTypeEnum(description=AttributeDescriptions.INPUT_TYPE)+ reference = graphene.ID(description="The ID of the attribute reference.")file = graphene.Field(File, description=AttributeValueDescriptions.FILE, required=False)@@ -74,6 +75,23 @@ class AttributeValue(CountableDjangoObjectType):returnreturn File(url=root.file_url, content_type=root.content_type)+ @staticmethod+ def resolve_reference(root: models.AttributeValue, info, **_kwargs):+ def prepare_reference(attribute):+ if not attribute.input_type == AttributeInputType.REFERENCE:+ return+ reference_pk = root.slug.split("_")[1]+ reference_id = graphene.Node.to_global_id(+ attribute.entity_type, reference_pk+ )+ return reference_id++ return (+ AttributesByAttributeId(info.context)+ .load(root.attribute_id)+ .then(prepare_reference)+ )+class Attribute(CountableDjangoObjectType):input_type = AttributeInputTypeEnum(description=AttributeDescriptions.INPUT_TYPE)diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.pyindex b56d5967d0..95de3982ad 100644--- a/saleor/graphql/attribute/utils.py+++ b/saleor/graphql/attribute/utils.py@@ -1,32 +1,47 @@-from collections import defaultdict, namedtuple-from typing import TYPE_CHECKING, Dict, Iterable, List, Tuple, Union+from collections import defaultdict+from dataclasses import dataclass+from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple, Unionimport graphenefrom django.core.exceptions import ValidationErrorfrom django.db.models import Qfrom django.utils.text import slugify+from graphql.error import GraphQLErrorfrom graphql_relay import from_global_id-from ...attribute import AttributeInputType, AttributeType, models as attribute_models+from ...attribute import (+ AttributeEntityType,+ AttributeInputType,+ AttributeType,+ models as attribute_models,+)from ...attribute.utils import associate_attribute_values_to_instancefrom ...core.utils import generate_unique_slugfrom ...page import models as page_modelsfrom ...page.error_codes import PageErrorCodefrom ...product import models as product_modelsfrom ...product.error_codes import ProductErrorCode+from ..utils import get_nodesif TYPE_CHECKING:from django.db.models import QuerySetfrom ...attribute.models import Attribute-AttrValuesInput = namedtuple(- "AttrValuesInput", ["global_id", "values", "file_url", "content_type"]-)+@dataclass+class AttrValuesInput:+ global_id: str+ values: List[str]+ references: Union[List[str], List[page_models.Page]]+ file_url: Optional[str] = None+ content_type: Optional[str] = None++T_INSTANCE = Union[product_models.Product, product_models.ProductVariant, page_models.Page]T_INPUT_MAP = List[Tuple[attribute_models.Attribute, AttrValuesInput]]+T_ERROR_DICT = Dict[Tuple[str, str], List[str]]class AttributeAssignmentMixin:@@ -45,10 +60,15 @@ class AttributeAssignmentMixin:be unable to build or might only be partially built."""+ REFERENCE_VALUE_NAME_MAPPING = {AttributeEntityType.PAGE: "title"}++ ENTITY_TYPE_TO_MODEL_MAPPING = {AttributeEntityType.PAGE: page_models.Page}+@classmethoddef _resolve_attribute_nodes(cls,qs: "QuerySet",+ error_class,*,global_ids: List[str],pks: Iterable[int],@@ -64,7 +84,7 @@ class AttributeAssignmentMixin:f"Could not resolve to a node: ids={global_ids}"f" and slugs={list(slugs)}"),- code=ProductErrorCode.NOT_FOUND.value,+ code=error_class.NOT_FOUND.value,)nodes_pk_list = set()@@ -77,31 +97,31 @@ class AttributeAssignmentMixin:if pk not in nodes_pk_list:raise ValidationError(f"Could not resolve {global_id!r} to Attribute",- code=ProductErrorCode.NOT_FOUND.value,+ 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=ProductErrorCode.NOT_FOUND.value,+ code=error_class.NOT_FOUND.value,)return nodes@classmethod- def _resolve_attribute_global_id(cls, global_id: str) -> int:+ def _resolve_attribute_global_id(cls, error_class, global_id: str) -> int:"""Resolve an Attribute global ID into an internal ID (int)."""graphene_type, internal_id = from_global_id(global_id) # type: str, strif graphene_type != "Attribute":raise ValidationError(f"Must receive an Attribute id, got {graphene_type}.",- code=ProductErrorCode.INVALID.value,+ code=error_class.INVALID.value,)if not internal_id.isnumeric():raise ValidationError(f"An invalid ID value was passed: {global_id}",- code=ProductErrorCode.INVALID.value,+ code=error_class.INVALID.value,)return int(internal_id)@@ -119,6 +139,33 @@ class AttributeAssignmentMixin:)[0]for value in attr_values.values)++ @classmethod+ def _pre_save_reference_values(+ cls,+ instance,+ attribute: attribute_models.Attribute,+ attr_values: AttrValuesInput,+ ):+ """Lazy-retrieve or create the database objects from the supplied raw values.++ Slug value is generated based on instance and reference entity id.+ """+ field_name = cls.REFERENCE_VALUE_NAME_MAPPING[+ attribute.entity_type # type: ignore+ ]+ get_or_create = attribute.values.get_or_create+ return tuple(+ get_or_create(+ attribute=attribute,+ slug=slugify(+ f"{instance.id}_{reference.id}", # type: ignore+ allow_unicode=True,+ ),+ defaults={"name": getattr(reference, field_name)},+ )[0]+ for reference in attr_values.references+ )@classmethoddef _pre_save_file_value(@@ -222,6 +269,7 @@ class AttributeAssignmentMixin::raises ValidationError: contain the message.:return: The resolved data"""+ error_class = PageErrorCode if is_page_attributes else ProductErrorCode# Mapping to associate the input values back to the resolved attribute nodespks = {}@@ -238,10 +286,11 @@ class AttributeAssignmentMixin:values=attribute_input.get("values", []),file_url=attribute_input.get("file"),content_type=attribute_input.get("content_type"),+ references=attribute_input.get("references", []),)if global_id:- internal_id = cls._resolve_attribute_global_id(global_id)+ internal_id = cls._resolve_attribute_global_id(error_class, global_id)global_ids.append(global_id)pks[internal_id] = valueselif slug:@@ -249,12 +298,17 @@ class AttributeAssignmentMixin:else:raise ValidationError("You must whether supply an ID or a slug",- code=ProductErrorCode.REQUIRED.value,+ code=error_class.REQUIRED.value, # type: ignore)attributes = cls._resolve_attribute_nodes(- attributes_qs, global_ids=global_ids, pks=pks.keys(), slugs=slugs.keys()+ 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)@@ -264,7 +318,26 @@ class AttributeAssignmentMixin:if key is None:key = slugs[attribute.slug]+ if attribute.input_type == AttributeInputType.REFERENCE:+ try:+ key = cls._validate_references(error_class, attribute, key)+ except GraphQLError:+ attr_with_invalid_references.append(attribute)+cleaned_input.append((attribute, key))++ if attr_with_invalid_references:+ raise ValidationError(+ {+ "attributes": ValidationError(+ "Provided references are invalid. Some of the nodes "+ "do not exist or are different types than types defined "+ "in attribute entity type.",+ code=error_class.INVALID.value, # type: ignore+ )+ }+ )+cls._validate_attributes_input(cleaned_input,attributes_qs,@@ -274,6 +347,21 @@ class AttributeAssignmentMixin:return cleaned_input+ @classmethod+ def _validate_references(+ cls, error_class, attribute: attribute_models.Attribute, values: AttrValuesInput+ ) -> AttrValuesInput:+ references = values.references+ if not references:+ return values++ entity_model = cls.ENTITY_TYPE_TO_MODEL_MAPPING[+ attribute.entity_type # type: ignore+ ]+ ref_instances = get_nodes(references, attribute.entity_type, model=entity_model)+ values.references = ref_instances+ return values+@classmethoddef save(cls, instance: T_INSTANCE, cleaned_input: T_INPUT_MAP):"""Save the cleaned input into the database against the given instance.@@ -288,6 +376,10 @@ class AttributeAssignmentMixin:attribute_values = cls._pre_save_file_value(instance, attribute, attr_values)+ elif attribute.input_type == AttributeInputType.REFERENCE:+ attribute_values = cls._pre_save_reference_values(+ instance, attribute, attr_values+ )else:attribute_values = cls._pre_save_values(attribute, attr_values)associate_attribute_values_to_instance(@@ -302,47 +394,36 @@ def get_variant_selection_attributes(qs: "QuerySet"):)-class ProductAttributeInputErrors:- ERROR_NO_VALUE_GIVEN = ValidationError(- "Attribute expects a value but none were given",- code=PageErrorCode.REQUIRED.value,- )- ERROR_DROPDOWN_GET_MORE_THAN_ONE_VALUE = ValidationError(- "Attribute must take only one value", code=PageErrorCode.INVALID.value,- )- ERROR_BLANK_VALUE = ValidationError(- "Attribute values cannot be blank", code=PageErrorCode.REQUIRED.value,- )-- # file errors- ERROR_NO_FILE_GIVEN = ValidationError(- "Attribute file url cannot be blank", code=PageErrorCode.REQUIRED.value,- )- ERROR_BLANK_FILE_VALUE = ValidationError(- "Attribute expects a file url but none were given",- code=PageErrorCode.REQUIRED.value,- )+class AttributeInputErrors:+ """Define error message and error code for given error.+ All used error codes must be specified in PageErrorCode and ProductErrorCode.+ """-class PageAttributeInputErrors:- ERROR_NO_VALUE_GIVEN = ValidationError(- "Attribute expects a value but none were given",- code=ProductErrorCode.REQUIRED.value,- )- ERROR_DROPDOWN_GET_MORE_THAN_ONE_VALUE = ValidationError(- "Attribute must take only one value", code=ProductErrorCode.INVALID.value,+ ERROR_NO_VALUE_GIVEN = ("Attribute expects a value but none were given", "REQUIRED")+ ERROR_DROPDOWN_GET_MORE_THAN_ONE_VALUE = (+ "Attribute must take only one value",+ "INVALID",)- ERROR_BLANK_VALUE = ValidationError(- "Attribute values cannot be blank", code=ProductErrorCode.REQUIRED.value,+ ERROR_BLANK_VALUE = (+ "Attribute values cannot be blank",+ "REQUIRED",)# file errors- ERROR_NO_FILE_GIVEN = ValidationError(- "Attribute file url cannot be blank", code=ProductErrorCode.REQUIRED.value,+ ERROR_NO_FILE_GIVEN = (+ "Attribute file url cannot be blank",+ "REQUIRED",)- ERROR_BLANK_FILE_VALUE = ValidationError(+ ERROR_BLANK_FILE_VALUE = ("Attribute expects a file url but none were given",- code=ProductErrorCode.REQUIRED.value,+ "REQUIRED",+ )++ # reference errors+ ERROR_NO_REFERENCE_GIVEN = (+ "Attribute expects an reference but none were given.",+ "REQUIRED",)@@ -359,34 +440,29 @@ def validate_attributes_input(- ensure the values are correct for a products or a page"""- errors_data_structure = (- PageAttributeInputErrors if is_page_attributes else ProductAttributeInputErrors- )- attribute_errors: Dict[ValidationError, List[str]] = defaultdict(list)+ error_code_enum = PageErrorCode if is_page_attributes else ProductErrorCode+ attribute_errors: T_ERROR_DICT = defaultdict(list)for attribute, attr_values in input_data:- # validation for file attribute+ attrs = (+ attribute,+ attr_values,+ attribute_errors,+ variant_validation,+ )if attribute.input_type == AttributeInputType.FILE:- validate_file_attributes_input(- attribute,- attr_values,- errors_data_structure,- attribute_errors,- variant_validation,- )+ validate_file_attributes_input(*attrs)+ elif attribute.input_type == AttributeInputType.REFERENCE:+ validate_reference_attributes_input(*attrs)# validation for other input typeselse:- validate_not_file_attributes_input(- attribute,- attr_values,- errors_data_structure,- attribute_errors,- variant_validation,- )+ validate_standard_attributes_input(*attrs)- errors = prepare_error_list_from_error_attribute_mapping(attribute_errors)+ errors = prepare_error_list_from_error_attribute_mapping(+ attribute_errors, error_code_enum+ )if not variant_validation:errors = validate_required_attributes(- input_data, attribute_qs, errors, is_page_attributes+ input_data, attribute_qs, errors, error_code_enum)return errors@@ -395,8 +471,7 @@ def validate_attributes_input(def validate_file_attributes_input(attribute: "Attribute",attr_values: "AttrValuesInput",- errors_data_structure,- attribute_errors: Dict[ValidationError, List[str]],+ attribute_errors: T_ERROR_DICT,variant_validation: bool,):attribute_id = attr_values.global_id@@ -405,20 +480,34 @@ def validate_file_attributes_input(if attribute.value_required or (variant_validation and is_variant_selection_attribute(attribute)):- attribute_errors[errors_data_structure.ERROR_NO_FILE_GIVEN].append(+ attribute_errors[AttributeInputErrors.ERROR_NO_FILE_GIVEN].append(attribute_id)elif not value.strip():- attribute_errors[errors_data_structure.ERROR_BLANK_FILE_VALUE].append(+ attribute_errors[AttributeInputErrors.ERROR_BLANK_FILE_VALUE].append(attribute_id)-def validate_not_file_attributes_input(+def validate_reference_attributes_input(attribute: "Attribute",attr_values: "AttrValuesInput",- errors_data_structure,- attribute_errors: Dict[ValidationError, List[str]],+ attribute_errors: T_ERROR_DICT,+ variant_validation: bool,+):+ attribute_id = attr_values.global_id+ references = attr_values.references+ if not references:+ if attribute.value_required or variant_validation:+ attribute_errors[AttributeInputErrors.ERROR_NO_REFERENCE_GIVEN].append(+ attribute_id+ )+++def validate_standard_attributes_input(+ attribute: "Attribute",+ attr_values: "AttrValuesInput",+ attribute_errors: T_ERROR_DICT,variant_validation: bool,):attribute_id = attr_values.global_id@@ -426,7 +515,7 @@ def validate_not_file_attributes_input(if attribute.value_required or (variant_validation and is_variant_selection_attribute(attribute)):- attribute_errors[errors_data_structure.ERROR_NO_VALUE_GIVEN].append(+ attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(attribute_id)elif (@@ -434,11 +523,11 @@ def validate_not_file_attributes_input(and len(attr_values.values) != 1):attribute_errors[- errors_data_structure.ERROR_DROPDOWN_GET_MORE_THAN_ONE_VALUE+ AttributeInputErrors.ERROR_DROPDOWN_GET_MORE_THAN_ONE_VALUE].append(attribute_id)for value in attr_values.values:if value is None or not value.strip():- attribute_errors[errors_data_structure.ERROR_BLANK_VALUE].append(+ attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(attribute_id)@@ -451,12 +540,11 @@ def validate_required_attributes(input_data: List[Tuple["Attribute", "AttrValuesInput"]],attribute_qs: "QuerySet",errors: List[ValidationError],- is_page_attributes: bool,+ error_code_enum,):"""Ensure all required attributes are supplied."""supplied_attribute_pk = [attribute.pk for attribute, _ in input_data]- error_code_enum = PageErrorCode if is_page_attributes else ProductErrorCodemissing_required_attributes = attribute_qs.filter(Q(value_required=True) & ~Q(pk__in=supplied_attribute_pk)@@ -478,11 +566,16 @@ def validate_required_attributes(def prepare_error_list_from_error_attribute_mapping(- attribute_errors: Dict[ValidationError, List[str]]+ attribute_errors: T_ERROR_DICT, error_code_enum):errors = []- for error, attributes in attribute_errors.items():- error.params = {"attributes": attributes}+ for error_data, attributes in attribute_errors.items():+ error_msg, error_type = error_data+ error = ValidationError(+ error_msg,+ code=getattr(error_code_enum, error_type).value,+ params={"attributes": attributes},+ )errors.append(error)return errorsdiff --git a/saleor/graphql/page/tests/test_page.py b/saleor/graphql/page/tests/test_page.pyindex c55de6e691..df5ee45dfe 100644--- a/saleor/graphql/page/tests/test_page.py+++ b/saleor/graphql/page/tests/test_page.py@@ -6,6 +6,7 @@ from django.utils import timezonefrom django.utils.text import slugifyfrom freezegun import freeze_time+from ....attribute.models import AttributeValuefrom ....attribute.utils import associate_attribute_values_to_instancefrom ....page.error_codes import PageErrorCodefrom ....page.models import Page, PageType@@ -153,6 +154,7 @@ CREATE_PAGE_MUTATION = """values {slugname+ referencefile {urlcontentType@@ -409,6 +411,7 @@ def test_create_page_with_file_attribute("slug": f"{attr_value.slug}-2","name": attr_value.name,"file": {"url": attr_value.file_url, "contentType": None},+ "reference": None,}],}@@ -479,6 +482,7 @@ def test_create_page_with_file_attribute_new_attribute_value("values": [{"slug": slugify(new_value),+ "reference": None,"name": new_value,"file": {"url": "http://testserver/media/" + new_value,@@ -588,6 +592,170 @@ def test_create_page_with_file_attribute_required_no_file_url_given(assert errors[0]["attributes"] == [file_attribute_id]+def test_create_page_with_reference_attribute(+ staff_api_client, permission_manage_pages, page_type, page_reference_attribute, page+):+ # given+ page_slug = "test-slug"+ page_content = "test content"+ page_content_json = json.dumps({"content": "test content"})+ page_title = "test title"+ page_is_published = True+ page_type = 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_reference_attribute.pk+ )+ page_type.page_attributes.add(page_reference_attribute)+ reference = graphene.Node.to_global_id("Page", page.pk)++ values_count = page_reference_attribute.values.count()++ # test creating root page+ variables = {+ "title": page_title,+ "content": page_content,+ "contentJson": page_content_json,+ "isPublished": page_is_published,+ "slug": page_slug,+ "pageType": page_type_id,+ "attributes": [{"id": 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["pageErrors"]++ assert not errors+ assert data["page"]["title"] == page_title+ assert data["page"]["content"] == page_content+ assert data["page"]["contentJson"] == page_content_json+ 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_reference_attribute.slug},+ "values": [+ {"slug": f"{new_page_pk}_{page.pk}", "file": None, "name": page.title, "reference": reference}+ ],+ }+ assert data["page"]["attributes"][0] == expected_attr_data++ page_reference_attribute.refresh_from_db()+ assert page_reference_attribute.values.count() == values_count + 1+++def test_create_page_with_reference_attribute_not_required_no_references_given(+ staff_api_client, permission_manage_pages, page_type, page_reference_attribute+):+ # given+ page_slug = "test-slug"+ page_content = "test content"+ page_content_json = json.dumps({"content": "test content"})+ page_title = "test title"+ page_is_published = True+ page_type = 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)++ file_attribute_id = graphene.Node.to_global_id(+ "Attribute", page_reference_attribute.pk+ )+ page_type.page_attributes.add(page_reference_attribute)++ page_reference_attribute.value_required = False+ page_reference_attribute.save(update_fields=["value_required"])++ # test creating root page+ variables = {+ "title": page_title,+ "content": page_content,+ "contentJson": page_content_json,+ "isPublished": page_is_published,+ "slug": page_slug,+ "pageType": page_type_id,+ "attributes": [{"id": file_attribute_id, "file": ""}],+ }++ # when+ response = staff_api_client.post_graphql(+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]+ )++ content = get_graphql_content(response)+ data = content["data"]["pageCreate"]+ assert data["pageErrors"] == []+ assert data["page"]["title"] == page_title+ assert data["page"]["content"] == page_content+ assert data["page"]["contentJson"] == page_content_json+ 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+ assert len(data["page"]["attributes"][0]["values"]) == 0+++def test_create_page_with_reference_attribute_required_no_references_given(+ staff_api_client, permission_manage_pages, page_type, page_reference_attribute+):+ # given+ page_slug = "test-slug"+ page_content = "test content"+ page_content_json = json.dumps({"content": "test content"})+ page_title = "test title"+ page_is_published = True+ page_type = 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)++ file_attribute_id = graphene.Node.to_global_id(+ "Attribute", page_reference_attribute.pk+ )+ page_type.page_attributes.add(page_reference_attribute)++ page_reference_attribute.value_required = True+ page_reference_attribute.save(update_fields=["value_required"])++ # test creating root page+ variables = {+ "title": page_title,+ "content": page_content,+ "contentJson": page_content_json,+ "isPublished": page_is_published,+ "slug": page_slug,+ "pageType": page_type_id,+ "attributes": [{"id": file_attribute_id, "file": ""}],+ }++ # when+ response = staff_api_client.post_graphql(+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]+ )++ content = get_graphql_content(response)+ data = content["data"]["pageCreate"]+ errors = data["pageErrors"]+ assert not data["page"]+ assert len(errors) == 1+ assert errors[0]["code"] == PageErrorCode.REQUIRED.name+ assert errors[0]["field"] == "attributes"+ assert errors[0]["attributes"] == [file_attribute_id]++def test_page_delete_mutation(staff_api_client, page, permission_manage_pages):query = """mutation DeletePage($id: ID!) {@@ -635,6 +803,7 @@ UPDATE_PAGE_MUTATION = """values {slugname+ referencefile {urlcontentType@@ -694,13 +863,20 @@ def test_update_page(staff_api_client, permission_manage_pages, page):for attr in page_type.page_attributes.all():if attr.slug != tag_attr.slug:values = [- {"slug": slug, "file": None, "name": name}+ {"slug": slug, "file": None, "name": name, "reference": None}for slug, name in page_attr.filter(assignment__attribute=attr).values_list("values__slug", "values__name")]else:- values = [{"slug": slugify(new_value), "file": None, "name": new_value}]+ values = [+ {+ "slug": slugify(new_value),+ "file": None,+ "name": new_value,+ "reference": None+ }+ ]attr_data = {"attribute": {"slug": attr.slug},"values": values,@@ -750,6 +926,7 @@ def test_update_page_with_file_attribute_value({"slug": slugify(new_value),"name": new_value,+ "reference": None,"file": {"url": "http://testserver/media/" + new_value,"contentType": None,@@ -802,6 +979,7 @@ def test_update_page_with_file_attribute_new_value_is_not_created({"slug": existing_value.slug,"name": existing_value.name,+ "reference": None,"file": {"url": existing_value.file_url,"contentType": existing_value.content_type,@@ -812,6 +990,105 @@ def test_update_page_with_file_attribute_new_value_is_not_created(assert updated_attribute in data["page"]["attributes"]+def test_update_page_with_reference_attribute_new_value(+ staff_api_client, permission_manage_pages, page_list, page_reference_attribute+):+ # given+ query = UPDATE_PAGE_MUTATION++ page = page_list[0]+ ref_page = page_list[1]+ page_type = page.page_type+ page_type.page_attributes.add(page_reference_attribute)++ values_count = page_reference_attribute.values.count()+ ref_attribute_id = graphene.Node.to_global_id(+ "Attribute", page_reference_attribute.pk+ )+ reference = graphene.Node.to_global_id("Page", ref_page.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["pageErrors"]+ assert data["page"]+ updated_attribute = {+ "attribute": {"slug": page_reference_attribute.slug},+ "values": [+ {"slug": f"{page.pk}_{ref_page.pk}", "name": page.title, "file": None, "reference": reference}+ ],+ }+ assert updated_attribute in data["page"]["attributes"]++ page_reference_attribute.refresh_from_db()+ assert page_reference_attribute.values.count() == values_count + 1+++def test_update_page_with_reference_attribute_existing_value(+ staff_api_client, permission_manage_pages, page_list, page_reference_attribute+):+ # given+ query = UPDATE_PAGE_MUTATION++ page = page_list[0]+ ref_page = page_list[1]+ page_type = page.page_type+ page_type.page_attributes.add(page_reference_attribute)++ attr_value = AttributeValue.objects.create(+ attribute=page_reference_attribute,+ name=page.title,+ slug=f"{page.pk}_{ref_page.pk}",+ )+ associate_attribute_values_to_instance(page, page_reference_attribute, attr_value)++ values_count = page_reference_attribute.values.count()+ ref_attribute_id = graphene.Node.to_global_id(+ "Attribute", page_reference_attribute.pk+ )+ reference = graphene.Node.to_global_id("Page", ref_page.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["pageErrors"]+ assert data["page"]+ updated_attribute = {+ "attribute": {"slug": page_reference_attribute.slug},+ "values": [{"slug": attr_value.slug, "file": None, "name": page.title, "reference": reference}],+ }+ assert updated_attribute in data["page"]["attributes"]++ page_reference_attribute.refresh_from_db()+ assert page_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_typediff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 73dd1ebbeb..96d3a5c503 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -464,6 +464,11 @@ class AttributeValueInput(InputObjectType):description="URL of the file attribute. Every time, a new value is created.",)content_type = graphene.String(required=False, description="File content type.")+ references = graphene.List(+ graphene.NonNull(graphene.ID),+ description="List of entity IDs that will be used as references.",+ required=False,+ )class ProductInput(graphene.InputObjectType):diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex 8d9a23ff0e..c432a1220e 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -37,7 +37,7 @@ from ....product.tasks import update_variants_namesfrom ....product.tests.utils import create_image, create_pdf_file_with_image_extfrom ....product.utils.costs import get_product_costs_datafrom ....warehouse.models import Allocation, Stock, Warehouse-from ...core.enums import ReportingPeriod+from ...core.enums import AttributeErrorCode, ReportingPeriodfrom ...tests.utils import (assert_no_permission,get_graphql_content,@@ -2108,6 +2108,7 @@ CREATE_PRODUCT_MUTATION = """productCreate(input: $input) {product {+ idcategory {name}@@ -2130,6 +2131,7 @@ CREATE_PRODUCT_MUTATION = """values {slugname+ referencefile {urlcontentType@@ -2308,6 +2310,7 @@ def test_create_product_with_file_attribute("name": existing_value.name,"slug": f"{existing_value.slug}-2","file": {"url": existing_value.file_url, "contentType": None},+ "reference": None,}],},@@ -2319,6 +2322,74 @@ def test_create_product_with_file_attribute(assert file_attribute.values.count() == values_count + 1+def test_create_product_with_page_reference_attribute(+ staff_api_client,+ product_type,+ category,+ color_attribute,+ page_reference_attribute,+ permission_manage_products,+ page,+):+ query = CREATE_PRODUCT_MUTATION++ values_count = page_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(page_reference_attribute)+ reference_attr_id = graphene.Node.to_global_id(+ "Attribute", 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["productErrors"] == []+ 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": page_reference_attribute.slug},+ "values": [+ {+ "slug": f"{product_id}_{page.id}",+ "name": page.title,+ "file": None,+ "reference": reference,+ }+ ],+ },+ ]+ for attr_data in data["product"]["attributes"]:+ assert attr_data in expected_attributes_data++ page_reference_attribute.refresh_from_db()+ assert page_reference_attribute.values.count() == values_count + 1++def test_create_product_with_file_attribute_new_attribute_value(staff_api_client,product_type,@@ -2371,6 +2442,7 @@ def test_create_product_with_file_attribute_new_attribute_value({"name": non_existing_value,"slug": slugify(non_existing_value, allow_unicode=True),+ "reference": None,"file": {"url": "http://testserver/media/" + non_existing_value,"contentType": None,@@ -2487,6 +2559,55 @@ def test_create_product_with_file_attribute_required_no_file_url_given(]+def test_create_product_with_page_reference_attribute_required_no_references(+ staff_api_client,+ product_type,+ category,+ page_reference_attribute,+ permission_manage_products,+):+ query = CREATE_PRODUCT_MUTATION++ page_reference_attribute.value_required = True+ page_reference_attribute.save(update_fields=["value_required"])++ 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(page_reference_attribute)+ reference_attr_id = graphene.Node.to_global_id(+ "Attribute", 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": []}],+ }+ }++ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ data = content["data"]["productCreate"]+ errors = data["productErrors"]+ assert not data["product"]+ assert len(errors) == 1+ assert errors[0]["code"] == ProductErrorCode.REQUIRED.name+ assert errors[0]["field"] == "attributes"+ assert errors[0]["attributes"] == [+ graphene.Node.to_global_id("Attribute", page_reference_attribute.pk)+ ]++def test_create_product_no_values_given(staff_api_client, product_type, category, permission_manage_products,):@@ -2706,7 +2827,6 @@ def test_create_product_no_slug_in_input(staff_api_client,product_type,category,- size_attribute,description_json,permission_manage_products,monkeypatch,@@ -2753,13 +2873,7 @@ def test_create_product_no_slug_in_input(def test_create_product_no_category_id(- staff_api_client,- product_type,- category,- size_attribute,- description_json,- permission_manage_products,- monkeypatch,+ staff_api_client, product_type, permission_manage_products, monkeypatch,):query = CREATE_PRODUCT_MUTATION@@ -2875,7 +2989,6 @@ def test_create_product_invalid_product_attributes(weight_attribute,description_json,permission_manage_products,- settings,monkeypatch,):query = CREATE_PRODUCT_MUTATION@@ -3142,6 +3255,7 @@ MUTATION_UPDATE_PRODUCT = """values {nameslug+ referencefile {urlcontentType@@ -3233,11 +3347,9 @@ def test_update_product_with_file_attribute_value(updated_webhook_mock,staff_api_client,file_attribute,- non_default_category,product,product_type,permission_manage_products,- color_attribute,):# givenquery = MUTATION_UPDATE_PRODUCT@@ -3273,6 +3385,7 @@ def test_update_product_with_file_attribute_value({"name": new_value,"slug": slugify(new_value),+ "reference": None,"file": {"url": "http://testserver/media/" + new_value,"contentType": None,@@ -3304,6 +3417,8 @@ def test_update_product_with_file_attribute_value_new_value_is_not_created(existing_value = file_attribute.values.first()associate_attribute_values_to_instance(product, file_attribute, existing_value)+ values_count = file_attribute.values.count()+variables = {"productId": product_id,"input": {@@ -3330,6 +3445,7 @@ def test_update_product_with_file_attribute_value_new_value_is_not_created({"name": existing_value.name,"slug": existing_value.slug,+ "reference": None,"file": {"url": existing_value.file_url,"contentType": existing_value.content_type,@@ -3339,6 +3455,9 @@ def test_update_product_with_file_attribute_value_new_value_is_not_created(}assert expected_file_att_data in attributes+ file_attribute.refresh_from_db()+ assert file_attribute.values.count() == values_count+updated_webhook_mock.assert_called_once_with(product)@@ -3365,6 +3484,175 @@ def test_update_product_rating(assert product.rating == expected_rating+@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_update_product_with_reference_attribute_value(+ updated_webhook_mock,+ staff_api_client,+ 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", page_reference_attribute.pk)+ product_type.product_attributes.add(page_reference_attribute)++ values_count = 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["productErrors"] == []++ attributes = data["product"]["attributes"]++ assert len(attributes) == 2+ expected_file_att_data = {+ "attribute": {"id": attribute_id, "name": page_reference_attribute.name},+ "values": [+ {+ "name": page.title,+ "slug": f"{product.id}_{page.id}",+ "file": None,+ "reference": reference,+ }+ ],+ }+ assert expected_file_att_data in attributes++ updated_webhook_mock.assert_called_once_with(product)++ page_reference_attribute.refresh_from_db()+ assert page_reference_attribute.values.count() == values_count + 1+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_update_product_with_reference_attribute_existing_value(+ updated_webhook_mock,+ staff_api_client,+ 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", page_reference_attribute.pk)+ product_type.product_attributes.add(page_reference_attribute)+ attr_value = AttributeValue.objects.create(+ attribute=page_reference_attribute,+ name=page.title,+ slug=f"{product.pk}_{page.pk}",+ )+ associate_attribute_values_to_instance(+ product, page_reference_attribute, attr_value+ )++ values_count = 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["productErrors"] == []++ attributes = data["product"]["attributes"]++ assert len(attributes) == 2+ expected_file_att_data = {+ "attribute": {"id": attribute_id, "name": page_reference_attribute.name},+ "values": [+ {+ "name": page.title,+ "slug": f"{product.id}_{page.id}",+ "file": None,+ "reference": reference,+ }+ ],+ }+ assert expected_file_att_data in attributes++ updated_webhook_mock.assert_called_once_with(product)++ page_reference_attribute.refresh_from_db()+ assert page_reference_attribute.values.count() == values_count+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_update_product_with_reference_attribute_value_not_given(+ updated_webhook_mock,+ staff_api_client,+ page_reference_attribute,+ product,+ product_type,+ permission_manage_products,+):+ # given+ query = MUTATION_UPDATE_PRODUCT++ page_reference_attribute.value_required = True+ page_reference_attribute.save(update_fields=["value_required"])++ product_id = graphene.Node.to_global_id("Product", product.pk)++ attribute_id = graphene.Node.to_global_id("Attribute", page_reference_attribute.pk)+ product_type.product_attributes.add(page_reference_attribute)++ variables = {+ "productId": product_id,+ "input": {"attributes": [{"id": attribute_id, "values": ["test"]}]},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ errors = data["productErrors"]++ assert not data["product"]+ assert len(errors) == 1+ assert errors[0]["field"] == "attributes"+ assert errors[0]["code"] == AttributeErrorCode.REQUIRED.name++ updated_webhook_mock.assert_not_called()++UPDATE_PRODUCT_SLUG_MUTATION = """mutation($id: ID!, $slug: String) {productUpdate(diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.pyindex cbbe98f253..e5f47075d4 100644--- a/saleor/graphql/product/tests/test_variant.py+++ b/saleor/graphql/product/tests/test_variant.py@@ -265,6 +265,7 @@ CREATE_VARIANT_MUTATION = """code}productVariant {+ idnameskuattributes {@@ -274,6 +275,7 @@ CREATE_VARIANT_MUTATION = """values {nameslug+ referencefile {urlcontentType@@ -539,6 +541,132 @@ def test_create_variant_with_file_attribute_no_file_url_given(updated_webhook_mock.assert_called_once_with(product)+@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_create_variant_with_reference_attribute(+ updated_webhook_mock,+ staff_api_client,+ product,+ product_type,+ page_reference_attribute,+ page_list,+ permission_manage_products,+ warehouse,+):+ 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(page_reference_attribute)+ ref_attr_id = graphene.Node.to_global_id("Attribute", page_reference_attribute.id)++ page_ref_1 = graphene.Node.to_global_id("Page", page_list[0].pk)+ page_ref_2 = graphene.Node.to_global_id("Page", page_list[1].pk)++ values_count = page_reference_attribute.values.count()++ stocks = [+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),+ "quantity": 20,+ }+ ]++ variables = {+ "productId": product_id,+ "sku": sku,+ "stocks": stocks,+ "attributes": [{"id": ref_attr_id, "references": [page_ref_1, page_ref_2]}],+ "trackInventory": True,+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)["data"]["productVariantCreate"]+ assert not content["productErrors"]+ 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"] == page_reference_attribute.slug+ expected_values = [+ {+ "slug": f"{variant_pk}_{page_list[0].pk}",+ "file": None,+ "reference": page_ref_1,+ "name": page_list[0].title,+ },+ {+ "slug": f"{variant_pk}_{page_list[1].pk}",+ "file": None,+ "reference": page_ref_2,+ "name": page_list[1].title,+ },+ ]+ 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++ page_reference_attribute.refresh_from_db()+ assert page_reference_attribute.values.count() == values_count + 2++ updated_webhook_mock.assert_called_once_with(product)+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+def test_create_variant_with_reference_attribute_no_references_given(+ updated_webhook_mock,+ staff_api_client,+ product,+ product_type,+ page_reference_attribute,+ permission_manage_products,+ warehouse,+):+ 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(page_reference_attribute)+ ref_attr_id = graphene.Node.to_global_id("Attribute", page_reference_attribute.id)++ values_count = page_reference_attribute.values.count()++ stocks = [+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),+ "quantity": 20,+ }+ ]++ variables = {+ "productId": product_id,+ "sku": sku,+ "stocks": stocks,+ "attributes": [{"id": ref_attr_id, "file": "test.jpg"}],+ "trackInventory": True,+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)["data"]["productVariantCreate"]+ errors = content["productErrors"]+ 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]++ page_reference_attribute.refresh_from_db()+ assert page_reference_attribute.values.count() == values_count++ updated_webhook_mock.assert_not_called()++def test_create_product_variant_with_negative_weight(staff_api_client, product, product_type, permission_manage_products):@@ -932,6 +1060,7 @@ QUERY_UPDATE_VARIANT_ATTRIBUTES = """urlcontentType}+ reference}}}@@ -1264,6 +1393,57 @@ def test_update_product_variant_with_file_attribute_new_value_is_not_created(assert value_data["file"]["contentType"] == existing_value.content_type+def test_update_product_variant_with_reference_attribute(+ staff_api_client,+ product,+ page,+ page_reference_attribute,+ permission_manage_products,+):+ 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(page_reference_attribute)++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ ref_attribute_id = graphene.Node.to_global_id(+ "Attribute", page_reference_attribute.pk+ )+ reference = graphene.Node.to_global_id("Page", page.pk)++ variables = {+ "id": variant_id,+ "sku": sku,+ "attributes": [{"id": ref_attribute_id, "references": [reference]}],+ }++ response = staff_api_client.post_graphql(+ QUERY_UPDATE_VARIANT_ATTRIBUTES,+ variables,+ permissions=[permission_manage_products],+ )+ 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"]+ == page_reference_attribute.slug+ )+ assert len(variant_data["attributes"][0]["values"]) == 1+ assert (+ variant_data["attributes"][0]["values"][0]["slug"] == f"{variant.pk}_{page.pk}"+ )+ assert variant_data["attributes"][0]["values"][0]["reference"] == reference++@pytest.mark.parametrize("values, message",(diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex c61a2c7421..99aac99730 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -573,6 +573,7 @@ type AttributeValue implements Node {type: AttributeValueType @deprecated(reason: "Use the `inputType` field to determine the type of attribute's value. This field will be removed after 2020-07-31.")translation(languageCode: LanguageCodeEnum!): AttributeValueTranslationinputType: AttributeInputTypeEnum+ reference: IDfile: File}@@ -605,6 +606,7 @@ input AttributeValueInput {values: [String]file: StringcontentType: String+ references: [ID!]}type AttributeValueTranslatableContent implements Node {