Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add AttributeBulkUpdate mutation (#13532)
SzymJ77eecc7a719b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ac906eaf9d..a05f607a42 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -85,6 +85,9 @@ Shipping methods can be removed by the user after it has been assigned to a chec- `checkoutShippingAddressUpdate`, `checkoutBillingAddressUpdate`, `shopAddressUpdate`, `warehouseUpdate`- Add `metadata` to `AddressInput` field- Add support for unhandled field `Shop.trackInventoryByDefault` for `productVariantCreate` and `productVariantBulkCreate` - #13492 by @Smit-Parmar+- - Add `AttributeBulkUpdate` mutation - #13532 by @SzymJ++### Saleor Apps- Introduce `Saleor-Schema-Version` HTTP header in app manifest fetching and app installation handshake requests. - #13075 by @przladadiff --git a/saleor/attribute/error_codes.py b/saleor/attribute/error_codes.pyindex ce99f8264c..724f76ed06 100644--- a/saleor/attribute/error_codes.py+++ b/saleor/attribute/error_codes.py@@ -20,3 +20,15 @@ class AttributeBulkCreateErrorCode(Enum):UNIQUE = "unique"DUPLICATED_INPUT_ITEM = "duplicated_input_item"MAX_LENGTH = "max_length"+++class AttributeBulkUpdateErrorCode(Enum):+ ALREADY_EXISTS = "already_exists"+ BLANK = "blank"+ GRAPHQL_ERROR = "graphql_error"+ INVALID = "invalid"+ NOT_FOUND = "not_found"+ REQUIRED = "required"+ UNIQUE = "unique"+ DUPLICATED_INPUT_ITEM = "duplicated_input_item"+ MAX_LENGTH = "max_length"diff --git a/saleor/graphql/attribute/mutations/__init__.py b/saleor/graphql/attribute/mutations/__init__.pyindex 6a0b5b9264..1b8ce5f784 100644--- a/saleor/graphql/attribute/mutations/__init__.py+++ b/saleor/graphql/attribute/mutations/__init__.py@@ -1,4 +1,5 @@from .attribute_bulk_create import AttributeBulkCreate+from .attribute_bulk_update import AttributeBulkUpdatefrom .attribute_create import AttributeCreatefrom .attribute_delete import AttributeDeletefrom .attribute_reorder_values import AttributeReorderValues@@ -15,6 +16,7 @@ __all__ = ["AttributeCreate","AttributeDelete","AttributeBulkCreate",+ "AttributeBulkUpdate","AttributeReorderValues","AttributeUpdate","AttributeValueCreate",diff --git a/saleor/graphql/attribute/mutations/attribute_bulk_create.py b/saleor/graphql/attribute/mutations/attribute_bulk_create.pyindex e205778b69..4d08f1c362 100644--- a/saleor/graphql/attribute/mutations/attribute_bulk_create.py+++ b/saleor/graphql/attribute/mutations/attribute_bulk_create.py@@ -16,21 +16,158 @@ from ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfofrom ...core.descriptions import ADDED_IN_315, PREVIEW_FEATUREfrom ...core.doc_category import DOC_CATEGORY_ATTRIBUTES-from ...core.enums import ErrorPolicyEnum, MeasurementUnitsEnum+from ...core.enums import ErrorPolicyEnumfrom ...core.mutations import BaseMutation, ModelMutation-from ...core.types import (- AttributeBulkCreateError,- BaseInputObjectType,- BaseObjectType,- NonNullList,-)+from ...core.types import AttributeBulkCreateError, BaseObjectType, NonNullListfrom ...core.utils import WebhookEventInfo, get_duplicated_valuesfrom ...plugins.dataloaders import get_plugin_manager_promise-from ..descriptions import AttributeDescriptions, AttributeValueDescriptions-from ..enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnum+from ..enums import AttributeTypeEnum+from ..mutations.attribute_create import AttributeCreateInput, AttributeValueCreateInputfrom ..types import AttributeONLY_SWATCH_FIELDS = ["file_url", "content_type", "value"]+DEPRECATED_ATTR_FIELDS = [+ "storefront_search_position",+ "filterable_in_storefront",+ "available_in_grid",+]+DEPRECATED_VALUE_FIELDS = ["rich_text", "plain_text"]+++def validate_value(+ value_data: AttributeCreateInput,+ input_type: AttributeInputType,+ slugs_list: list[str],+ value_index: int,+ attribute_index: int,+ index_error_map: dict[int, list],+ path_prefix="values",+ error_class=AttributeBulkCreateError,+):+ name = value_data.get("name")+ is_swatch_attr = input_type == AttributeInputType.SWATCH++ if is_swatch_attr and value_data.get("value") and value_data.get("file_url"):+ index_error_map[attribute_index].append(+ error_class(+ path=f"{path_prefix}.{value_index}",+ message=("Cannot specify both value and file for swatch attribute."),+ code=error_class.code.INVALID.value,+ )+ )++ if not is_swatch_attr and any(+ [value_data.get(field) for field in ONLY_SWATCH_FIELDS]+ ):+ message = (+ "Cannot define value, file and contentType fields for not "+ "swatch attribute."+ )+ index_error_map[attribute_index].append(+ error_class(+ path=f"{path_prefix}.{value_index}",+ message=message,+ code=error_class.code.INVALID.value,+ )+ )++ slug_value = prepare_unique_slug(slugify(unidecode(name)), slugs_list)+ value_data["slug"] = slug_value+ slugs_list.append(slug_value)++ return value_data+++def clean_values(+ values: list,+ input_type: AttributeInputType,+ values_existing_external_refs: set,+ duplicated_values_external_ref: set,+ attribute_index: int,+ index_error_map: dict[int, list],+ attribute=None,+ path_prefix="values",+ error_class=AttributeBulkCreateError,+):+ cleand_values: list = []+ slugs_list: list = []++ if attribute:+ slugs_list = list(attribute.values.values_list("slug", flat=True))++ duplicated_names = get_duplicated_values(+ [unidecode(value_data.name.lower().strip()) for value_data in values]+ )++ for value_index, value_data in enumerate(values):+ external_ref = value_data.external_reference+ if external_ref in duplicated_values_external_ref:+ index_error_map[attribute_index].append(+ error_class(+ path=f"{path_prefix}.{value_index}.externalReference",+ message="Duplicated external reference.",+ code=error_class.code.DUPLICATED_INPUT_ITEM.value,+ )+ )+ continue++ if external_ref and external_ref in values_existing_external_refs:+ index_error_map[attribute_index].append(+ error_class(+ path=f"{path_prefix}.{value_index}.externalReference",+ message="External reference already exists.",+ code=error_class.code.UNIQUE.value,+ )+ )+ continue++ if unidecode(value_data.name.lower().strip()) in duplicated_names:+ index_error_map[attribute_index].append(+ error_class(+ path=f"{path_prefix}.{value_index}.name",+ message="Duplicated name.",+ code=error_class.code.DUPLICATED_INPUT_ITEM.value,+ )+ )+ continue++ if value_data.value and input_type not in AttributeInputType.TYPES_WITH_CHOICES:+ index_error_map[attribute_index].append(+ error_class(+ path="values",+ message=(f"Values cannot be used with input type {input_type}.",),+ code=error_class.code.INVALID.value,+ )+ )+ continue++ if any(key in DEPRECATED_VALUE_FIELDS for key in value_data.keys()):+ message = (+ "Deprecated fields 'rich_text', 'plain_text' and are not "+ "allowed in bulk mutation."+ )+ index_error_map[attribute_index].append(+ AttributeBulkCreateError(+ path=f"{path_prefix}.{value_index}",+ message=message,+ code=error_class.code.INVALID.value,+ )+ )+ continue++ validate_value(+ value_data,+ input_type,+ slugs_list,+ value_index,+ attribute_index,+ index_error_map,+ path_prefix,+ error_class,+ )+ cleand_values.append(value_data)++ return cleand_valuesclass AttributeBulkCreateResult(BaseObjectType):@@ -57,51 +194,6 @@ def get_results(]-class AttributeBulkCreateValueInput(BaseInputObjectType):- name = graphene.String(required=True, description=AttributeValueDescriptions.NAME)- value = graphene.String(description=AttributeValueDescriptions.VALUE)- external_reference = graphene.String(- description="External ID of this attribute value.",- required=False,- )- file_url = graphene.String(- required=False,- description="URL of the file attribute. Every time, a new value is created.",- )- content_type = graphene.String(required=False, description="File content type.")-- class Meta:- doc_category = DOC_CATEGORY_ATTRIBUTES---class AttributeBulkCreateInput(BaseInputObjectType):- external_reference = graphene.String(- description="External ID of this attribute.", required=False- )- input_type = AttributeInputTypeEnum(description=AttributeDescriptions.INPUT_TYPE)- entity_type = AttributeEntityTypeEnum(description=AttributeDescriptions.ENTITY_TYPE)- name = graphene.String(required=True, description=AttributeDescriptions.NAME)- slug = graphene.String(required=False, description=AttributeDescriptions.SLUG)- type = AttributeTypeEnum(description=AttributeDescriptions.TYPE, required=True)- unit = MeasurementUnitsEnum(description=AttributeDescriptions.UNIT, required=False)- values = NonNullList(- AttributeBulkCreateValueInput, description=AttributeDescriptions.VALUES- )- value_required = graphene.Boolean(description=AttributeDescriptions.VALUE_REQUIRED)- is_variant_only = graphene.Boolean(- required=False, description=AttributeDescriptions.IS_VARIANT_ONLY- )- visible_in_storefront = graphene.Boolean(- description=AttributeDescriptions.VISIBLE_IN_STOREFRONT- )- filterable_in_dashboard = graphene.Boolean(- description=AttributeDescriptions.FILTERABLE_IN_DASHBOARD- )-- class Meta:- doc_category = DOC_CATEGORY_ATTRIBUTES--class AttributeBulkCreate(BaseMutation):count = graphene.Int(required=True,@@ -116,9 +208,9 @@ class AttributeBulkCreate(BaseMutation):class Arguments:attributes = NonNullList(- AttributeBulkCreateInput,+ AttributeCreateInput,required=True,- description="Input list of products to create.",+ description="Input list of attributes to create.",)error_policy = ErrorPolicyEnum(required=False,@@ -141,7 +233,7 @@ class AttributeBulkCreate(BaseMutation):def clean_attributes(cls,info: ResolveInfo,- attributes_data: List[AttributeBulkCreateInput],+ attributes_data: List[AttributeCreateInput],index_error_map: dict[int, List[AttributeBulkCreateError]],):cleaned_inputs_map: dict = {}@@ -207,6 +299,21 @@ class AttributeBulkCreate(BaseMutation):cleaned_inputs_map[attribute_index] = Nonecontinue+ if any(key in DEPRECATED_ATTR_FIELDS for key in attribute_data.keys()):+ message = (+ "Deprecated fields 'storefront_search_position', "+ "'filterable_in_storefront', 'available_in_grid' and are not "+ "allowed in bulk mutation."+ )+ index_error_map[attribute_index].append(+ AttributeBulkCreateError(+ message=message,+ code=AttributeBulkCreateErrorCode.INVALID.value,+ )+ )+ cleaned_inputs_map[attribute_index] = None+ continue+cleaned_input = cls.clean_attribute_input(info,attribute_data,@@ -223,7 +330,7 @@ class AttributeBulkCreate(BaseMutation):def clean_attribute_input(cls,info: ResolveInfo,- attribute_data: AttributeBulkCreateInput,+ attribute_data: AttributeCreateInput,attribute_index: int,existing_slugs: set,values_existing_external_refs: set,@@ -232,7 +339,7 @@ class AttributeBulkCreate(BaseMutation):):values = attribute_data.pop("values", None)cleaned_input = ModelMutation.clean_input(- info, None, attribute_data, input_cls=AttributeBulkCreateInput+ info, None, attribute_data, input_cls=AttributeCreateInput)# check permissions based on attribute type@@ -290,7 +397,7 @@ class AttributeBulkCreate(BaseMutation):cleaned_input["slug"] = cls._generate_slug(cleaned_input, existing_slugs)if values:- cleaned_values = cls.clean_values(+ cleaned_values = clean_values(values,input_type,values_existing_external_refs,@@ -302,128 +409,6 @@ class AttributeBulkCreate(BaseMutation):return cleaned_input- @classmethod- def clean_values(- cls,- values: list[AttributeBulkCreateValueInput],- input_type: AttributeInputType,- values_existing_external_refs: set,- duplicated_values_external_ref: set,- attribute_index: int,- index_error_map: dict[int, List[AttributeBulkCreateError]],- ) -> list[AttributeBulkCreateValueInput]:- slugs_list: list = []- cleand_values: list = []-- duplicated_names = get_duplicated_values(- [unidecode(value_data.name.lower().strip()) for value_data in values]- )-- for value_index, value_data in enumerate(values):- external_ref = value_data.external_reference- if external_ref in duplicated_values_external_ref:- index_error_map[attribute_index].append(- AttributeBulkCreateError(- path=f"values.{value_index}.externalReference",- message="Duplicated external reference.",- code=AttributeBulkCreateErrorCode.DUPLICATED_INPUT_ITEM.value,- )- )- continue-- if external_ref and external_ref in values_existing_external_refs:- index_error_map[attribute_index].append(- AttributeBulkCreateError(- path=f"values.{value_index}.externalReference",- message="External reference already exists.",- code=AttributeBulkCreateErrorCode.UNIQUE.value,- )- )- continue-- if unidecode(value_data.name.lower().strip()) in duplicated_names:- index_error_map[attribute_index].append(- AttributeBulkCreateError(- path=f"values.{value_index}.name",- message="Duplicated name.",- code=AttributeBulkCreateErrorCode.DUPLICATED_INPUT_ITEM.value,- )- )- continue-- if (- value_data.value- and input_type not in AttributeInputType.TYPES_WITH_CHOICES- ):- index_error_map[attribute_index].append(- AttributeBulkCreateError(- path="values",- message=(- f"Values cannot be used with input type {input_type}.",- ),- code=AttributeBulkCreateErrorCode.INVALID.value,- )- )- continue-- cls._validate_value(- value_data,- input_type,- slugs_list,- value_index,- attribute_index,- index_error_map,- )-- cleand_values.append(value_data)-- return cleand_values-- @classmethod- def _validate_value(- cls,- value_data: AttributeBulkCreateValueInput,- input_type: AttributeInputType,- slugs_list: list[str],- value_index: int,- attribute_index: int,- index_error_map: dict[int, List[AttributeBulkCreateError]],- ):- name = value_data.get("name")- is_swatch_attr = input_type == AttributeInputType.SWATCH-- if is_swatch_attr and value_data.get("value") and value_data.get("file_url"):- index_error_map[attribute_index].append(- AttributeBulkCreateError(- path=f"values.{value_index}",- message=(- "Cannot specify both value and file for swatch attribute."- ),- code=AttributeBulkCreateErrorCode.INVALID.value,- )- )-- if not is_swatch_attr and any(- [value_data.get(field) for field in ONLY_SWATCH_FIELDS]- ):- message = (- "Cannot define value, file and contentType fields for not "- "swatch attribute."- )- index_error_map[attribute_index].append(- AttributeBulkCreateError(- path=f"values.{value_index}",- message=message,- code=AttributeBulkCreateErrorCode.INVALID.value,- )- )-- slug_value = prepare_unique_slug(slugify(unidecode(name)), slugs_list)- value_data["slug"] = slug_value- slugs_list.append(slug_value)-- return value_data-@classmethoddef _generate_slug(cls, cleaned_input, existing_slugs):name = cleaned_input.get("name")@@ -495,7 +480,7 @@ class AttributeBulkCreate(BaseMutation):def create_values(cls,attribute: models.Attribute,- values_data: list[AttributeBulkCreateValueInput],+ values_data: list[AttributeValueCreateInput],values: list[models.AttributeValue],attr_index: int,index_error_map: dict[int, List[AttributeBulkCreateError]],diff --git a/saleor/graphql/attribute/mutations/attribute_bulk_update.py b/saleor/graphql/attribute/mutations/attribute_bulk_update.pynew file mode 100644index 0000000000..64c2efe98d--- /dev/null+++ b/saleor/graphql/attribute/mutations/attribute_bulk_update.py@@ -0,0 +1,636 @@+from collections import defaultdict+from typing import List, Tuple, Union++import graphene+from django.core.exceptions import ValidationError+from django.db.models import Q+from django.utils.text import slugify+from graphene.utils.str_converters import to_camel_case+from graphql.error import GraphQLError+from text_unidecode import unidecode++from ....attribute import models+from ....attribute.error_codes import AttributeBulkUpdateErrorCode+from ....core.tracing import traced_atomic_transaction+from ....permission.enums import PageTypePermissions, ProductTypePermissions+from ...core import ResolveInfo+from ...core.descriptions import ADDED_IN_315, PREVIEW_FEATURE+from ...core.doc_category import DOC_CATEGORY_ATTRIBUTES+from ...core.enums import ErrorPolicyEnum+from ...core.mutations import BaseMutation, ModelMutation+from ...core.types import (+ AttributeBulkUpdateError,+ BaseInputObjectType,+ BaseObjectType,+ NonNullList,+)+from ...core.utils import (+ WebhookEventAsyncType,+ WebhookEventInfo,+ from_global_id_or_error,+ get_duplicated_values,+)+from ...core.validators import validate_one_of_args_is_in_mutation+from ...plugins.dataloaders import get_plugin_manager_promise+from ..enums import AttributeTypeEnum+from ..types import Attribute+from .attribute_bulk_create import DEPRECATED_ATTR_FIELDS, clean_values+from .attribute_update import AttributeUpdateInput+++class AttributeBulkUpdateResult(BaseObjectType):+ attribute = graphene.Field(Attribute, description="Attribute data.")+ errors = NonNullList(+ AttributeBulkUpdateError,+ required=False,+ description="List of errors occurred on update attempt.",+ )++ class Meta:+ doc_category = DOC_CATEGORY_ATTRIBUTES+++def get_results(+ instances_data_with_errors_list: list[dict], reject_everything: bool = False+) -> list[AttributeBulkUpdateResult]:+ return [+ AttributeBulkUpdateResult(+ attribute=None if reject_everything else data.get("instance"),+ errors=data.get("errors"),+ )+ for data in instances_data_with_errors_list+ ]+++class AttributeBulkUpdateInput(BaseInputObjectType):+ id = graphene.ID(description="ID of an attribute to update.", required=False)+ external_reference = graphene.String(+ description="External ID of this attribute.", required=False+ )+ fields = AttributeUpdateInput(description="Fields to update.", required=True)++ class Meta:+ doc_category = DOC_CATEGORY_ATTRIBUTES+++class AttributeBulkUpdate(BaseMutation):+ count = graphene.Int(+ required=True,+ description="Returns how many objects were updated.",+ )+ results = NonNullList(+ AttributeBulkUpdateResult,+ required=True,+ default_value=[],+ description="List of the updated attributes.",+ )++ class Arguments:+ attributes = NonNullList(+ AttributeBulkUpdateInput,+ required=True,+ description="Input list of attributes to update.",+ )+ error_policy = ErrorPolicyEnum(+ required=False,+ description="Policies of error handling. DEFAULT: "+ + ErrorPolicyEnum.REJECT_EVERYTHING.name,+ )++ class Meta:+ description = "Updates attributes." + ADDED_IN_315 + PREVIEW_FEATURE+ doc_category = DOC_CATEGORY_ATTRIBUTES+ error_type_class = AttributeBulkUpdateError+ webhook_events_info = [+ WebhookEventInfo(+ type=WebhookEventAsyncType.ATTRIBUTE_UPDATED,+ description=(+ "An attribute was updated. "+ "Optionally called when new attribute value was created or "+ "deleted."+ ),+ ),+ WebhookEventInfo(+ type=WebhookEventAsyncType.ATTRIBUTE_VALUE_CREATED,+ description="Called optionally when an attribute value was created.",+ ),+ WebhookEventInfo(+ type=WebhookEventAsyncType.ATTRIBUTE_VALUE_DELETED,+ description="Called optionally when an attribute value was deleted.",+ ),+ ]++ @classmethod+ def clean_attributes(+ cls,+ info: ResolveInfo,+ attributes_data: List[AttributeBulkUpdateInput],+ index_error_map: dict[int, List[AttributeBulkUpdateError]],+ ):+ cleaned_inputs_map: dict = {}++ existing_slugs = cls._get_attrs_existing_slugs(attributes_data)+ (+ attrs_existing_external_refs,+ duplicated_external_ref,+ ) = cls._get_attrs_existing_and_duplicated_external_refs(attributes_data)+ (+ values_existing_external_refs,+ duplicated_values_external_ref,+ ) = cls._get_values_existing_and_duplicated_external_refs(attributes_data)++ attributes = cls.get_attributes(attributes_data)+ for attribute_index, attribute_data in enumerate(attributes_data):+ external_ref = attribute_data.external_reference+ new_external_ref = attribute_data.fields.external_reference++ try:+ validate_one_of_args_is_in_mutation(+ "id",+ attribute_data.id,+ "external_reference",+ external_ref,+ use_camel_case=True,+ )+ except ValidationError as exc:+ index_error_map[attribute_index].append(+ AttributeBulkUpdateError(+ message=exc.message,+ code=AttributeBulkUpdateErrorCode.INVALID.value,+ )+ )+ cleaned_inputs_map[attribute_index] = None+ continue++ if any(+ key in DEPRECATED_ATTR_FIELDS for key in attribute_data.fields.keys()+ ):+ message = (+ "Deprecated fields 'storefront_search_position', "+ "'filterable_in_storefront', 'available_in_grid' and are not "+ "allowed in bulk mutation."+ )+ index_error_map[attribute_index].append(+ AttributeBulkUpdateError(+ message=message,+ code=AttributeBulkUpdateErrorCode.INVALID.value,+ )+ )+ cleaned_inputs_map[attribute_index] = None+ continue++ if attribute_data.id:+ try:+ obj_type, db_id = from_global_id_or_error(+ attribute_data.id, only_type="Attribute", raise_error=True+ )+ except GraphQLError as exc:+ index_error_map[attribute_index].append(+ AttributeBulkUpdateError(+ path="id",+ message=str(exc),+ code=AttributeBulkUpdateErrorCode.INVALID.value,+ )+ )+ cleaned_inputs_map[attribute_index] = None+ continue++ attribute_data["db_id"] = db_id++ if new_external_ref in duplicated_external_ref:+ index_error_map[attribute_index].append(+ AttributeBulkUpdateError(+ path="fields.externalReference",+ message="Duplicated external reference.",+ code=AttributeBulkUpdateErrorCode.DUPLICATED_INPUT_ITEM.value,+ )+ )+ cleaned_inputs_map[attribute_index] = None+ continue++ if new_external_ref and new_external_ref in attrs_existing_external_refs:+ index_error_map[attribute_index].append(+ AttributeBulkUpdateError(+ path="fields.externalReference",+ message="External reference already exists.",+ code=AttributeBulkUpdateErrorCode.UNIQUE.value,+ )+ )+ cleaned_inputs_map[attribute_index] = None+ continue++ cleaned_input = cls.clean_attribute_input(+ info,+ attribute_data,+ attribute_index,+ existing_slugs,+ values_existing_external_refs,+ duplicated_values_external_ref,+ attributes,+ index_error_map,+ )+ cleaned_inputs_map[attribute_index] = cleaned_input+ return cleaned_inputs_map++ @classmethod+ def _get_attrs_existing_and_duplicated_external_refs(+ cls, attributes_data: List[AttributeBulkUpdateInput]+ ):+ attr_input_external_refs = [+ attribute_data.fields.external_reference+ for attribute_data in attributes_data+ if attribute_data.fields.external_reference+ ]+ attrs_existing_external_refs = set(+ models.Attribute.objects.filter(+ external_reference__in=attr_input_external_refs+ ).values_list("external_reference", flat=True)+ )+ duplicated_external_ref = get_duplicated_values(attr_input_external_refs)++ return attrs_existing_external_refs, duplicated_external_ref++ @classmethod+ def _get_attrs_existing_slugs(cls, attributes_data: List[AttributeBulkUpdateInput]):+ return set(+ models.Attribute.objects.filter(+ slug__in=[+ slugify(unidecode(attribute_data.fields.name))+ for attribute_data in attributes_data+ if attribute_data.fields.name+ ]+ ).values_list("slug", flat=True)+ )++ @classmethod+ def _get_values_existing_and_duplicated_external_refs(+ cls, attributes_data: List[AttributeBulkUpdateInput]+ ):+ values_input_external_refs = [+ value.external_reference+ for attribute_data in attributes_data+ if attribute_data.fields.add_values+ for value in attribute_data.fields.add_values+ if value.external_reference+ ]+ values_existing_external_refs = set(+ models.AttributeValue.objects.filter(+ external_reference__in=values_input_external_refs+ ).values_list("external_reference", flat=True)+ )+ duplicated_values_external_ref = get_duplicated_values(+ values_input_external_refs+ )++ return values_existing_external_refs, duplicated_values_external_ref++ @classmethod+ def clean_attribute_input(+ cls,+ info: ResolveInfo,+ attribute_data: AttributeBulkUpdateInput,+ attribute_index: int,+ existing_slugs: set,+ values_existing_external_refs,+ duplicated_values_external_ref,+ attributes,+ index_error_map: dict[int, List[AttributeBulkUpdateError]],+ ):+ remove_values = attribute_data.fields.pop("remove_values", [])+ add_values = attribute_data.fields.pop("add_values", [])++ attr = cls.find_attribute(+ attribute_data.get("db_id"),+ attribute_data.get("external_reference"),+ attributes,+ attribute_index,+ index_error_map,+ )++ if not attr:+ return None++ attribute_data["instance"] = attr++ # check permissions based on attribute type+ permissions: Union[Tuple[ProductTypePermissions], Tuple[PageTypePermissions]]+ if attr.type == AttributeTypeEnum.PRODUCT_TYPE.value:+ permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)+ else:+ permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)++ if not cls.check_permissions(info.context, permissions):+ index_error_map[attribute_index].append(+ AttributeBulkUpdateError(+ message=(+ "You have no permission to manage this type of attributes. "+ f"You need one of the following permissions: {permissions}"+ ),+ code=AttributeBulkUpdateErrorCode.REQUIRED.value,+ )+ )+ return None++ attribute_data["fields"] = ModelMutation.clean_input(+ info, None, attribute_data.fields, input_cls=AttributeUpdateInput+ )++ if remove_values:+ cleaned_remove_values = cls.clean_remove_values(+ remove_values, attr, attribute_index, index_error_map+ )+ attribute_data["fields"]["remove_values"] = cleaned_remove_values++ if add_values:+ cleaned_add_values = clean_values(+ add_values,+ attr.input_type,+ values_existing_external_refs,+ duplicated_values_external_ref,+ attribute_index,+ index_error_map,+ attr,+ "addValues",+ AttributeBulkUpdateError,+ )+ attribute_data["fields"]["add_values"] = cleaned_add_values++ return attribute_data++ @classmethod+ def clean_remove_values(+ cls, remove_values, attribute, attribute_index, index_error_map+ ):+ clean_remove_values = []++ for index, value_global_id in enumerate(remove_values):+ try:+ obj_type, value_db_id = from_global_id_or_error(+ value_global_id, only_type="AttributeValue", raise_error=True+ )+ except GraphQLError as exc:+ index_error_map[attribute_index].append(+ AttributeBulkUpdateError(+ path=f"removeValues.{index}",+ message=str(exc),+ code=AttributeBulkUpdateErrorCode.INVALID.value,+ )+ )+ continue++ # values are prefetched+ values = attribute.values.all()+ value = next((obj for obj in values if str(obj.pk) == value_db_id), None)++ if not value:+ msg = f"Value {value_global_id} does not belong to this attribute."+ index_error_map[attribute_index].append(+ AttributeBulkUpdateError(+ path=f"removeValues.{index}",+ message=msg,+ code=AttributeBulkUpdateErrorCode.INVALID.value,+ )+ )+ else:+ clean_remove_values.append(value)+ return clean_remove_values++ @classmethod+ def update_attributes(+ cls,+ info: ResolveInfo,+ cleaned_inputs_map: dict[int, dict],+ error_policy: str,+ index_error_map: dict[int, List[AttributeBulkUpdateError]],+ ) -> List[dict]:+ instances_data_and_errors_list: List[dict] = []++ for index, cleaned_input in cleaned_inputs_map.items():+ if not cleaned_input:+ instances_data_and_errors_list.append(+ {"instance": None, "errors": index_error_map[index]}+ )+ continue++ attr = cleaned_input["instance"]+ fields = cleaned_input["fields"]+ remove_values = fields.pop("remove_values", [])+ add_values = fields.pop("add_values", [])++ if fields:+ try:+ attr = cls.construct_instance(attr, fields)+ cls.clean_instance(info, attr)+ except ValidationError as exc:+ for key, errors in exc.error_dict.items():+ for e in errors:+ index_error_map[index].append(+ AttributeBulkUpdateError(+ path=to_camel_case(key),+ message=e.messages[0],+ code=e.code,+ )+ )+ instances_data_and_errors_list.append(+ {"instance": None, "errors": index_error_map[index]}+ )+ continue++ data = {+ "instance": attr,+ "errors": index_error_map[index],+ "remove_values": remove_values,+ "add_values": [],+ "attribute_updated": True if fields else False,+ }++ if add_values:+ values = cls.create_values(attr, add_values, index, index_error_map)+ data["add_values"] = values++ instances_data_and_errors_list.append(data)++ if error_policy == ErrorPolicyEnum.REJECT_FAILED_ROWS.value:+ for instance_data in instances_data_and_errors_list:+ if instance_data["errors"]:+ instance_data["instance"] = None++ return instances_data_and_errors_list++ @classmethod+ def create_values(+ cls,+ attribute: models.Attribute,+ values_data: list,+ attr_index: int,+ index_error_map: dict[int, list],+ ):+ values = []+ for value_index, value_data in enumerate(values_data):+ value = models.AttributeValue(attribute=attribute)++ try:+ value = cls.construct_instance(value, value_data)+ value.full_clean(exclude=["attribute", "slug"])+ values.append(value)+ except ValidationError as exc:+ for key, errors in exc.error_dict.items():+ for e in errors:+ path = f"addValues.{value_index}.{to_camel_case(key)}"+ index_error_map[attr_index].append(+ AttributeBulkUpdateError(+ path=path,+ message=e.messages[0],+ code=e.code,+ )+ )+ return values++ @classmethod+ def get_attributes(+ cls, attributes_data: List[AttributeBulkUpdateInput]+ ) -> list[models.Attribute]:+ lookup = Q()++ for attribute_input in attributes_data:+ external_ref = attribute_input.get("external_reference")+ attribute_id = attribute_input.get("id")++ if not external_ref and not attribute_id:+ continue++ single_attr_lookup = Q()++ if attribute_id:+ single_attr_lookup |= Q(+ pk=graphene.Node.from_global_id(attribute_id)[1]+ )+ else:+ single_attr_lookup |= Q(external_reference=external_ref)+ lookup |= single_attr_lookup++ attributes = models.Attribute.objects.filter(lookup).prefetch_related("values")+ return list(attributes)++ @classmethod+ def find_attribute(+ cls, attr_id, external_ref, attributes, attribute_index, index_error_map+ ):+ if attr_id:+ attr = next((obj for obj in attributes if str(obj.pk) == attr_id), None)+ else:+ attr = next(+ (+ obj+ for obj in attributes+ if str(obj.external_reference) == external_ref+ ),+ None,+ )+ if not attr:+ index_error_map[attribute_index].append(+ AttributeBulkUpdateError(+ message="Couldn't resolve to an object.",+ code=AttributeBulkUpdateErrorCode.NOT_FOUND.value,+ path="id" if attr_id else "externalReference",+ )+ )++ return attr++ @classmethod+ def save(cls, instances_data_with_errors_list: list[dict]):+ attributes_to_update: list = []+ values_to_create: list = []+ values_to_remove: list = []+ updated_attributes: list = []++ for attribute_data in instances_data_with_errors_list:+ attribute = attribute_data["instance"]++ if not attribute:+ continue++ if attribute_data.get("attribute_updated"):+ attributes_to_update.append(attribute)+ else:+ updated_attributes.append(attribute)++ values_to_remove.extend(attribute_data["remove_values"])+ values_to_create.extend(attribute_data["add_values"])++ models.Attribute.objects.bulk_update(+ attributes_to_update,+ [+ "name",+ "slug",+ "unit",+ "value_required",+ "visible_in_storefront",+ "is_variant_only",+ "filterable_in_dashboard",+ "external_reference",+ ],+ )++ models.AttributeValue.objects.filter(+ id__in=[values_to_remove.id for values_to_remove in values_to_remove]+ ).delete()+ models.AttributeValue.objects.bulk_create(values_to_create)++ updated_attributes.extend(attributes_to_update)+ return updated_attributes, values_to_remove, values_to_create++ @classmethod+ def post_save_actions(+ cls,+ info: ResolveInfo,+ attributes: list[models.Attribute],+ values_to_remove: list[models.AttributeValue],+ values_to_create: list[models.AttributeValue],+ ):+ manager = get_plugin_manager_promise(info.context).get()++ for attribute in attributes:+ cls.call_event(manager.attribute_updated, attribute)+ for value in values_to_create:+ cls.call_event(manager.attribute_value_created, value)+ for value in values_to_remove:+ cls.call_event(manager.attribute_value_deleted, value)++ @classmethod+ @traced_atomic_transaction()+ def perform_mutation(cls, root, info, **data):+ index_error_map: dict = defaultdict(list)+ error_policy = data.get("error_policy", ErrorPolicyEnum.REJECT_EVERYTHING.value)++ # clean and validate inputs+ cleaned_inputs_map = cls.clean_attributes(+ info, data["attributes"], index_error_map+ )+ instances_data_with_errors_list = cls.update_attributes(+ info, cleaned_inputs_map, error_policy, index_error_map+ )++ # check if errors occurred+ inputs_have_errors = next(+ (True for errors in index_error_map.values() if errors), False+ )++ if (+ inputs_have_errors+ and error_policy == ErrorPolicyEnum.REJECT_EVERYTHING.value+ ):+ results = get_results(instances_data_with_errors_list, True)+ return AttributeBulkUpdate(count=0, results=results)++ # save all objects+ attributes, values_to_remove, values_to_create = cls.save(+ instances_data_with_errors_list+ )++ # prepare and return data+ results = get_results(instances_data_with_errors_list)+ cls.post_save_actions(info, attributes, values_to_remove, values_to_create)++ return AttributeBulkUpdate(count=len(attributes), results=results)diff --git a/saleor/graphql/attribute/mutations/attribute_create.py b/saleor/graphql/attribute/mutations/attribute_create.pyindex 90fddaca4d..54269c91cb 100644--- a/saleor/graphql/attribute/mutations/attribute_create.py+++ b/saleor/graphql/attribute/mutations/attribute_create.py@@ -98,6 +98,12 @@ class AttributeCreateInput(BaseInputObjectType):class Meta:doc_category = DOC_CATEGORY_ATTRIBUTES+ description = (+ "Represents an input for create of attribute.\n\n"+ "NOTE: Deprecated fields `filterableInStorefront`, "+ "`storefrontSearchPosition` and `availableInGrid` are not supported in "+ "bulk mutations: `attributeBulkCreate`, `attributeBulkUpdate`."+ )class AttributeCreate(AttributeMixin, ModelMutation):diff --git a/saleor/graphql/attribute/mutations/attribute_update.py b/saleor/graphql/attribute/mutations/attribute_update.pyindex 76d7f5284f..f643d53ef2 100644--- a/saleor/graphql/attribute/mutations/attribute_update.py+++ b/saleor/graphql/attribute/mutations/attribute_update.py@@ -69,6 +69,12 @@ class AttributeUpdateInput(BaseInputObjectType):class Meta:doc_category = DOC_CATEGORY_ATTRIBUTES+ description = (+ "Represents an input for update of attribute.\n\n"+ "NOTE: Deprecated fields `filterableInStorefront`, "+ "`storefrontSearchPosition` and `availableInGrid` are not supported in "+ "bulk mutations: `attributeBulkCreate`, `attributeBulkUpdate`."+ )class AttributeUpdate(AttributeMixin, ModelWithExtRefMutation):diff --git a/saleor/graphql/attribute/schema.py b/saleor/graphql/attribute/schema.pyindex 4f47456ebb..0862380109 100644--- a/saleor/graphql/attribute/schema.py+++ b/saleor/graphql/attribute/schema.py@@ -17,6 +17,7 @@ from .bulk_mutations import AttributeBulkDelete, AttributeValueBulkDeletefrom .filters import AttributeFilterInput, AttributeWhereInput, filter_attribute_searchfrom .mutations import (AttributeBulkCreate,+ AttributeBulkUpdate,AttributeCreate,AttributeDelete,AttributeReorderValues,@@ -79,6 +80,7 @@ class AttributeMutations(graphene.ObjectType):attribute_delete = AttributeDelete.Field()attribute_update = AttributeUpdate.Field()attribute_bulk_create = AttributeBulkCreate.Field()+ attribute_bulk_update = AttributeBulkUpdate.Field()attribute_translate = AttributeTranslate.Field()attribute_bulk_translate = AttributeBulkTranslate.Field()attribute_bulk_delete = AttributeBulkDelete.Field()diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_create.pyindex f22c200d69..41e43e8ca4 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_create.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_create.py@@ -8,7 +8,7 @@ from ...enums import AttributeInputTypeEnum, AttributeTypeEnumATTRIBUTE_BULK_CREATE_MUTATION = """mutation AttributeBulkCreate(- $attributes: [AttributeBulkCreateInput!]!,+ $attributes: [AttributeCreateInput!]!,$errorPolicy: ErrorPolicyEnum) {attributeBulkCreate(attributes: $attributes, errorPolicy: $errorPolicy) {@@ -169,6 +169,44 @@ def test_attribute_bulk_create_without_permission(staff_api_client):assert data["count"] == 0+def test_attribute_bulk_create_with_deprecated_field(staff_api_client):+ # given+ attribute_1_name = "Example name 1"+ external_reference_1 = "test-ext-ref-1"++ attributes = [+ {+ "name": attribute_1_name,+ "externalReference": external_reference_1,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "filterableInStorefront": True,+ }+ ]++ # when+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_CREATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkCreate"]++ # then+ attributes = Attribute.objects.all()+ errors = data["results"][0]["errors"]+ message = (+ "Deprecated fields 'storefront_search_position', "+ "'filterable_in_storefront', 'available_in_grid' and are not "+ "allowed in bulk mutation."+ )++ assert len(attributes) == 0+ assert data["count"] == 0+ assert errors+ assert errors[0]["code"] == AttributeBulkCreateErrorCode.INVALID.name+ assert errors[0]["message"] == message++def test_attribute_bulk_create_with_file_input_type_and_invalid_settings(staff_api_client,permission_manage_product_types_and_attributes,@@ -466,6 +504,45 @@ def test_attribute_bulk_create_with_duplicated_external_reference_in_values()+def test_attribute_bulk_create_with_existing_external_reference_in_values(+ staff_api_client, color_attribute, permission_manage_product_types_and_attributes+):+ # given+ attribute_1_name = "Example name 1"+ value_1 = "RED"+ value_external_reference = color_attribute.values.first().external_reference++ attributes = [+ {+ "name": attribute_1_name,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "inputType": AttributeInputTypeEnum.DROPDOWN.name,+ "values": [+ {"name": value_1, "externalReference": value_external_reference},+ ],+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_CREATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkCreate"]++ # then+ assert data["count"] == 0++ errors = data["results"][0]["errors"]+ assert errors+ assert errors[0]["path"] == "values.0.externalReference"+ assert errors[0]["code"] == AttributeBulkCreateErrorCode.UNIQUE.name++def test_attribute_bulk_create_dropdown_with_one_invalid_value_and_ignore_failed(staff_api_client, permission_manage_product_types_and_attributes):diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.pynew file mode 100644index 0000000000..6934d4bb1f--- /dev/null+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.py@@ -0,0 +1,835 @@+from unittest.mock import patch++import graphene++from .....attribute.error_codes import AttributeBulkUpdateErrorCode+from .....attribute.models import Attribute+from ....core.enums import ErrorPolicyEnum+from ....tests.utils import get_graphql_content++ATTRIBUTE_BULK_UPDATE_MUTATION = """+ mutation AttributeBulkUpdate(+ $attributes: [AttributeBulkUpdateInput!]!,+ $errorPolicy: ErrorPolicyEnum+ ) {+ attributeBulkUpdate(attributes: $attributes, errorPolicy: $errorPolicy) {+ results {+ errors {+ path+ message+ code+ }+ attribute{+ id+ name+ slug+ choices(first: 10) {+ edges {+ node {+ name+ slug+ value+ file {+ url+ contentType+ }+ }+ }+ }+ }+ }+ count+ }+ }+"""+++def test_attribute_bulk_update_with_base_data(+ staff_api_client,+ color_attribute,+ size_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ attribute_1_new_name = "ColorAttrNewName"+ attribute_2_new_name = "SizeAttrNewName"++ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {"name": attribute_1_new_name},+ },+ {+ "id": graphene.Node.to_global_id("Attribute", size_attribute.id),+ "fields": {"name": attribute_2_new_name},+ },+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ attributes = Attribute.objects.all()++ assert len(attributes) == 2+ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]+ assert data["count"] == 2+ assert data["results"][0]["attribute"]["name"] == attribute_1_new_name+ assert data["results"][1]["attribute"]["name"] == attribute_2_new_name+++@patch("saleor.plugins.manager.PluginsManager.attribute_updated")+def test_attribute_bulk_update_trigger_webhook(+ created_webhook_mock,+ color_attribute,+ size_attribute,+ staff_api_client,+ permission_manage_product_types_and_attributes,+):+ # given+ attribute_1_new_name = "ColorAttrNewName"+ attribute_2_new_name = "SizeAttrNewName"++ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {"name": attribute_1_new_name},+ },+ {+ "id": graphene.Node.to_global_id("Attribute", size_attribute.id),+ "fields": {"name": attribute_2_new_name},+ },+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ assert data["count"] == 2+ assert created_webhook_mock.call_count == 2+++def test_attribute_bulk_update_without_permission(+ staff_api_client,+ color_attribute,+):+ # given+ attribute_new_name = "ColorAttrNewName"++ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {"name": attribute_new_name},+ }+ ]++ # when+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ assert data["count"] == 0+ errors = data["results"][0]["errors"]+ assert errors+++def test_attribute_bulk_update_with_deprecated_fields(+ staff_api_client,+ color_attribute,+):+ # given+ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {"filterableInStorefront": True},+ }+ ]++ # when+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ errors = data["results"][0]["errors"]+ message = (+ "Deprecated fields 'storefront_search_position', "+ "'filterable_in_storefront', 'available_in_grid' and are not "+ "allowed in bulk mutation."+ )++ assert data["count"] == 0+ assert errors+ assert errors[0]["code"] == AttributeBulkUpdateErrorCode.INVALID.name+ assert errors[0]["message"] == message+++def test_attribute_bulk_update_with_duplicated_external_ref(+ staff_api_client,+ color_attribute,+ size_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ duplicated_external_ref = "duplicated_external_ref"++ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {"externalReference": duplicated_external_ref},+ },+ {+ "id": graphene.Node.to_global_id("Attribute", size_attribute.id),+ "fields": {"externalReference": duplicated_external_ref},+ },+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ errors_1 = data["results"][0]["errors"]+ errors_2 = data["results"][1]["errors"]++ assert data["count"] == 0+ assert errors_1+ assert errors_2+ assert errors_1[0]["path"] == "fields.externalReference"+ assert (+ errors_1[0]["code"] == AttributeBulkUpdateErrorCode.DUPLICATED_INPUT_ITEM.name+ )+ assert errors_2[0]["path"] == "fields.externalReference"+ assert (+ errors_2[0]["code"] == AttributeBulkUpdateErrorCode.DUPLICATED_INPUT_ITEM.name+ )+++def test_attribute_bulk_update_with_existing_external_ref(+ staff_api_client,+ color_attribute,+ size_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ existing_external_ref = size_attribute.external_reference++ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {"externalReference": existing_external_ref},+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ errors = data["results"][0]["errors"]++ assert data["count"] == 0+ assert errors+ assert errors[0]["path"] == "fields.externalReference"+ assert errors[0]["code"] == AttributeBulkUpdateErrorCode.UNIQUE.name+++def test_attribute_bulk_update_with_invalid_type_id(+ staff_api_client, permission_manage_product_types_and_attributes+):+ # given+ attributes = [+ {"id": graphene.Node.to_global_id("Page", 1), "fields": {"name": "ExampleName"}}+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ assert data["count"] == 0+ errors = data["results"][0]["errors"]+ assert errors+ assert errors[0]["code"] == AttributeBulkUpdateErrorCode.INVALID.name+ assert errors[0]["message"] == "Must receive a Attribute id."+++def test_attribute_bulk_update_without_id_and_external_ref(+ staff_api_client, permission_manage_product_types_and_attributes+):+ # given+ attributes = [{"fields": {"name": "ExampleName"}}]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ assert data["count"] == 0+ errors = data["results"][0]["errors"]+ assert errors+ assert errors[0]["code"] == AttributeBulkUpdateErrorCode.INVALID.name+ assert (+ errors[0]["message"]+ == "At least one of arguments is required: 'id', 'externalReference'."+ )+++def test_attribute_bulk_update_with_id_and_external_ref(+ staff_api_client, color_attribute, permission_manage_product_types_and_attributes+):+ # given+ color_attribute.external_reference = "ColorExternalRef"+ color_attribute.save(update_fields=["external_reference"])++ global_id = graphene.Node.to_global_id("Attribute", color_attribute.id)++ attributes = [+ {+ "id": global_id,+ "externalReference": color_attribute.external_reference,+ "fields": {"name": "ExampleName"},+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ assert data["count"] == 0+ errors = data["results"][0]["errors"]+ assert errors+ assert errors[0]["code"] == AttributeBulkUpdateErrorCode.INVALID.name+ assert (+ errors[0]["message"]+ == "Argument 'id' cannot be combined with 'externalReference'"+ )+++def test_attribute_bulk_update_removes_value(+ staff_api_client, color_attribute, permission_manage_product_types_and_attributes+):+ # given+ assert color_attribute.values.count() == 2++ value_global_id = graphene.Node.to_global_id(+ "AttributeValue", color_attribute.values.first().id+ )++ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {"removeValues": [value_global_id]},+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ color_attribute.refresh_from_db()++ assert color_attribute.values.count() == 1+ assert data["count"] == 1+ assert not data["results"][0]["errors"]+++@patch("saleor.plugins.manager.PluginsManager.attribute_updated")+@patch("saleor.plugins.manager.PluginsManager.attribute_value_deleted")+def test_attribute_bulk_update_removes_value_trigger_webhook(+ attribute_updated_webhook_mock,+ value_deleted_webhook_mock,+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ assert color_attribute.values.count() == 2++ value_global_id = graphene.Node.to_global_id(+ "AttributeValue", color_attribute.values.first().id+ )++ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {"removeValues": [value_global_id]},+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ assert data["count"] == 1+ assert value_deleted_webhook_mock.call_count == 1+ assert attribute_updated_webhook_mock.call_count == 1+++def test_attribute_bulk_update_removes_invalid_value(+ staff_api_client,+ color_attribute,+ size_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ assert size_attribute.values.count() == 2++ invalid_value_global_id = graphene.Node.to_global_id(+ "AttributeValue", size_attribute.values.first().id+ )++ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {"removeValues": [invalid_value_global_id]},+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ color_attribute.refresh_from_db()+ size_attribute.refresh_from_db()++ assert color_attribute.values.count() == 2+ assert color_attribute.values.count() == 2+ assert data["count"] == 0+ errors = data["results"][0]["errors"]+ assert errors+ assert errors[0]["path"] == "removeValues.0"+ assert errors[0]["code"] == AttributeBulkUpdateErrorCode.INVALID.name+ assert (+ errors[0]["message"]+ == f"Value {invalid_value_global_id} does not belong to this attribute."+ )+++def test_attribute_bulk_update_add_new_value(+ staff_api_client,+ color_attribute,+ size_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ assert color_attribute.values.count() == 2+ assert size_attribute.values.count() == 2++ color_new_value_name = "BLACK"+ size_new_value_name = "MINI"++ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {+ "addValues": [+ {+ "name": color_new_value_name,+ }+ ]+ },+ },+ {+ "id": graphene.Node.to_global_id("Attribute", size_attribute.id),+ "fields": {+ "addValues": [+ {+ "name": size_new_value_name,+ }+ ]+ },+ },+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ color_attribute.refresh_from_db()+ size_attribute.refresh_from_db()++ assert data["count"] == 2+ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]+ assert color_attribute.values.count() == 3+ assert size_attribute.values.count() == 3+++def test_attribute_bulk_update_add_value_with_existing_name(+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ assert color_attribute.values.count() == 2++ value = color_attribute.values.first()++ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {+ "addValues": [+ {+ "name": value.name,+ }+ ]+ },+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ color_attribute.refresh_from_db()++ assert data["count"] == 1+ assert not data["results"][0]["errors"]+ assert color_attribute.values.count() == 3+++def test_attribute_bulk_update_with_duplicated_external_reference_in_values(+ staff_api_client,+ color_attribute,+ size_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ assert color_attribute.values.count() == 2+ assert size_attribute.values.count() == 2++ color_new_value_name = "BLACK"+ size_new_value_name = "MINI"+ value_external_reference = "test-value-ext-ref"++ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {+ "addValues": [+ {+ "name": color_new_value_name,+ "externalReference": value_external_reference,+ }+ ]+ },+ },+ {+ "id": graphene.Node.to_global_id("Attribute", size_attribute.id),+ "fields": {+ "addValues": [+ {+ "name": size_new_value_name,+ "externalReference": value_external_reference,+ }+ ]+ },+ },+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ assert data["count"] == 0+ errors_1 = data["results"][0]["errors"]+ errors_2 = data["results"][1]["errors"]+ assert errors_1+ assert errors_2+ assert errors_1[0]["path"] == "addValues.0.externalReference"+ assert (+ errors_1[0]["code"] == AttributeBulkUpdateErrorCode.DUPLICATED_INPUT_ITEM.name+ )++ assert errors_2[0]["path"] == "addValues.0.externalReference"+ assert (+ errors_2[0]["code"] == AttributeBulkUpdateErrorCode.DUPLICATED_INPUT_ITEM.name+ )+++def test_attribute_bulk_update_add_value_with_to_long_name_and_reject_failed_rows(+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ assert color_attribute.values.count() == 2++ new_value_1_name = 60 * "BLACK"+ new_value_2_name = "BLACK"+ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {+ "addValues": [+ {+ "name": new_value_1_name,+ },+ {+ "name": new_value_2_name,+ },+ ]+ },+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {+ "attributes": attributes,+ "errorPolicy": ErrorPolicyEnum.REJECT_FAILED_ROWS.name,+ },+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ color_attribute.refresh_from_db()++ errors = data["results"][0]["errors"]+ assert data["count"] == 0+ assert errors+ assert errors[0]["path"] == "addValues.0.name"+ assert errors[0]["code"] == AttributeBulkUpdateErrorCode.MAX_LENGTH.name+ assert color_attribute.values.count() == 2+++def test_attribute_bulk_update_add_value_with_to_long_name_and_ignore_failed(+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ assert color_attribute.values.count() == 2++ new_value_1_name = 60 * "BLACK"+ new_value_2_name = "BLACK"+ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {+ "addValues": [+ {+ "name": new_value_1_name,+ },+ {+ "name": new_value_2_name,+ },+ ]+ },+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes, "errorPolicy": ErrorPolicyEnum.IGNORE_FAILED.name},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ color_attribute.refresh_from_db()++ errors = data["results"][0]["errors"]+ assert data["count"] == 1+ assert errors+ assert errors[0]["path"] == "addValues.0.name"+ assert errors[0]["code"] == AttributeBulkUpdateErrorCode.MAX_LENGTH.name+ assert color_attribute.values.count() == 3+++def test_attribute_bulk_update_add_value_with_existing_external_ref(+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ assert color_attribute.values.count() == 2+ external_ref = color_attribute.values.first().external_reference+ new_value = "BLACK"+ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {+ "addValues": [+ {+ "name": new_value,+ "externalReference": external_ref,+ },+ ]+ },+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ color_attribute.refresh_from_db()++ errors = data["results"][0]["errors"]+ assert data["count"] == 0+ assert errors+ assert errors[0]["path"] == "addValues.0.externalReference"+ assert errors[0]["code"] == AttributeBulkUpdateErrorCode.UNIQUE.name+ assert color_attribute.values.count() == 2+++def test_attribute_bulk_update_removes_value_with_invalid_id(+ staff_api_client, color_attribute, permission_manage_product_types_and_attributes+):+ # given+ assert color_attribute.values.count() == 2++ invalid_value_id = graphene.Node.to_global_id("Product", 1)++ attributes = [+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "fields": {"removeValues": [invalid_value_id]},+ }+ ]++ # when+ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]++ # then+ errors = data["results"][0]["errors"]+ assert data["count"] == 0+ assert errors+ assert errors[0]["code"] == AttributeBulkUpdateErrorCode.INVALID.name+ assert errors[0]["path"] == "removeValues.0"diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.pyindex 54df61f735..c851e82829 100644--- a/saleor/graphql/core/enums.py+++ b/saleor/graphql/core/enums.py@@ -169,6 +169,12 @@ AttributeBulkCreateErrorCode = graphene.Enum.from_enum(AttributeBulkCreateErrorCode.doc_category = DOC_CATEGORY_ATTRIBUTES+AttributeBulkUpdateErrorCode = graphene.Enum.from_enum(+ attribute_error_codes.AttributeBulkUpdateErrorCode+)+AttributeBulkCreateErrorCode.doc_category = DOC_CATEGORY_ATTRIBUTES++AttributeTranslateErrorCode = graphene.Enum.from_enum(translatable_error_codes.AttributeTranslateErrorCode)diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.pyindex 0cde816d55..9cb20b254c 100644--- a/saleor/graphql/core/types/__init__.py+++ b/saleor/graphql/core/types/__init__.py@@ -5,6 +5,7 @@ from .common import (AppError,AttributeBulkCreateError,AttributeBulkTranslateError,+ AttributeBulkUpdateError,AttributeError,AttributeValueBulkTranslateError,BulkProductError,@@ -90,6 +91,7 @@ __all__ = ["AppError","AttributeError","AttributeBulkCreateError",+ "AttributeBulkUpdateError","AttributeBulkTranslateError","AttributeValueBulkTranslateError","BaseConnection",diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.pyindex d501ec1628..784923a2af 100644--- a/saleor/graphql/core/types/common.py+++ b/saleor/graphql/core/types/common.py@@ -37,6 +37,7 @@ from ..enums import (AccountErrorCode,AppErrorCode,AttributeBulkCreateErrorCode,+ AttributeBulkUpdateErrorCode,AttributeErrorCode,AttributeTranslateErrorCode,AttributeValueTranslateErrorCode,@@ -450,6 +451,13 @@ class AttributeBulkCreateError(BulkError):doc_category = DOC_CATEGORY_ATTRIBUTES+class AttributeBulkUpdateError(BulkError):+ code = AttributeBulkUpdateErrorCode(description="The error code.", required=True)++ class Meta:+ doc_category = DOC_CATEGORY_ATTRIBUTES++class BulkProductError(ProductError):index = graphene.Int(description="Index of an input list item that caused the error."diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 7afb5353b3..8cf66683aa 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -17553,13 +17553,33 @@ type Mutation {- ATTRIBUTE_CREATED (async): An attribute was created."""attributeBulkCreate(- """Input list of products to create."""- attributes: [AttributeBulkCreateInput!]!+ """Input list of attributes to create."""+ attributes: [AttributeCreateInput!]!"""Policies of error handling. DEFAULT: REJECT_EVERYTHING"""errorPolicy: ErrorPolicyEnum): AttributeBulkCreate @doc(category: "Attributes") @webhookEventsInfo(asyncEvents: [ATTRIBUTE_CREATED], syncEvents: [])+ """+ Updates attributes.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.++ Triggers the following webhook events:+ - ATTRIBUTE_UPDATED (async): An attribute was updated. Optionally called when new attribute value was created or deleted.+ - ATTRIBUTE_VALUE_CREATED (async): Called optionally when an attribute value was created.+ - ATTRIBUTE_VALUE_DELETED (async): Called optionally when an attribute value was deleted.+ """+ attributeBulkUpdate(+ """Input list of attributes to update."""+ attributes: [AttributeBulkUpdateInput!]!++ """Policies of error handling. DEFAULT: REJECT_EVERYTHING"""+ errorPolicy: ErrorPolicyEnum+ ): AttributeBulkUpdate @doc(category: "Attributes") @webhookEventsInfo(asyncEvents: [ATTRIBUTE_UPDATED, ATTRIBUTE_VALUE_CREATED, ATTRIBUTE_VALUE_DELETED], syncEvents: [])+"""Creates/updates translations for an attribute.@@ -26990,6 +27010,11 @@ enum AttributeErrorCode @doc(category: "Attributes") {UNIQUE}+"""+Represents an input for create of attribute.++NOTE: Deprecated fields `filterableInStorefront`, `storefrontSearchPosition` and `availableInGrid` are not supported in bulk mutations: `attributeBulkCreate`, `attributeBulkUpdate`.+"""input AttributeCreateInput @doc(category: "Attributes") {"""The input type to use for entering attribute values in the dashboard."""inputType: AttributeInputTypeEnum@@ -27120,6 +27145,11 @@ type AttributeUpdate @doc(category: "Attributes") @webhookEventsInfo(asyncEventserrors: [AttributeError!]!}+"""+Represents an input for update of attribute.++NOTE: Deprecated fields `filterableInStorefront`, `storefrontSearchPosition` and `availableInGrid` are not supported in bulk mutations: `attributeBulkCreate`, `attributeBulkUpdate`.+"""input AttributeUpdateInput @doc(category: "Attributes") {"""Name of an attribute displayed in the interface."""name: String@@ -27269,61 +27299,70 @@ enum AttributeBulkCreateErrorCode @doc(category: "Attributes") {MAX_LENGTH}-input AttributeBulkCreateInput @doc(category: "Attributes") {- """External ID of this attribute."""- externalReference: String-- """The input type to use for entering attribute values in the dashboard."""- inputType: AttributeInputTypeEnum-- """The entity type which can be used as a reference."""- entityType: AttributeEntityTypeEnum+"""+Updates attributes.- """Name of an attribute displayed in the interface."""- name: String!+Added in Saleor 3.15.- """Internal representation of an attribute name."""- slug: String+Note: this API is currently in Feature Preview and can be subject to changes at later point.- """The attribute type."""- type: AttributeTypeEnum!+Triggers the following webhook events:+- ATTRIBUTE_UPDATED (async): An attribute was updated. Optionally called when new attribute value was created or deleted.+- ATTRIBUTE_VALUE_CREATED (async): Called optionally when an attribute value was created.+- ATTRIBUTE_VALUE_DELETED (async): Called optionally when an attribute value was deleted.+"""+type AttributeBulkUpdate @doc(category: "Attributes") @webhookEventsInfo(asyncEvents: [ATTRIBUTE_UPDATED, ATTRIBUTE_VALUE_CREATED, ATTRIBUTE_VALUE_DELETED], syncEvents: []) {+ """Returns how many objects were updated."""+ count: Int!- """The unit of attribute values."""- unit: MeasurementUnitsEnum+ """List of the updated attributes."""+ results: [AttributeBulkUpdateResult!]!+ errors: [AttributeBulkUpdateError!]!+}- """List of attribute's values."""- values: [AttributeBulkCreateValueInput!]+type AttributeBulkUpdateResult @doc(category: "Attributes") {+ """Attribute data."""+ attribute: Attribute- """Whether the attribute requires values to be passed or not."""- valueRequired: Boolean+ """List of errors occurred on update attempt."""+ errors: [AttributeBulkUpdateError!]+}- """Whether the attribute is for variants only."""- isVariantOnly: Boolean+type AttributeBulkUpdateError @doc(category: "Attributes") {+ """+ Path to field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.+ """+ path: String- """Whether the attribute should be visible or not in storefront."""- visibleInStorefront: Boolean+ """The error message."""+ message: String- """Whether the attribute can be filtered in dashboard."""- filterableInDashboard: Boolean+ """The error code."""+ code: AttributeBulkUpdateErrorCode!}-input AttributeBulkCreateValueInput @doc(category: "Attributes") {- """Name of a value displayed in the interface."""- name: String!+"""An enumeration."""+enum AttributeBulkUpdateErrorCode {+ ALREADY_EXISTS+ BLANK+ GRAPHQL_ERROR+ INVALID+ NOT_FOUND+ REQUIRED+ UNIQUE+ DUPLICATED_INPUT_ITEM+ MAX_LENGTH+}- """- Represent value of the attribute value (e.g. color values for swatch attributes).- """- value: String+input AttributeBulkUpdateInput @doc(category: "Attributes") {+ """ID of an attribute to update."""+ id: ID- """External ID of this attribute value."""+ """External ID of this attribute."""externalReference: String- """URL of the file attribute. Every time, a new value is created."""- fileUrl: String-- """File content type."""- contentType: String+ """Fields to update."""+ fields: AttributeUpdateInput!}"""