Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Allow to use external references for attributes in product mutations (#12935)
SzymJ66907b149076
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dc3cdfe3c3..d70b459ff3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -38,6 +38,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add `brand` optional field with brand data (initially logo image) to `Manifest`, `AppInstallation` and `App` - #12361 by @przlada- [Preview] Add `AttributeBulkTranslate` and `AttributeValueBulkTranslate` mutation - #12965 by @SzymJ- [Preview] Add `where` and `search` filtering option on `products` query - #12960 by @zedzior+- Add `externalReference` field to `AttributeValueInput`, `BulkAttributeValueInput` and `AttributeValueSelectableTypeInput` - #12823 by @SzymJ### Saleor Appsdiff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_update.pyindex 221cd839c3..d4b8a218b1 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py@@ -494,6 +494,7 @@ def test_update_attribute_slug_exists(second_attribute = Attribute.objects.get(pk=color_attribute.pk)second_attribute.pk = None+ second_attribute.external_reference = Nonesecond_attribute.slug = "second-attribute"second_attribute.save()diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.pyindex ae11ecf788..f4384b9905 100644--- a/saleor/graphql/attribute/tests/test_utils.py+++ b/saleor/graphql/attribute/tests/test_utils.py@@ -1520,6 +1520,107 @@ def test_validate_selectable_attribute_by_id_and_value(assert errors[0].code == ProductErrorCode.INVALID.value[email protected]("creation", [True, False])+def test_validate_selectable_attribute_by_external_reference(+ creation, color_attribute, product_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ dropdown=AttrValuesForSelectableFieldInput(+ external_reference=color_attribute.external_reference,+ value="new color",+ ),+ ),+ )+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert not errors++[email protected]("creation", [True, False])+def test_validate_selectable_attribute_by_id_and_external_reference(+ creation, color_attribute, product_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ dropdown=AttrValuesForSelectableFieldInput(+ id="id", external_reference="external_reference"+ ),+ ),+ )+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert len(errors) == 1+ assert errors[0].code == ProductErrorCode.INVALID.value++[email protected]("creation", [True, False])+def test_validate_selectable_attribute_by_value_and_external_reference(+ creation, color_attribute, product_type+):+ # given+ color_attribute.input_type = AttributeInputType.DROPDOWN+ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ color_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", color_attribute.pk),+ dropdown=AttrValuesForSelectableFieldInput(+ value="new color", external_reference="external_reference"+ ),+ ),+ )+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert not errors++@pytest.mark.parametrize("creation", [True, False])def test_validate_multiselect_attribute_by_id_and_value(creation, weight_attribute, product_type@@ -1627,6 +1728,42 @@ def test_validate_multiselect_attribute_duplicated_ids(assert errors[0].code == ProductErrorCode.DUPLICATED_INPUT_ITEM.value[email protected]("creation", [True, False])+def test_validate_multiselect_attribute_duplicated_external_refs(+ creation, weight_attribute, product_type+):+ # given+ weight_attribute.input_type = AttributeInputType.MULTISELECT+ weight_attribute.value_required = True+ weight_attribute.save(update_fields=["value_required", "input_type"])++ input_data = [+ (+ weight_attribute,+ AttrValuesInput(+ global_id=graphene.Node.to_global_id("Attribute", weight_attribute.pk),+ multiselect=[+ AttrValuesForSelectableFieldInput(external_reference="newWeight"),+ AttrValuesForSelectableFieldInput(external_reference="newWeight"),+ AttrValuesForSelectableFieldInput(external_reference="newWeight2"),+ ],+ ),+ ),+ ]++ # when+ errors = validate_attributes_input(+ input_data,+ product_type.product_attributes.all(),+ is_page_attributes=False,+ creation=creation,+ )++ # then+ assert len(errors) == 1+ assert errors[0].code == ProductErrorCode.DUPLICATED_INPUT_ITEM.value++@pytest.mark.parametrize("creation", [True, False])def test_validate_selectable_attribute_max_length_exceeded(creation, color_attribute, product_typediff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.pyindex 4030c9217d..787ae03c53 100644--- a/saleor/graphql/attribute/types.py+++ b/saleor/graphql/attribute/types.py@@ -20,6 +20,7 @@ from ..core.descriptions import (ADDED_IN_31,ADDED_IN_39,ADDED_IN_310,+ ADDED_IN_314,DEPRECATED_IN_3X_FIELD,)from ..core.doc_category import DOC_CATEGORY_ATTRIBUTES@@ -400,6 +401,10 @@ class AttributeInput(BaseInputObjectType):class AttributeValueSelectableTypeInput(BaseInputObjectType):id = graphene.ID(required=False, description="ID of an attribute value.")+ external_reference = graphene.String(+ required=False,+ description="External reference of an attribute value." + ADDED_IN_314,+ )value = graphene.String(required=False,description=(@@ -410,14 +415,23 @@ class AttributeValueSelectableTypeInput(BaseInputObjectType):class Meta:description = (- "Represents attribute value. If no ID provided, value will be resolved. "- + ADDED_IN_39+ "Represents attribute value.\n"+ "1. If ID is provided, then attribute value will be resolved by ID.\n"+ "2. If externalReference is provided, then attribute value will be "+ "resolved by external reference.\n"+ "3. If value is provided, then attribute value will be resolved by value. "+ "If this attribute value doesn't exist, then it will be created.\n"+ "4. If externalReference and value is provided then "+ "new attribute value will be created." + ADDED_IN_39)doc_category = DOC_CATEGORY_ATTRIBUTESclass AttributeValueInput(BaseInputObjectType):- id = graphene.ID(description="ID of the selected attribute.")+ id = graphene.ID(description="ID of the selected attribute.", required=False)+ external_reference = graphene.String(+ description="External ID of this attribute." + ADDED_IN_314, required=False+ )values = NonNullList(graphene.String,required=False,@@ -429,16 +443,16 @@ class AttributeValueInput(BaseInputObjectType):)dropdown = AttributeValueSelectableTypeInput(required=False,- description="Attribute value ID." + ADDED_IN_39,+ description="Attribute value ID or external reference." + ADDED_IN_39,)swatch = AttributeValueSelectableTypeInput(required=False,- description="Attribute value ID." + ADDED_IN_39,+ description="Attribute value ID or external reference." + ADDED_IN_39,)multiselect = NonNullList(AttributeValueSelectableTypeInput,required=False,- description="List of attribute value IDs." + ADDED_IN_39,+ description="List of attribute value IDs or external references." + ADDED_IN_39,)numeric = graphene.String(required=False,diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.pyindex 844e2c86cb..9d0fdbb367 100644--- a/saleor/graphql/attribute/utils.py+++ b/saleor/graphql/attribute/utils.py@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple, Type, Uimport graphenefrom django.core.exceptions import ValidationErrorfrom django.db.models import Q+from django.db.utils import IntegrityErrorfrom django.template.defaultfilters import truncatecharsfrom django.utils import timezonefrom django.utils.text import slugify@@ -24,6 +25,7 @@ from ...page.error_codes import PageErrorCodefrom ...product import models as product_modelsfrom ...product.error_codes import ProductErrorCodefrom ..core.utils import from_global_id_or_error, get_duplicated_values+from ..core.validators import validate_one_of_args_is_in_mutationfrom ..utils import get_nodesif TYPE_CHECKING:@@ -35,12 +37,14 @@ if TYPE_CHECKING:@dataclassclass AttrValuesForSelectableFieldInput:id: Optional[str] = None+ external_reference: Optional[str] = Nonevalue: Optional[str] = None@dataclassclass AttrValuesInput:- global_id: str+ global_id: Optional[str] = None+ external_reference: Optional[str] = Nonevalues: Optional[List[str]] = Nonedropdown: Optional[AttrValuesForSelectableFieldInput] = Noneswatch: Optional[AttrValuesForSelectableFieldInput] = None@@ -60,7 +64,7 @@ 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]]+T_ERROR_DICT = Dict[Tuple[str, str], List]EntityTypeData = namedtuple("EntityTypeData", ["model", "name_field", "value_field"])@@ -103,21 +107,29 @@ class AttributeAssignmentMixin:error_class,*,global_ids: List[str],+ external_references: Iterable[str],pks: Iterable[int],):- """Retrieve attributes nodes from given global IDs."""- qs = qs.filter(pk__in=pks)+ """Retrieve attributes nodes from given global IDs or external reference."""++ qs = qs.filter(Q(pk__in=pks) | Q(external_reference__in=external_references))nodes: List[attribute_models.Attribute] = list(qs)if not nodes:raise ValidationError(- (f"Could not resolve to a node: ids={global_ids}."),+ (+ f"Could not resolve to a node: ids={global_ids}, "+ f"external_references={external_references}."+ ),code=error_class.NOT_FOUND.value,)nodes_pk_list = set()+ nodes_external_reference_list = set()+for node in nodes:nodes_pk_list.add(node.pk)+ nodes_external_reference_list.add(node.external_reference)for pk, global_id in zip(pks, global_ids):if pk not in nodes_pk_list:@@ -126,6 +138,13 @@ class AttributeAssignmentMixin:code=error_class.NOT_FOUND.value,)+ for external_ref in external_references:+ if external_ref not in nodes_external_reference_list:+ raise ValidationError(+ f"Could not resolve {external_ref} to Attribute",+ code=error_class.NOT_FOUND.value,+ )+return nodes@classmethod@@ -161,6 +180,28 @@ class AttributeAssignmentMixin:else assignment.values.filter(**{lookup_field: value}).first())+ @classmethod+ def _create_value_instance(+ cls, attribute, attr_value, external_ref, attr_and_value_slugs_map+ ):+ try:+ slug = prepare_unique_slug(+ slugify(unidecode(attr_value)), attr_and_value_slugs_map[attribute]+ )+ value = attribute_models.AttributeValue.objects.create(+ external_reference=external_ref,+ attribute=attribute,+ name=attr_value,+ slug=slug,+ )+ except IntegrityError:+ raise ValidationError(+ "Attribute value with given externalReference already exists."+ )++ attr_and_value_slugs_map[attribute].add(slug)+ return (value,)+@classmethoddef clean_input(cls,@@ -187,18 +228,32 @@ class AttributeAssignmentMixin:# Mapping to associate the input values back to the resolved attribute nodespks = {}+ external_references_values_map = {}# Temporary storage of the passed ID for error reportingglobal_ids = []+for attribute_input in raw_input:global_id = attribute_input.pop("id", None)- if global_id is None:+ external_reference = attribute_input.pop("external_reference", None)++ try:+ validate_one_of_args_is_in_mutation(+ "id",+ global_id,+ "external_reference",+ external_reference,+ use_camel_case=True,+ )+ except ValidationError as error:raise ValidationError(- "The attribute ID is required.",+ error.message,code=error_class.REQUIRED.value,)+values = AttrValuesInput(global_id=global_id,+ external_reference=external_reference,values=attribute_input.pop("values", []),file_url=cls._clean_file_url(attribute_input.pop("file", None), error_class@@ -206,26 +261,35 @@ class AttributeAssignmentMixin:**attribute_input,)- internal_id = cls._resolve_attribute_global_id(error_class, global_id)- global_ids.append(global_id)- pks[internal_id] = values+ if global_id:+ internal_id = cls._resolve_attribute_global_id(error_class, global_id)+ global_ids.append(global_id)+ pks[internal_id] = values++ if external_reference:+ external_references_values_map[external_reference] = valuesattributes = cls._resolve_attribute_nodes(attributes_qs,error_class,global_ids=global_ids,+ external_references=external_references_values_map.keys(),pks=pks.keys(),)+attr_with_invalid_references = []cleaned_input = []+for attribute in attributes:- key = pks[attribute.pk]+ key = pks.get(attribute.pk)+ if not key:+ key = external_references_values_map[attribute.external_reference]+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:@@ -332,6 +396,14 @@ class AttributeAssignmentMixin:AttributeInputType.RICH_TEXT: cls._pre_save_rich_text_values,}clean_assignment = []+ attr_and_value_slugs_map = {}++ for attribute, _ in cleaned_input:+ if attribute not in attr_and_value_slugs_map:+ attr_and_value_slugs_map[attribute] = set(+ attribute.values.all().values_list("slug", flat=True)+ )+for attribute, attr_values in cleaned_input:is_handled_by_values_field = (attr_values.values@@ -346,7 +418,9 @@ class AttributeAssignmentMixin:attribute_values = cls._pre_save_values(attribute, attr_values)else:pre_save_func = pre_save_methods_mapping[attribute.input_type]- attribute_values = pre_save_func(instance, attribute, attr_values)+ attribute_values = pre_save_func(+ instance, attribute, attr_values, attr_and_value_slugs_map+ )associate_attribute_values_to_instance(instance, attribute, *attribute_values@@ -366,20 +440,40 @@ class AttributeAssignmentMixin:_,attribute: attribute_models.Attribute,attr_values: AttrValuesInput,+ attr_and_value_slugs_map,):if not attr_values.dropdown:return tuple()+ attr_value = attr_values.dropdown.value+ external_ref = attr_values.dropdown.external_reference++ if external_ref and attr_value:+ value = cls._create_value_instance(+ attribute, attr_value, external_ref, attr_and_value_slugs_map+ )+ return value++ if external_ref:+ value = attribute_models.AttributeValue.objects.get(+ external_reference=external_ref+ )+ if not value:+ raise ValidationError(+ "Attribute value with given externalReference can't be found"+ )+ return (value,)+if id := attr_values.dropdown.id:_, attr_value_id = from_global_id_or_error(id)- model = attribute_models.AttributeValue.objects.get(pk=attr_value_id)- if not model:+ value = attribute_models.AttributeValue.objects.get(pk=attr_value_id)+ if not value:raise ValidationError("Attribute value with given ID can't be found")- return (model,)+ return (value,)- if attr_value := attr_values.dropdown.value:- model = prepare_attribute_values(attribute, [attr_value])- return model+ if attr_value:+ value = prepare_attribute_values(attribute, [attr_value])+ return valuereturn tuple()@@ -389,10 +483,30 @@ class AttributeAssignmentMixin:_,attribute: attribute_models.Attribute,attr_values: AttrValuesInput,+ attr_and_value_slugs_map,):if not attr_values.swatch:return tuple()+ attr_value = attr_values.swatch.value+ external_ref = attr_values.swatch.external_reference++ if external_ref and attr_value:+ value = cls._create_value_instance(+ attribute, attr_value, external_ref, attr_and_value_slugs_map+ )+ return value++ if external_ref:+ value = attribute_models.AttributeValue.objects.get(+ external_reference=external_ref+ )+ if not value:+ raise ValidationError(+ "Attribute value with given externalReference can't be found"+ )+ return (value,)+if id := attr_values.swatch.id:_, attr_value_id = from_global_id_or_error(id)model = attribute_models.AttributeValue.objects.get(pk=attr_value_id)@@ -412,12 +526,31 @@ class AttributeAssignmentMixin:_,attribute: attribute_models.Attribute,attr_values_input: AttrValuesInput,+ attr_and_value_slugs_map,):if not attr_values_input.multiselect:return tuple()attribute_values: List[attribute_models.AttributeValue] = []for attr_value in attr_values_input.multiselect:+ external_ref = attr_value.external_reference++ if external_ref and attr_value.value:+ value = cls._create_value_instance(+ attribute, attr_value.value, external_ref, attr_and_value_slugs_map+ )+ return value++ if external_ref:+ value = attribute_models.AttributeValue.objects.get(+ external_reference=external_ref+ )+ if not value:+ raise ValidationError(+ "Attribute value with given externalReference can't be found"+ )+ return (value,)+if attr_value.id:_, attr_value_id = from_global_id_or_error(attr_value.id)attr_value_model = attribute_models.AttributeValue.objects.get(@@ -445,6 +578,7 @@ class AttributeAssignmentMixin:instance: T_INSTANCE,attribute: attribute_models.Attribute,attr_values: AttrValuesInput,+ attr_and_value_slugs_map,):if attr_values.values:value = attr_values.values[0]@@ -480,6 +614,7 @@ class AttributeAssignmentMixin:instance: T_INSTANCE,attribute: attribute_models.Attribute,attr_values: AttrValuesInput,+ attr_and_value_slugs_map,):if not attr_values.rich_text:return tuple()@@ -497,6 +632,7 @@ class AttributeAssignmentMixin:instance: T_INSTANCE,attribute: attribute_models.Attribute,attr_values: AttrValuesInput,+ attr_and_value_slugs_map,):if not attr_values.plain_text:return tuple()@@ -512,12 +648,13 @@ class AttributeAssignmentMixin:instance: T_INSTANCE,attribute: attribute_models.Attribute,attr_values: AttrValuesInput,+ attr_and_value_slugs_map,):if attr_values.boolean is None:return tuple()- get_or_create = attribute.values.get_or_create+boolean = bool(attr_values.boolean)- value, _ = get_or_create(+ value, _ = attribute.values.get_or_create(attribute=attribute,slug=slugify(unidecode(f"{attribute.id}_{boolean}")),defaults={@@ -533,6 +670,7 @@ class AttributeAssignmentMixin:instance: T_INSTANCE,attribute: attribute_models.Attribute,attr_values: AttrValuesInput,+ attr_and_value_slugs_map,):is_date_attr = attribute.input_type == AttributeInputType.DATEtz = timezone.utc@@ -578,6 +716,7 @@ class AttributeAssignmentMixin:instance,attribute: attribute_models.Attribute,attr_values: AttrValuesInput,+ attr_and_value_slugs_map,):"""Lazy-retrieve or create the database objects from the supplied raw values.@@ -612,6 +751,7 @@ class AttributeAssignmentMixin:instance: T_INSTANCE,attribute: attribute_models.Attribute,attr_value: AttrValuesInput,+ attr_and_value_slugs_map,):"""Create database file attribute value object from the supplied value.@@ -715,6 +855,14 @@ class AttributeInputErrors:"Attribute values cannot be assigned by both id and value.","INVALID",)+ ERROR_ID_AND_EXTERNAL_REFERENCE = (+ "Attribute values cannot be assigned by both id and external reference.",+ "INVALID",+ )+ ERROR_NO_ID_OR_EXTERNAL_REFERENCE = (+ "Attribute id or external reference has to be provided.",+ "REQUIRED",+ )# file errorsERROR_NO_FILE_GIVEN = ("Attribute file url cannot be blank.",@@ -810,16 +958,22 @@ def validate_file_attributes_input(attr_values: "AttrValuesInput",attribute_errors: T_ERROR_DICT,):- attribute_id = attr_values.global_id+ attr_identifier = attr_values.global_id or attr_values.external_reference+ if not attr_identifier:+ attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(+ attr_identifier+ )+ return+value = attr_values.file_urlif not value:if attribute.value_required:attribute_errors[AttributeInputErrors.ERROR_NO_FILE_GIVEN].append(- attribute_id+ attr_identifier)elif not value.strip():attribute_errors[AttributeInputErrors.ERROR_BLANK_FILE_VALUE].append(- attribute_id+ attr_identifier)@@ -828,12 +982,18 @@ def validate_reference_attributes_input(attr_values: "AttrValuesInput",attribute_errors: T_ERROR_DICT,):- attribute_id = attr_values.global_id+ attr_identifier = attr_values.global_id or attr_values.external_reference+ if not attr_identifier:+ attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(+ attr_identifier+ )+ return+references = attr_values.referencesif not references:if attribute.value_required:attribute_errors[AttributeInputErrors.ERROR_NO_REFERENCE_GIVEN].append(- attribute_id+ attr_identifier)@@ -842,11 +1002,17 @@ def validate_boolean_input(attr_values: "AttrValuesInput",attribute_errors: T_ERROR_DICT,):- attribute_id = attr_values.global_id+ attr_identifier = attr_values.global_id or attr_values.external_reference+ if not attr_identifier:+ attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(+ attr_identifier+ )+ return+value = attr_values.booleanif attribute.value_required and value is None:- attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(attribute_id)+ attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(attr_identifier)def validate_rich_text_attributes_input(@@ -854,11 +1020,19 @@ def validate_rich_text_attributes_input(attr_values: "AttrValuesInput",attribute_errors: T_ERROR_DICT,):- attribute_id = attr_values.global_id+ attr_identifier = attr_values.global_id or attr_values.external_reference+ if not attr_identifier:+ attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(+ attr_identifier+ )+ return+text = clean_editor_js(attr_values.rich_text or {}, to_string=True)if not text.strip() and attribute.value_required:- attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(attribute_id)+ attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(+ attr_identifier+ )def validate_plain_text_attributes_input(@@ -866,12 +1040,20 @@ def validate_plain_text_attributes_input(attr_values: "AttrValuesInput",attribute_errors: T_ERROR_DICT,):- attribute_id = attr_values.global_id+ attr_identifier = attr_values.global_id or attr_values.external_reference++ if not attr_identifier:+ attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(+ attr_identifier+ )+ returnif (not attr_values.plain_text or not attr_values.plain_text.strip()) and attribute.value_required:- attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(attribute_id)+ attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(+ attr_identifier+ )def validate_standard_attributes_input(@@ -880,24 +1062,30 @@ def validate_standard_attributes_input(attribute_errors: T_ERROR_DICT,):"""To be deprecated together with `AttributeValueInput.values` field."""- attribute_id = attr_values.global_id+ attr_identifier = attr_values.global_id or attr_values.external_reference++ if not attr_identifier:+ attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(+ attr_identifier+ )+ returnif not attr_values.values:if attribute.value_required:attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(- attribute_id+ attr_identifier)elif (attribute.input_type != AttributeInputType.MULTISELECTand len(attr_values.values) != 1):attribute_errors[AttributeInputErrors.ERROR_MORE_THAN_ONE_VALUE_GIVEN].append(- attribute_id+ attr_identifier)if attr_values.values is not None:validate_values(- attribute_id,+ attr_identifier,attribute,attr_values.values,attribute_errors,@@ -908,32 +1096,46 @@ def validate_single_selectable_field(attribute: "Attribute",attr_value: AttrValuesForSelectableFieldInput,attribute_errors: T_ERROR_DICT,- attribute_id: str,+ attr_identifier: str,):id = attr_value.idvalue = attr_value.value+ external_reference = attr_value.external_reference++ if id and external_reference:+ attribute_errors[AttributeInputErrors.ERROR_ID_AND_EXTERNAL_REFERENCE].append(+ attr_identifier+ )+ returnif id and value:- attribute_errors[AttributeInputErrors.ERROR_ID_AND_VALUE].append(attribute_id)+ attribute_errors[AttributeInputErrors.ERROR_ID_AND_VALUE].append(+ attr_identifier+ )return- if not id and not value and attribute.value_required:- attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(attribute_id)+ if not id and not external_reference and not value and attribute.value_required:+ attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(+ attr_identifier+ )returnif value:max_length = attribute.values.model.name.field.max_length # type: ignoreif not value.strip():attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(- attribute_id+ attr_identifier)elif len(value) > max_length:- attribute_errors[AttributeInputErrors.ERROR_MAX_LENGTH].append(attribute_id)+ attribute_errors[AttributeInputErrors.ERROR_MAX_LENGTH].append(+ attr_identifier+ )- if id:- if not id.strip():+ value_identifier = id or external_reference+ if value_identifier:+ if not value_identifier.strip():attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(- attribute_id+ attr_identifier)@@ -942,18 +1144,24 @@ def validate_dropdown_input(attr_values: "AttrValuesInput",attribute_errors: T_ERROR_DICT,):- attribute_id = attr_values.global_id+ attr_identifier = attr_values.global_id or attr_values.external_reference+ if not attr_identifier:+ attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(+ attr_identifier+ )+ return+if not attr_values.dropdown:if attribute.value_required:attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(- attribute_id+ attr_identifier)else:validate_single_selectable_field(attribute,attr_values.dropdown,attribute_errors,- attribute_id,+ attr_identifier,)@@ -962,18 +1170,24 @@ def validate_swatch_input(attr_values: "AttrValuesInput",attribute_errors: T_ERROR_DICT,):- attribute_id = attr_values.global_id+ attr_identifier = attr_values.global_id or attr_values.external_reference+ if not attr_identifier:+ attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(+ attr_identifier+ )+ return+if not attr_values.swatch:if attribute.value_required:attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(- attribute_id+ attr_identifier)else:validate_single_selectable_field(attribute,attr_values.swatch,attribute_errors,- attribute_id,+ attr_identifier,)@@ -982,32 +1196,45 @@ def validate_multiselect_input(attr_values: "AttrValuesInput",attribute_errors: T_ERROR_DICT,):- attribute_id = attr_values.global_id+ attr_identifier = attr_values.global_id or attr_values.external_reference+ if not attr_identifier:+ attribute_errors[AttributeInputErrors.ERROR_NO_ID_OR_EXTERNAL_REFERENCE].append(+ attr_identifier+ )+ return+multi_values = attr_values.multiselectif not multi_values:if attribute.value_required:attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(- attribute_id+ attr_identifier)else:ids = [value.id for value in multi_values if value.id is not None]values = [value.value for value in multi_values if value.value is not None]-+ external_refs = [+ value.external_reference+ for value in multi_values+ if value.external_reference is not None+ ]if ids and values:attribute_errors[AttributeInputErrors.ERROR_ID_AND_VALUE].append(- attribute_id+ attr_identifier)return-- if not ids and not values and attribute.value_required:+ if not ids and not external_refs and not values and attribute.value_required:attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(- attribute_id+ attr_identifier)return- if len(ids) > len(set(ids)) or len(values) > len(set(values)):+ if (+ len(ids) > len(set(ids))+ or len(values) > len(set(values))+ or len(external_refs) > len(set(external_refs))+ ):attribute_errors[AttributeInputErrors.ERROR_DUPLICATED_VALUES].append(- attribute_id+ attr_identifier)return@@ -1016,7 +1243,7 @@ def validate_multiselect_input(attribute,attr_value,attribute_errors,- attribute_id,+ attr_identifier,)@@ -1067,7 +1294,7 @@ def validate_date_time_input(def validate_values(- attribute_id: str,+ attr_identifier: str,attribute: "Attribute",values: list,attribute_errors: T_ERROR_DICT,@@ -1077,12 +1304,12 @@ def validate_values(is_numeric = attribute.input_type == AttributeInputType.NUMERICif get_duplicated_values(values):attribute_errors[AttributeInputErrors.ERROR_DUPLICATED_VALUES].append(- attribute_id+ attr_identifier)for value in values:if value is None or (not is_numeric and not value.strip()):attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(- attribute_id+ attr_identifier)elif is_numeric:try:@@ -1090,9 +1317,11 @@ def validate_values(except ValueError:attribute_errors[AttributeInputErrors.ERROR_NUMERIC_VALUE_REQUIRED- ].append(attribute_id)+ ].append(attr_identifier)elif len(value) > name_field.max_length:- attribute_errors[AttributeInputErrors.ERROR_MAX_LENGTH].append(attribute_id)+ attribute_errors[AttributeInputErrors.ERROR_MAX_LENGTH].append(+ attr_identifier+ )def validate_required_attributes(diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.pyindex 12ab149977..d852cc27f8 100644--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py@@ -463,6 +463,10 @@ class ProductBulkCreate(BaseMutation):graphene.Node.to_global_id("Attribute", variant_attribute.id)for variant_attribute in variant_attributes}+ variant_attributes_external_refs = {+ variant_attribute.external_reference+ for variant_attribute in variant_attributes+ }for index, variant_data in enumerate(variant_inputs):variant_data["product_type"] = product_type@@ -474,6 +478,7 @@ class ProductBulkCreate(BaseMutation):variant_attributes,[],variant_attributes_ids,+ variant_attributes_external_refs,duplicated_sku,variant_index_error_map,index,diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.pyindex 4e536c688a..e8d7a05f6d 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py@@ -24,6 +24,7 @@ from ...channel import ChannelContextfrom ...core.descriptions import (ADDED_IN_311,ADDED_IN_312,+ ADDED_IN_314,DEPRECATED_IN_3X_FIELD,PREVIEW_FEATURE,)@@ -48,10 +49,7 @@ from ...core.validators import validate_price_precisionfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..mutations.channels import ProductVariantChannelListingAddInputfrom ..mutations.product.product_create import StockInput-from ..mutations.product_variant.product_variant_create import (- ProductVariantCreate,- ProductVariantInput,-)+from ..mutations.product_variant.product_variant_create import ProductVariantInputfrom ..types import ProductVariantfrom ..utils import clean_variant_sku, get_used_variants_attribute_values@@ -124,7 +122,10 @@ class ProductVariantBulkResult(BaseObjectType):class BulkAttributeValueInput(BaseInputObjectType):- id = graphene.ID(description="ID of the selected attribute.")+ id = graphene.ID(description="ID of the selected attribute.", required=False)+ external_reference = graphene.String(+ description="External ID of this attribute." + ADDED_IN_314, required=False+ )values = NonNullList(graphene.String,required=False,@@ -274,6 +275,7 @@ class ProductVariantBulkCreate(BaseMutation):product_type,variant_attributes,variant_attributes_ids,+ variant_attributes_external_refs,used_attribute_values,errors,variant_index,@@ -281,8 +283,17 @@ class ProductVariantBulkCreate(BaseMutation):):attributes_errors_count = 0if attributes_input := cleaned_input.get("attributes"):- attributes_ids = {attr["id"] for attr in attributes_input or []}+ attributes_ids = {+ attr["id"] for attr in attributes_input if attr.get("id") or []+ }+ attrs_external_refs = {+ attr["external_reference"]+ for attr in attributes_input+ if attr.get("external_reference") or []+ }invalid_attributes = attributes_ids - variant_attributes_ids+ invalid_attributes |= attrs_external_refs - variant_attributes_external_refs+if len(invalid_attributes) > 0:message = "Given attributes are not a variant attributes."code = ProductVariantBulkErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.value@@ -313,9 +324,6 @@ class ProductVariantBulkCreate(BaseMutation):cleaned_attributes = AttributeAssignmentMixin.clean_input(attributes_input, variant_attributes)- ProductVariantCreate.validate_duplicated_attribute_values(- cleaned_attributes, used_attribute_values, None- )cleaned_input["attributes"] = cleaned_attributesexcept ValidationError as exc:for error in exc.error_list:@@ -689,6 +697,7 @@ class ProductVariantBulkCreate(BaseMutation):variant_attributes,used_attribute_values,variant_attributes_ids,+ variant_attributes_external_refs,duplicated_sku,index_error_map,index,@@ -719,6 +728,7 @@ class ProductVariantBulkCreate(BaseMutation):variant_data["product_type"],variant_attributes,variant_attributes_ids,+ variant_attributes_external_refs,used_attribute_values,errors,index,@@ -771,6 +781,10 @@ class ProductVariantBulkCreate(BaseMutation):graphene.Node.to_global_id("Attribute", variant_attribute.id)for variant_attribute in variant_attributes}+ variant_attributes_external_refs = {+ variant_attribute.external_reference+ for variant_attribute in variant_attributes+ }used_attribute_values = get_used_variants_attribute_values(product)duplicated_sku = get_duplicated_values(@@ -789,6 +803,7 @@ class ProductVariantBulkCreate(BaseMutation):variant_attributes,used_attribute_values,variant_attributes_ids,+ variant_attributes_external_refs,duplicated_sku,index_error_map,index,diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.pyindex 0a52ab5ce8..cf5be6e9bc 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py@@ -349,6 +349,7 @@ class ProductVariantBulkUpdate(BaseMutation):variant_attributes,used_attribute_values,variant_attributes_ids,+ variant_attributes_external_refs,duplicated_sku,index_error_map,index,@@ -378,6 +379,7 @@ class ProductVariantBulkUpdate(BaseMutation):variant_data["product_type"],variant_attributes,variant_attributes_ids,+ variant_attributes_external_refs,used_attribute_values,None,index,@@ -452,6 +454,10 @@ class ProductVariantBulkUpdate(BaseMutation):graphene.Node.to_global_id("Attribute", variant_attribute.id)for variant_attribute in variant_attributes}+ variant_attributes_external_refs = {+ variant_attribute.external_reference+ for variant_attribute in variant_attributes+ }duplicated_sku = get_duplicated_values([variant.sku for variant in variants if variant.sku])@@ -484,6 +490,7 @@ class ProductVariantBulkUpdate(BaseMutation):variant_attributes,used_attribute_values,variant_attributes_ids,+ variant_attributes_external_refs,duplicated_sku,index_error_map,index,diff --git a/saleor/graphql/product/tests/deprecated/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/deprecated/test_product_variant_bulk_create.pyindex 9a801fcf60..9d6c5f47f3 100644--- a/saleor/graphql/product/tests/deprecated/test_product_variant_bulk_create.py+++ b/saleor/graphql/product/tests/deprecated/test_product_variant_bulk_create.py@@ -1040,77 +1040,6 @@ def test_product_variant_bulk_create_many_errors(assert product_variant_count == ProductVariant.objects.count()-def test_product_variant_bulk_create_two_variants_duplicated_attribute_value(- staff_api_client,- product_with_variant_with_two_attributes,- color_attribute,- size_attribute,- permission_manage_products,-):- product = product_with_variant_with_two_attributes- product_variant_count = ProductVariant.objects.count()- product_id = graphene.Node.to_global_id("Product", product.pk)- color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)- size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.id)- variants = [- {- "sku": str(uuid4())[:12],- "attributes": [- {"id": color_attribute_id, "values": ["red"]},- {"id": size_attribute_id, "values": ["small"]},- ],- }- ]- variables = {"productId": product_id, "variants": variants}- staff_api_client.user.user_permissions.add(permission_manage_products)- response = staff_api_client.post_graphql(- PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables- )- content = get_graphql_content(response)- data = content["data"]["productVariantBulkCreate"]- assert len(data["errors"]) == 1- error = data["errors"][0]- assert error["field"] == "attributes"- assert error["code"] == ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.name- assert error["index"] == 0- assert product_variant_count == ProductVariant.objects.count()---def test_product_variant_bulk_create_two_variants_duplicated_attribute_value_in_input(- staff_api_client,- product_with_variant_with_two_attributes,- permission_manage_products,- color_attribute,- size_attribute,-):- product = product_with_variant_with_two_attributes- product_id = graphene.Node.to_global_id("Product", product.pk)- product_variant_count = ProductVariant.objects.count()- color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)- size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.id)- attributes = [- {"id": color_attribute_id, "values": [color_attribute.values.last().slug]},- {"id": size_attribute_id, "values": [size_attribute.values.last().slug]},- ]- variants = [- {"sku": str(uuid4())[:12], "attributes": attributes},- {"sku": str(uuid4())[:12], "attributes": attributes},- ]- variables = {"productId": product_id, "variants": variants}- staff_api_client.user.user_permissions.add(permission_manage_products)- response = staff_api_client.post_graphql(- PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables- )- content = get_graphql_content(response)- data = content["data"]["productVariantBulkCreate"]- assert len(data["errors"]) == 1- error = data["errors"][0]- assert error["field"] == "attributes"- assert error["code"] == ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.name- assert error["index"] == 1- assert product_variant_count == ProductVariant.objects.count()--def test_product_variant_bulk_create_two_variants_duplicated_one_attribute_value(staff_api_client,product_with_variant_with_two_attributes,diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.pyindex 8c94ce2c70..9f7533b274 100644--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py@@ -570,7 +570,10 @@ def test_product_bulk_create_with_attributes("taxCode": product_tax_rate,"weight": 2,"attributes": [- {"id": color_attr_id, "values": [color_value_name]},+ {+ "externalReference": color_attr.external_reference,+ "values": [color_value_name],+ },{"id": size_attr_id, "values": [non_existent_attr_value]},],},@@ -619,6 +622,214 @@ def test_product_bulk_create_with_attributes(assert first_attribute_assignment.values.count() == 1+def test_product_bulk_create_with_attributes_using_external_refs(+ staff_api_client,+ product_type,+ category,+ size_attribute,+ description_json,+ permission_manage_products,+ media_root,+ channel_USD,+):+ # given+ description_json = json.dumps(description_json)+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)+ category_id = graphene.Node.to_global_id("Category", category.pk)++ product_name_1 = "test name 1"+ base_product_slug = "product-test-slug"+ product_charge_taxes = True+ product_tax_rate = "STANDARD"++ # Default attribute defined in product_type fixture+ color_attr = product_type.product_attributes.get(name="Color")+ color_value_external_reference = color_attr.values.first().external_reference++ # Add second attribute+ product_type.product_attributes.add(size_attribute)+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.id)+ non_existent_attr_value = "The cake is a lie"++ products = [+ {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name_1,+ "slug": f"{base_product_slug}-1",+ "description": description_json,+ "chargeTaxes": product_charge_taxes,+ "taxCode": product_tax_rate,+ "weight": 2,+ "attributes": [+ {+ "externalReference": color_attr.external_reference,+ "dropdown": {"externalReference": color_value_external_reference},+ },+ {"id": size_attr_id, "values": [non_existent_attr_value]},+ ],+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}+ )+ content = get_graphql_content(response)+ data = content["data"]["productBulkCreate"]++ # then+ products = Product.objects.all()++ assert not data["results"][0]["errors"]+ assert data["count"] == 1+ assert (+ data["results"][0]["product"]["attributes"][0]["attribute"]["slug"]+ == color_attr.slug+ )++ for product in products:+ first_attribute_assignment = product.attributes.first()+ assert product.attributes.count() == 2+ assert first_attribute_assignment.attribute == color_attr+ assert first_attribute_assignment.values.count() == 1+++def test_product_bulk_create_with_attributes_and_create_new_value_with_external_ref(+ staff_api_client,+ product_type,+ category,+ size_attribute,+ description_json,+ permission_manage_products,+ media_root,+ channel_USD,+):+ # given+ description_json = json.dumps(description_json)+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)+ category_id = graphene.Node.to_global_id("Category", category.pk)++ product_name_1 = "test name 1"+ base_product_slug = "product-test-slug"+ product_charge_taxes = True+ product_tax_rate = "STANDARD"++ # Default attribute defined in product_type fixture+ color_attr = product_type.product_attributes.get(name="Color")+ color_attr_values_count = color_attr.values.count()+ color_value_external_reference = color_attr.values.first().external_reference++ new_value = "NewTestValue"+ new_external_ref = color_value_external_reference + "New"+ products = [+ {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name_1,+ "slug": f"{base_product_slug}-1",+ "description": description_json,+ "chargeTaxes": product_charge_taxes,+ "taxCode": product_tax_rate,+ "weight": 2,+ "attributes": [+ {+ "externalReference": color_attr.external_reference,+ "dropdown": {+ "externalReference": new_external_ref,+ "value": new_value,+ },+ },+ ],+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}+ )+ content = get_graphql_content(response)+ data = content["data"]["productBulkCreate"]++ # then+ product = Product.objects.last()++ assert not data["results"][0]["errors"]+ assert data["count"] == 1+ assert (+ data["results"][0]["product"]["attributes"][0]["attribute"]["slug"]+ == color_attr.slug+ )+ assert color_attr.values.count() == color_attr_values_count + 1+ first_attribute_assignment = product.attributes.first()+ assert product.attributes.count() == 1+ assert first_attribute_assignment.attribute == color_attr+ assert first_attribute_assignment.values.count() == 1+++def test_product_bulk_create_return_error_when_attribute_id_and_external_ref_provided(+ staff_api_client,+ product_type,+ category,+ description_json,+ permission_manage_products,+ media_root,+ channel_USD,+):+ # given+ description_json = json.dumps(description_json)+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)+ category_id = graphene.Node.to_global_id("Category", category.pk)++ product_name_1 = "test name 1"+ base_product_slug = "product-test-slug"+ product_charge_taxes = True+ product_tax_rate = "STANDARD"++ # Default attribute defined in product_type fixture+ color_attr = product_type.product_attributes.get(name="Color")+ color_value_external_reference = color_attr.values.first().external_reference+ color_attr_id = graphene.Node.to_global_id("Attribute", color_attr.id)++ products = [+ {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name_1,+ "slug": f"{base_product_slug}-1",+ "description": description_json,+ "chargeTaxes": product_charge_taxes,+ "taxCode": product_tax_rate,+ "weight": 2,+ "attributes": [+ {+ "id": color_attr_id,+ "externalReference": color_attr.external_reference,+ "dropdown": {"externalReference": color_value_external_reference},+ }+ ],+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}+ )+ content = get_graphql_content(response)+ data = content["data"]["productBulkCreate"]++ # then+ assert data["results"][0]["errors"]+ error = data["results"][0]["errors"][0]+ assert error["path"] == "attributes"+ assert error["message"] == (+ "Argument 'id' cannot be combined with 'externalReference'"+ )++def test_product_bulk_create_with_meta_data(staff_api_client,product_type,diff --git a/saleor/graphql/product/tests/mutations/test_product_create.py b/saleor/graphql/product/tests/mutations/test_product_create.pyindex 3751286a42..7abe0a4a04 100644--- a/saleor/graphql/product/tests/mutations/test_product_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_create.py@@ -268,6 +268,181 @@ def test_create_product_description_plaintext(assert product.description_plaintext == description+def test_create_product_with_using_attribute_external_ref(+ staff_api_client,+ product_type,+ category,+ color_attribute,+ permission_manage_products,+):+ # given+ 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"++ # test creating root product+ variables = {+ "input": {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name,+ "slug": product_slug,+ "attributes": [+ {+ "externalReference": color_attribute.external_reference,+ "dropdown": {"value": "newColor"},+ }+ ],+ }+ }++ # when+ response = staff_api_client.post_graphql(+ CREATE_PRODUCT_MUTATION, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ data = content["data"]["productCreate"]++ # then+ assert data["errors"] == []+ assert data["product"]["name"] == product_name+ assert data["product"]["slug"] == product_slug++ expected_attributes_data = [+ {+ "attribute": {"slug": "color"},+ "values": [+ {+ "slug": "newcolor",+ "name": "newColor",+ "reference": None,+ "richText": None,+ "plainText": None,+ "file": None,+ "boolean": None,+ "date": None,+ "dateTime": None,+ }+ ],+ }+ ]++ for attr_data in data["product"]["attributes"]:+ assert attr_data in expected_attributes_data+++def test_create_product_with_using_attribute_id_and_external_ref(+ staff_api_client,+ product_type,+ category,+ color_attribute,+ permission_manage_products,+):+ # given+ 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"++ # test creating root product+ variables = {+ "input": {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name,+ "slug": product_slug,+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),+ "externalReference": color_attribute.external_reference,+ "dropdown": {"value": "newColor"},+ }+ ],+ }+ }++ # when+ response = staff_api_client.post_graphql(+ CREATE_PRODUCT_MUTATION, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ data = content["data"]["productCreate"]++ # then+ assert data["errors"]+ assert data["errors"][0]["field"] == "attributes"+ assert data["errors"][0]["code"] == ProductErrorCode.REQUIRED.name+ assert data["errors"][0]["message"] == (+ "Argument 'id' cannot be combined with 'externalReference'"+ )+++def test_create_product_with_using_attribute_and_value_external_ref(+ staff_api_client,+ product_type,+ category,+ color_attribute,+ permission_manage_products,+):+ # given+ 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"++ attr_value = color_attribute.values.first()++ # test creating root product+ variables = {+ "input": {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name,+ "slug": product_slug,+ "attributes": [+ {+ "externalReference": color_attribute.external_reference,+ "dropdown": {"externalReference": attr_value.external_reference},+ }+ ],+ }+ }+ # when+ response = staff_api_client.post_graphql(+ CREATE_PRODUCT_MUTATION, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ data = content["data"]["productCreate"]++ # then+ assert data["errors"] == []+ assert data["product"]["name"] == product_name+ assert data["product"]["slug"] == product_slug++ expected_attributes_data = [+ {+ "attribute": {"slug": "color"},+ "values": [+ {+ "slug": attr_value.slug,+ "name": attr_value.name,+ "reference": None,+ "richText": None,+ "plainText": None,+ "file": None,+ "boolean": None,+ "date": None,+ "dateTime": None,+ }+ ],+ }+ ]++ for attr_data in data["product"]["attributes"]:+ assert attr_data in expected_attributes_data++def test_create_product_with_rich_text_attribute(staff_api_client,product_type,diff --git a/saleor/graphql/product/tests/mutations/test_product_update.py b/saleor/graphql/product/tests/mutations/test_product_update.pyindex f0bc15eb8e..3e9fa00e82 100644--- a/saleor/graphql/product/tests/mutations/test_product_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_update.py@@ -1512,7 +1512,7 @@ def test_update_product_with_variant_reference_attribute_value(assert product_type_variant_reference_attribute.values.count() == values_count + 1-def test_update_product_with_no_id(+def test_update_product_with_attribute_without_id_or_external_ref(staff_api_client, product, permission_manage_products, color_attribute):"""Ensure only supplying values triggers a validation error."""diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.pyindex d9ddb81000..887c034932 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py@@ -38,6 +38,9 @@ PRODUCT_VARIANT_BULK_CREATE_MUTATION = """nameskuattributes{+ attribute {+ slug+ }values {nameslug@@ -111,20 +114,27 @@ def test_product_variant_bulk_create_by_name(product_id = graphene.Node.to_global_id("Product", product.pk)attribut_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)attribute_value = size_attribute.values.last()- sku = str(uuid4())[:12]- name = "new-variant-name"+ sku1 = str(uuid4())[:12]+ sku2 = str(uuid4())[:12]+ name1 = "new-variant-name"+ name2 = "new-variant-name"metadata_key = "md key"metadata_value = "md value"variants = [{- "sku": sku,+ "sku": sku1,"weight": 2.5,"trackInventory": True,- "name": name,+ "name": name1,"attributes": [{"id": attribut_id, "values": [attribute_value.name]}],"metadata": [{"key": metadata_key, "value": metadata_value}],- }+ },+ {+ "sku": sku2,+ "name": name2,+ "attributes": [{"id": attribut_id, "values": [attribute_value.name]}],+ },]variables = {"productId": product_id, "variants": variants}@@ -140,18 +150,19 @@ def test_product_variant_bulk_create_by_name(# thenassert not data["results"][0]["errors"]- assert data["count"] == 1+ assert not data["results"][1]["errors"]+ assert data["count"] == 2variant_data = data["results"][0]["productVariant"]- assert variant_data["name"] == name+ assert variant_data["name"] == name1assert variant_data["metadata"][0]["key"] == metadata_keyassert variant_data["metadata"][0]["value"] == metadata_value- assert product_variant_count + 1 == ProductVariant.objects.count()+ assert product_variant_count + 2 == ProductVariant.objects.count()assert attribute_value_count == size_attribute.values.count()- product_variant = ProductVariant.objects.get(sku=sku)+ product_variant = ProductVariant.objects.get(sku=sku1)product.refresh_from_db()assert product.default_variant == product_variantassert product_variant_created_webhook_mock.call_count == data["count"]- update_product_discounted_price_task_mock.assert_called_once_with(product.id)+ update_product_discounted_price_task_mock.call_count == data["count"]@patch("saleor.product.tasks.update_product_discounted_price_task.delay")@@ -204,6 +215,168 @@ def test_product_variant_bulk_create_by_attribute_id(update_product_discounted_price_task_mock.assert_called_once_with(product.id)+def test_product_variant_bulk_create_by_attribute_external_ref(+ staff_api_client,+ product,+ color_attribute,+ permission_manage_products,+):+ # given+ product_variant_count = ProductVariant.objects.count()+ product.product_type.variant_attributes.add(color_attribute)++ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_value = color_attribute.values.last()+ attribute_external_ref = color_attribute.external_reference+ sku = str(uuid4())[:12]+ variants = [+ {+ "sku": sku,+ "weight": 2.5,+ "trackInventory": True,+ "attributes": [+ {+ "externalReference": attribute_external_ref,+ "dropdown": {+ "externalReference": attribute_value.external_reference+ },+ }+ ],+ }+ ]++ variables = {"productId": product_id, "variants": variants}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantBulkCreate"]++ # then+ assert not data["results"][0]["errors"]+ assert data["count"] == 1+ assert product_variant_count + 1 == ProductVariant.objects.count()+ assert (+ data["results"][0]["productVariant"]["attributes"][1]["attribute"]["slug"]+ == color_attribute.slug+ )+ assert (+ data["results"][0]["productVariant"]["attributes"][1]["values"][0]["slug"]+ == attribute_value.slug+ )+++def test_product_variant_bulk_create_return_error_when_attribute_external_ref_and_id(+ staff_api_client,+ product,+ color_attribute,+ permission_manage_products,+):+ # given+ product.product_type.variant_attributes.add(color_attribute)+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_value = color_attribute.values.last()+ attribute_external_ref = color_attribute.external_reference+ sku = str(uuid4())[:12]+ variants = [+ {+ "sku": sku,+ "weight": 2.5,+ "trackInventory": True,+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),+ "externalReference": attribute_external_ref,+ "dropdown": {+ "externalReference": attribute_value.external_reference+ },+ }+ ],+ }+ ]++ variables = {"productId": product_id, "variants": variants}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantBulkCreate"]++ # then+ assert data["results"][0]["errors"]+ error = data["results"][0]["errors"][0]+ assert error["path"] == "attributes"+ assert error["message"] == (+ "Argument 'id' cannot be combined with 'externalReference'"+ )+++def test_product_variant_bulk_create_will_create_new_attr_value_and_external_reference(+ staff_api_client,+ product,+ color_attribute,+ permission_manage_products,+):+ # given+ product.product_type.variant_attributes.add(color_attribute)+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_value = color_attribute.values.last()+ attribute_external_ref = color_attribute.external_reference+ sku = str(uuid4())[:12]+ color_attr_values_count = color_attribute.values.count()+ new_value = "NewColorValue"+ new_value_external_ref = attribute_value.external_reference + "New"++ variants = [+ {+ "sku": sku,+ "weight": 2.5,+ "trackInventory": True,+ "attributes": [+ {+ "externalReference": attribute_external_ref,+ "dropdown": {+ "externalReference": new_value_external_ref,+ "value": new_value,+ },+ }+ ],+ }+ ]++ variables = {"productId": product_id, "variants": variants}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantBulkCreate"]++ # then+ assert not data["results"][0]["errors"]+ assert data["count"] == 1+ assert color_attribute.values.count() == color_attr_values_count + 1+ assert (+ data["results"][0]["productVariant"]["attributes"][1]["attribute"]["slug"]+ == color_attribute.slug+ )+ assert (+ data["results"][0]["productVariant"]["attributes"][1]["values"][0]["name"]+ == new_value+ )++def test_product_variant_bulk_create_with_swatch_attribute(staff_api_client, product, swatch_attribute, permission_manage_products):@@ -2026,87 +2199,6 @@ def test_product_variant_bulk_create_many_errors_with_reject_failed_rows(assert product_variant_count + 1 == ProductVariant.objects.count()-def test_product_variant_bulk_create_two_variants_duplicated_attribute_value(- staff_api_client,- product_with_variant_with_two_attributes,- color_attribute,- size_attribute,- permission_manage_products,-):- # given- product = product_with_variant_with_two_attributes- product_variant_count = ProductVariant.objects.count()- product_id = graphene.Node.to_global_id("Product", product.pk)- color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)- size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.id)- variants = [- {- "sku": str(uuid4())[:12],- "attributes": [- {"id": color_attribute_id, "values": ["red"]},- {"id": size_attribute_id, "values": ["small"]},- ],- }- ]- variables = {"productId": product_id, "variants": variants}-- # when- staff_api_client.user.user_permissions.add(permission_manage_products)- response = staff_api_client.post_graphql(- PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables- )- content = get_graphql_content(response)- data = content["data"]["productVariantBulkCreate"]-- # then- input_errors = data["results"][0]["errors"]- assert len(input_errors) == 1- error = input_errors[0]- assert error["field"] == "attributes"- assert error["code"] == ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.name- assert product_variant_count == ProductVariant.objects.count()---def test_product_variant_bulk_create_two_variants_duplicated_attribute_value_in_input(- staff_api_client,- product_with_variant_with_two_attributes,- permission_manage_products,- color_attribute,- size_attribute,-):- # given- product = product_with_variant_with_two_attributes- product_id = graphene.Node.to_global_id("Product", product.pk)- product_variant_count = ProductVariant.objects.count()- color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)- size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.id)- attributes = [- {"id": color_attribute_id, "values": [color_attribute.values.last().slug]},- {"id": size_attribute_id, "values": [size_attribute.values.last().slug]},- ]- variants = [- {"sku": str(uuid4())[:12], "attributes": attributes},- {"sku": str(uuid4())[:12], "attributes": attributes},- ]- variables = {"productId": product_id, "variants": variants}-- # when- staff_api_client.user.user_permissions.add(permission_manage_products)- response = staff_api_client.post_graphql(- PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables- )- content = get_graphql_content(response)- data = content["data"]["productVariantBulkCreate"]-- # then- input_2_errors = data["results"][1]["errors"]- assert len(input_2_errors) == 1- error = input_2_errors[0]- assert error["field"] == "attributes"- assert error["code"] == ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.name- assert product_variant_count == ProductVariant.objects.count()--def test_product_variant_bulk_create_two_variants_duplicated_one_attribute_value(staff_api_client,product_with_variant_with_two_attributes,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 572f0d88ca..239d5d5c72 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -19363,27 +19363,34 @@ input AttributeValueInput @doc(category: "Attributes") {"""ID of the selected attribute."""id: ID+ """+ External ID of this attribute.++ Added in Saleor 3.14.+ """+ externalReference: String+"""The value or slug of an attribute to resolve. If the passed value is non-existent, it will be created. This field will be removed in Saleor 4.0."""values: [String!]"""- Attribute value ID.+ Attribute value ID or external reference.Added in Saleor 3.9."""dropdown: AttributeValueSelectableTypeInput"""- Attribute value ID.+ Attribute value ID or external reference.Added in Saleor 3.9."""swatch: AttributeValueSelectableTypeInput"""- List of attribute value IDs.+ List of attribute value IDs or external references.Added in Saleor 3.9."""@@ -19422,7 +19429,11 @@ input AttributeValueInput @doc(category: "Attributes") {}"""-Represents attribute value. If no ID provided, value will be resolved.+Represents attribute value.+1. If ID is provided, then attribute value will be resolved by ID.+2. If externalReference is provided, then attribute value will be resolved by external reference.+3. If value is provided, then attribute value will be resolved by value. If this attribute value doesn't exist, then it will be created.+4. If externalReference and value is provided then new attribute value will be created.Added in Saleor 3.9."""@@ -19430,6 +19441,13 @@ input AttributeValueSelectableTypeInput @doc(category: "Attributes") {"""ID of an attribute value."""id: ID+ """+ External reference of an attribute value.++ Added in Saleor 3.14.+ """+ externalReference: String+"""The value or slug of an attribute to resolve. If the passed value is non-existent, it will be created."""@@ -19689,6 +19707,13 @@ input BulkAttributeValueInput @doc(category: "Products") {"""ID of the selected attribute."""id: ID+ """+ External ID of this attribute.++ Added in Saleor 3.14.+ """+ externalReference: String+"""The value or slug of an attribute to resolve. If the passed value is non-existent, it will be created.This field will be removed in Saleor 4.0."""diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 16befc3677..640f929692 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -1360,6 +1360,7 @@ def shipping_method_channel_PLN(shipping_zone, channel_PLN):@pytest.fixturedef color_attribute(db):attribute = Attribute.objects.create(+ external_reference="colorAttributeExternalReference",slug="color",name="Color",type=AttributeType.PRODUCT_TYPE,@@ -1367,8 +1368,18 @@ def color_attribute(db):filterable_in_dashboard=True,available_in_grid=True,)- AttributeValue.objects.create(attribute=attribute, name="Red", slug="red")- AttributeValue.objects.create(attribute=attribute, name="Blue", slug="blue")+ AttributeValue.objects.create(+ external_reference="colorAttributeValue1ExternalReference",+ attribute=attribute,+ name="Red",+ slug="red",+ )+ AttributeValue.objects.create(+ external_reference="colorAttributeValue2ExternalReference",+ attribute=attribute,+ name="Blue",+ slug="blue",+ )return attribute@@ -1684,6 +1695,7 @@ def pink_attribute_value(color_attribute): # pylint: disable=W0613@pytest.fixturedef size_attribute(db): # pylint: disable=W0613attribute = Attribute.objects.create(+ external_reference="sizeAttributeExternalReference",slug="size",name="Size",type=AttributeType.PRODUCT_TYPE,