Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Product and Variant bulk mutations (#11392)
SzymJceff598575dc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 076b848ad0..47826a211c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,10 @@ All notable, unreleased changes to this project will be documented in this file.### Breaking changes+### Preview+- Add new error handling policies in `ProductVariantBulkCreate`- #11392 by @SzymJ+- Add `ProductVariantBulkUpdate` mutation - #11392 by @SzymJ+### GraphQL API- Add `webhookDryRun` mutation - #11548 by @zedziordiff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.pyindex f033d5e7db..38de8c4fd2 100644--- a/saleor/graphql/core/enums.py+++ b/saleor/graphql/core/enums.py@@ -101,6 +101,34 @@ VolumeUnitsEnum = to_enum(VolumeUnits)WeightUnitsEnum = to_enum(WeightUnits)unit_enums = [DistanceUnitsEnum, AreaUnitsEnum, VolumeUnitsEnum, WeightUnitsEnum]++class ErrorPolicy:+ IGNORE_FAILED = "ignore_failed"+ REJECT_EVERYTHING = "reject_everything"+ REJECT_FAILED_ROWS = "reject_failed_rows"++ CHOICES = [+ (IGNORE_FAILED, "Ignore failed"),+ (REJECT_EVERYTHING, "Reject everything"),+ (REJECT_FAILED_ROWS, "Reject failed rows"),+ ]+++def error_policy_enum_description(enum):+ if enum == ErrorPolicyEnum.IGNORE_FAILED:+ return (+ "Save what is possible within a single row. If there are errors in an "+ "input data row, try to save it partially and skip the invalid part."+ )+ if enum == ErrorPolicyEnum.REJECT_FAILED_ROWS:+ return "Reject rows with errors."+ if enum == ErrorPolicyEnum.REJECT_EVERYTHING:+ return "Reject all rows if there is at least one error in any of them."+ return None+++ErrorPolicyEnum = to_enum(ErrorPolicy, description=error_policy_enum_description)+AccountErrorCode = graphene.Enum.from_enum(account_error_codes.AccountErrorCode)AppErrorCode = graphene.Enum.from_enum(app_error_codes.AppErrorCode)AttributeErrorCode = graphene.Enum.from_enum(attribute_error_codes.AttributeErrorCode)@@ -141,6 +169,9 @@ PermissionGroupErrorCode = graphene.Enum.from_enum(account_error_codes.PermissionGroupErrorCode)ProductErrorCode = graphene.Enum.from_enum(product_error_codes.ProductErrorCode)+ProductVariantBulkErrorCode = graphene.Enum.from_enum(+ product_error_codes.ProductVariantBulkErrorCode+)CollectionErrorCode = graphene.Enum.from_enum(product_error_codes.CollectionErrorCode)ShopErrorCode = graphene.Enum.from_enum(core_error_codes.ShopErrorCode)ShippingErrorCode = graphene.Enum.from_enum(shipping_error_codes.ShippingErrorCode)diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.pyindex a6c4e4af8d..dc7bdcb91e 100644--- a/saleor/graphql/core/types/__init__.py+++ b/saleor/graphql/core/types/__init__.py@@ -25,6 +25,7 @@ from .common import (InvoiceError,Job,LanguageDisplay,+ MediaInput,MenuError,MetadataError,NonNullList,@@ -39,6 +40,7 @@ from .common import (PriceRangeInput,ProductChannelListingError,ProductError,+ ProductVariantBulkError,ProductWithoutVariantError,SeoInput,ShippingError,@@ -91,6 +93,7 @@ __all__ = ["InvoiceError","Job","LanguageDisplay",+ "MediaInput","MenuError","MetadataError","ModelObjectType",@@ -109,6 +112,7 @@ __all__ = ["ProductChannelListingError","ProductError","ProductWithoutVariantError",+ "ProductVariantBulkError","ReducedRate","SeoInput","ShippingError",diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.pyindex 1da1aec142..2ac9eb3f68 100644--- a/saleor/graphql/core/types/common.py+++ b/saleor/graphql/core/types/common.py@@ -32,6 +32,7 @@ from ..enums import (PermissionGroupErrorCode,PluginErrorCode,ProductErrorCode,+ ProductVariantBulkErrorCode,ShippingErrorCode,ShopErrorCode,StockErrorCode,@@ -51,6 +52,7 @@ from ..enums import (from ..scalars import Date, PositiveDecimalfrom ..tracing import traced_resolverfrom .money import VAT+from .upload import Uploadif TYPE_CHECKING:from .. import ResolveInfo@@ -317,6 +319,30 @@ class BulkProductError(ProductError):)+class ProductVariantBulkError(Error):+ code = ProductVariantBulkErrorCode(description="The error code.", required=True)+ attributes = NonNullList(+ graphene.ID,+ description="List of attributes IDs which causes the error.",+ required=False,+ )+ values = NonNullList(+ graphene.ID,+ description="List of attribute values IDs which causes the error.",+ required=False,+ )+ warehouses = NonNullList(+ graphene.ID,+ description="List of warehouse IDs which causes the error.",+ required=False,+ )+ channels = NonNullList(+ graphene.ID,+ description="List of channel IDs which causes the error.",+ required=False,+ )++class ShopError(Error):code = ShopErrorCode(description="The error code.", required=True)@@ -545,3 +571,13 @@ class ThumbnailField(graphene.Field):kwargs["size"] = self.sizekwargs["format"] = self.formatsuper().__init__(of_type, *args, **kwargs)+++class MediaInput(graphene.InputObjectType):+ alt = graphene.String(description="Alt text for a product media.")+ image = Upload(+ required=False, description="Represents an image file in a multipart request."+ )+ media_url = graphene.String(+ required=False, description="Represents an URL to an external media."+ )diff --git a/saleor/graphql/product/bulk_mutations/__init__.py b/saleor/graphql/product/bulk_mutations/__init__.pyindex e69de29bb2..9154d00410 100644--- a/saleor/graphql/product/bulk_mutations/__init__.py+++ b/saleor/graphql/product/bulk_mutations/__init__.py@@ -0,0 +1,25 @@+from .category_bulk_delete import CategoryBulkDelete+from .collection_bulk_delete import CollectionBulkDelete+from .product_bulk_delete import ProductBulkDelete+from .product_media_bulk_delete import ProductMediaBulkDelete+from .product_type_bulk_delete import ProductTypeBulkDelete+from .product_variant_bulk_create import ProductVariantBulkCreate+from .product_variant_bulk_delete import ProductVariantBulkDelete+from .product_variant_bulk_update import ProductVariantBulkUpdate+from .product_variant_stocks_create import ProductVariantStocksCreate+from .product_variant_stocks_delete import ProductVariantStocksDelete+from .product_variant_stocks_update import ProductVariantStocksUpdate++__all__ = [+ "CategoryBulkDelete",+ "CollectionBulkDelete",+ "ProductBulkDelete",+ "ProductMediaBulkDelete",+ "ProductTypeBulkDelete",+ "ProductVariantBulkCreate",+ "ProductVariantBulkDelete",+ "ProductVariantBulkUpdate",+ "ProductVariantStocksCreate",+ "ProductVariantStocksDelete",+ "ProductVariantStocksUpdate",+]diff --git a/saleor/graphql/product/bulk_mutations/category_bulk_delete.py b/saleor/graphql/product/bulk_mutations/category_bulk_delete.pynew file mode 100644index 0000000000..601d4ff893--- /dev/null+++ b/saleor/graphql/product/bulk_mutations/category_bulk_delete.py@@ -0,0 +1,29 @@+import graphene++from ....permission.enums import ProductPermissions+from ....product import models+from ....product.utils import delete_categories+from ...core.mutations import ModelBulkDeleteMutation+from ...core.types import NonNullList, ProductError+from ...plugins.dataloaders import get_plugin_manager_promise+from ..types import Category+++class CategoryBulkDelete(ModelBulkDeleteMutation):+ class Arguments:+ ids = NonNullList(+ graphene.ID, required=True, description="List of category IDs to delete."+ )++ class Meta:+ description = "Deletes categories."+ model = models.Category+ object_type = Category+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = ProductError+ error_type_field = "product_errors"++ @classmethod+ def bulk_action(cls, info, queryset):+ manager = get_plugin_manager_promise(info.context).get()+ delete_categories(queryset.values_list("pk", flat=True), manager)diff --git a/saleor/graphql/product/bulk_mutations/collection_bulk_delete.py b/saleor/graphql/product/bulk_mutations/collection_bulk_delete.pynew file mode 100644index 0000000000..411057f149--- /dev/null+++ b/saleor/graphql/product/bulk_mutations/collection_bulk_delete.py@@ -0,0 +1,39 @@+import graphene++from ....permission.enums import ProductPermissions+from ....product import models+from ...core.mutations import ModelBulkDeleteMutation+from ...core.types import CollectionError, NonNullList+from ...plugins.dataloaders import get_plugin_manager_promise+from ..types import Collection+++class CollectionBulkDelete(ModelBulkDeleteMutation):+ class Arguments:+ ids = NonNullList(+ graphene.ID, required=True, description="List of collection IDs to delete."+ )++ class Meta:+ description = "Deletes collections."+ model = models.Collection+ object_type = Collection+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = CollectionError+ error_type_field = "collection_errors"++ @classmethod+ def bulk_action(cls, info, queryset):+ collections_ids = queryset.values_list("id", flat=True)+ products = list(+ models.Product.objects.prefetched_for_webhook(single_object=False)+ .filter(collections__in=collections_ids)+ .distinct()+ )+ manager = get_plugin_manager_promise(info.context).get()+ for collection in queryset.iterator():+ manager.collection_deleted(collection)+ queryset.delete()++ for product in products:+ manager.product_updated(product)diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_bulk_delete.pynew file mode 100644index 0000000000..733c794330--- /dev/null+++ b/saleor/graphql/product/bulk_mutations/product_bulk_delete.py@@ -0,0 +1,99 @@+from collections import defaultdict++import graphene+from django.core.exceptions import ValidationError++from ....attribute import AttributeInputType+from ....attribute import models as attribute_models+from ....core.tracing import traced_atomic_transaction+from ....order import events as order_events+from ....order import models as order_models+from ....order.tasks import recalculate_orders_task+from ....permission.enums import ProductPermissions+from ....product import models+from ...app.dataloaders import get_app_promise+from ...core import ResolveInfo+from ...core.mutations import ModelBulkDeleteMutation+from ...core.types import NonNullList, ProductError+from ...plugins.dataloaders import get_plugin_manager_promise+from ..types import Product+from ..utils import get_draft_order_lines_data_for_variants+++class ProductBulkDelete(ModelBulkDeleteMutation):+ class Arguments:+ ids = NonNullList(+ graphene.ID, required=True, description="List of product IDs to delete."+ )++ class Meta:+ description = "Deletes products."+ model = models.Product+ object_type = Product+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = ProductError+ error_type_field = "product_errors"++ @classmethod+ @traced_atomic_transaction()+ def perform_mutation( # type: ignore[override]+ cls, _root, info: ResolveInfo, /, *, ids+ ):+ try:+ pks = cls.get_global_ids_or_error(ids, Product)+ except ValidationError as error:+ return 0, error+ product_to_variant = list(+ models.ProductVariant.objects.filter(product__pk__in=pks).values_list(+ "product_id", "id"+ )+ )+ variants_ids = [variant_id for _, variant_id in product_to_variant]++ cls.delete_assigned_attribute_values(pks)++ draft_order_lines_data = get_draft_order_lines_data_for_variants(variants_ids)++ response = super().perform_mutation(+ _root, info, ids=ids, product_to_variant=product_to_variant+ )++ # delete order lines for deleted variants+ order_models.OrderLine.objects.filter(+ pk__in=draft_order_lines_data.line_pks+ ).delete()++ app = get_app_promise(info.context).get()+ # run order event for deleted lines+ for order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():+ order_events.order_line_product_removed_event(+ order, info.context.user, app, order_lines+ )++ order_pks = draft_order_lines_data.order_pks+ if order_pks:+ recalculate_orders_task.delay(list(order_pks))++ return response++ @staticmethod+ def delete_assigned_attribute_values(instance_pks):+ attribute_models.AttributeValue.objects.filter(+ productassignments__product_id__in=instance_pks,+ attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,+ ).delete()++ @classmethod+ def bulk_action( # type: ignore[override]+ cls, info: ResolveInfo, queryset, /, *, product_to_variant+ ):+ product_variant_map = defaultdict(list)+ for product, variant in product_to_variant:+ product_variant_map[product].append(variant)++ products = [product for product in queryset]+ queryset.delete()+ manager = get_plugin_manager_promise(info.context).get()+ for product in products:+ variants = product_variant_map.get(product.id, [])+ manager.product_deleted(product, variants)diff --git a/saleor/graphql/product/bulk_mutations/product_media_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_media_bulk_delete.pynew file mode 100644index 0000000000..237d6ffe30--- /dev/null+++ b/saleor/graphql/product/bulk_mutations/product_media_bulk_delete.py@@ -0,0 +1,24 @@+import graphene++from ....permission.enums import ProductPermissions+from ....product import models+from ...core.mutations import ModelBulkDeleteMutation+from ...core.types import NonNullList, ProductError+from ..types import ProductMedia+++class ProductMediaBulkDelete(ModelBulkDeleteMutation):+ class Arguments:+ ids = NonNullList(+ graphene.ID,+ required=True,+ description="List of product media IDs to delete.",+ )++ class Meta:+ description = "Deletes product media."+ model = models.ProductMedia+ object_type = ProductMedia+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = ProductError+ error_type_field = "product_errors"diff --git a/saleor/graphql/product/bulk_mutations/product_type_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_type_bulk_delete.pynew file mode 100644index 0000000000..df8328652a--- /dev/null+++ b/saleor/graphql/product/bulk_mutations/product_type_bulk_delete.py@@ -0,0 +1,52 @@+import graphene+from django.core.exceptions import ValidationError+from django.db.models import Q++from ....attribute import AttributeInputType+from ....attribute import models as attribute_models+from ....core.tracing import traced_atomic_transaction+from ....permission.enums import ProductTypePermissions+from ....product import models+from ...core import ResolveInfo+from ...core.mutations import ModelBulkDeleteMutation+from ...core.types import NonNullList, ProductError+from ..types import ProductType+++class ProductTypeBulkDelete(ModelBulkDeleteMutation):+ class Arguments:+ ids = NonNullList(+ graphene.ID,+ required=True,+ description="List of product type IDs to delete.",+ )++ class Meta:+ description = "Deletes product types."+ model = models.ProductType+ object_type = ProductType+ permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)+ error_type_class = ProductError+ error_type_field = "product_errors"++ @classmethod+ @traced_atomic_transaction()+ def perform_mutation( # type: ignore[override]+ cls, _root, info: ResolveInfo, /, *, ids+ ):+ try:+ pks = cls.get_global_ids_or_error(ids, ProductType)+ except ValidationError as error:+ return 0, error+ cls.delete_assigned_attribute_values(pks)+ return super().perform_mutation(_root, info, ids=ids)++ @staticmethod+ def delete_assigned_attribute_values(instance_pks):+ attribute_models.AttributeValue.objects.filter(+ Q(attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES)+ & (+ Q(productassignments__assignment__product_type_id__in=instance_pks)+ | Q(variantassignments__assignment__product_type_id__in=instance_pks)+ )+ ).delete()diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.pynew file mode 100644index 0000000000..2510dde758--- /dev/null+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py@@ -0,0 +1,796 @@+from collections import defaultdict+from typing import cast++import graphene+from django.core.exceptions import ValidationError+from django.db import transaction+from django.db.utils import IntegrityError+from graphene.types import InputObjectType+from graphene.utils.str_converters import to_camel_case++from ....core.tracing import traced_atomic_transaction+from ....permission.enums import ProductPermissions+from ....product import models+from ....product.error_codes import ProductVariantBulkErrorCode+from ....product.search import update_product_search_vector+from ....product.tasks import update_product_discounted_price_task+from ....product.utils.variants import generate_and_set_variant_name+from ....warehouse import models as warehouse_models+from ...attribute.utils import AttributeAssignmentMixin+from ...channel import ChannelContext+from ...core.descriptions import ADDED_IN_311, DEPRECATED_IN_3X_FIELD, PREVIEW_FEATURE+from ...core.enums import ErrorPolicyEnum+from ...core.mutations import (+ BaseMutation,+ ModelMutation,+ validation_error_to_error_type,+)+from ...core.types import BulkProductError, NonNullList, ProductVariantBulkError+from ...core.utils import get_duplicated_values+from ...core.validators import validate_price_precision+from ...plugins.dataloaders import get_plugin_manager_promise+from ..mutations.channels import ProductVariantChannelListingAddInput+from ..mutations.product.product_create import StockInput+from ..mutations.product_variant.product_variant_create import (+ ProductVariantCreate,+ ProductVariantInput,+)+from ..types import ProductVariant+from ..utils import clean_variant_sku, get_used_variants_attribute_values+++class ProductVariantBulkResult(graphene.ObjectType):+ product_variant = graphene.Field(+ ProductVariant, required=False, description="Product variant data."+ )+ errors = NonNullList(+ ProductVariantBulkError,+ required=False,+ description="List of errors occurred on create attempt.",+ )+++class BulkAttributeValueInput(InputObjectType):+ id = graphene.ID(description="ID of the selected attribute.")+ values = NonNullList(+ graphene.String,+ required=False,+ description=(+ "The value or slug of an attribute to resolve. "+ "If the passed value is non-existent, it will be created."+ ),+ )+ boolean = graphene.Boolean(+ required=False,+ description=(+ "The boolean value of an attribute to resolve. "+ "If the passed value is non-existent, it will be created."+ ),+ )+++class ProductVariantBulkCreateInput(ProductVariantInput):+ attributes = NonNullList(+ BulkAttributeValueInput,+ required=True,+ description="List of attributes specific to this variant.",+ )+ stocks = NonNullList(+ StockInput,+ description="Stocks of a product available for sale.",+ required=False,+ )+ channel_listings = NonNullList(+ ProductVariantChannelListingAddInput,+ description="List of prices assigned to channels.",+ required=False,+ )+ sku = graphene.String(description="Stock keeping unit.")+++class ProductVariantBulkCreate(BaseMutation):+ count = graphene.Int(+ required=True,+ default_value=0,+ description="Returns how many objects were created.",+ )+ product_variants = NonNullList(+ ProductVariant,+ required=True,+ default_value=[],+ description="List of the created variants." + DEPRECATED_IN_3X_FIELD,+ )++ results = NonNullList(+ ProductVariantBulkResult,+ required=True,+ default_value=[],+ description="List of the created variants." + ADDED_IN_311,+ )++ class Arguments:+ variants = NonNullList(+ ProductVariantBulkCreateInput,+ required=True,+ description="Input list of product variants to create.",+ )+ product_id = graphene.ID(+ description="ID of the product to create the variants for.",+ name="product",+ required=True,+ )+ error_policy = ErrorPolicyEnum(+ required=False,+ default_value=ErrorPolicyEnum.REJECT_EVERYTHING.value,+ description=(+ "Policies of error handling. DEFAULT: "+ + ErrorPolicyEnum.REJECT_EVERYTHING.name+ + ADDED_IN_311+ + PREVIEW_FEATURE+ ),+ )++ class Meta:+ description = "Creates product variants for a given product."+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = BulkProductError+ error_type_field = "bulk_product_errors"++ @classmethod+ def clean_attributes(+ cls,+ cleaned_input,+ product_type,+ variant_attributes_ids,+ used_attribute_values,+ errors,+ variant_index,+ index_error_map,+ ):++ attributes_errors_count = 0+ if attributes := cleaned_input.get("attributes"):+ attributes_ids = {attr["id"] for attr in attributes or []}+ invalid_attributes = attributes_ids - variant_attributes_ids+ if len(invalid_attributes) > 0:+ message = "Given attributes are not a variant attributes."+ code = ProductVariantBulkErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.value+ index_error_map[variant_index].append(+ ProductVariantBulkError(+ field="attributes", message=message, code=code+ )+ )+ if errors is not None:+ errors["attributes"].append(+ ValidationError(+ message,+ code=code,+ params={+ "attributes": invalid_attributes,+ "index": variant_index,+ },+ )+ )+ attributes_errors_count += 1++ if product_type.has_variants:+ try:+ cleaned_attributes = ProductVariantCreate.clean_attributes(+ attributes, product_type+ )+ ProductVariantCreate.validate_duplicated_attribute_values(+ cleaned_attributes, used_attribute_values, None+ )+ cleaned_input["attributes"] = cleaned_attributes+ except ValidationError as exc:+ index_error_map[variant_index].append(+ ProductVariantBulkError(+ field="attributes", message=exc.message, code=exc.code+ )+ )+ if errors is not None:+ exc.params = {"index": variant_index}+ errors["attributes"].append(exc)+ attributes_errors_count += 1+ else:+ message = "Cannot assign attributes for product type without variants"+ index_error_map[variant_index].append(+ ProductVariantBulkError(+ field="attributes",+ message=message,+ code=ProductVariantBulkErrorCode.INVALID.value,+ )+ )+ if errors is not None:+ errors["attributes"].append(+ ValidationError(+ message,+ code=ProductVariantBulkErrorCode.INVALID.value,+ params={+ "attributes": invalid_attributes,+ "index": variant_index,+ },+ )+ )+ attributes_errors_count += 1+ return attributes_errors_count++ @classmethod+ def clean_price(+ cls,+ price,+ field_name,+ currency,+ channel_id,+ variant_index,+ errors,+ index_error_map,+ ):+ try:+ validate_price_precision(price, currency)+ except ValidationError as error:+ index_error_map[variant_index].append(+ ProductVariantBulkError(+ field=to_camel_case(field_name),+ message=error.message,+ code=ProductVariantBulkErrorCode.INVALID_PRICE.value,+ channels=[channel_id],+ )+ )+ if errors is not None:+ error.code = ProductVariantBulkErrorCode.INVALID_PRICE.value+ error.params = {+ "channels": [channel_id],+ "index": variant_index,+ }+ errors[field_name].append(error)++ @classmethod+ def clean_channel_listings(+ cls,+ cleaned_input,+ product_channel_global_id_to_instance_map,+ errors,+ variant_index,+ index_error_map,+ ):+ channel_listings = cleaned_input.get("channel_listings")+ channel_ids = [+ channel_listing["channel_id"] for channel_listing in channel_listings+ ]+ listings_to_create = []++ duplicates = get_duplicated_values(channel_ids)+ if duplicates:+ message = "Duplicated channel ID."+ index_error_map[variant_index].append(+ ProductVariantBulkError(+ field="channelListings",+ message=message,+ code=ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.value,+ channels=duplicates,+ )+ )+ if errors is not None:+ errors["channel_listings"] = ValidationError(+ message=message,+ code=ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.value,+ params={"channels": duplicates, "index": variant_index},+ )++ channels_not_assigned_to_product = [+ channel_id+ for channel_id in channel_ids+ if channel_id not in product_channel_global_id_to_instance_map.keys()+ ]++ if channels_not_assigned_to_product:+ message = "Product not available in channels."+ code = ProductVariantBulkErrorCode.PRODUCT_NOT_ASSIGNED_TO_CHANNEL.value+ index_error_map[variant_index].append(+ ProductVariantBulkError(+ field="channelId",+ message=message,+ code=code,+ channels=channels_not_assigned_to_product,+ )+ )+ if errors is not None:+ errors["channel_id"].append(+ ValidationError(+ message=message,+ code=code,+ params={+ "index": variant_index,+ "channels": channels_not_assigned_to_product,+ },+ )+ )++ for channel_listing in channel_listings:+ channel_id = channel_listing["channel_id"]++ if (+ channel_id in channels_not_assigned_to_product+ or channel_id in duplicates+ ):+ continue++ channel_listing["channel"] = product_channel_global_id_to_instance_map[+ channel_id+ ]+ price = channel_listing.get("price")+ cost_price = channel_listing.get("cost_price")+ currency_code = channel_listing["channel"].currency_code++ errors_count_before_prices = len(index_error_map[variant_index])+ cls.clean_price(+ price,+ "price",+ currency_code,+ channel_id,+ variant_index,+ errors,+ index_error_map,+ )+ cls.clean_price(+ cost_price,+ "cost_price",+ currency_code,+ channel_id,+ variant_index,+ errors,+ index_error_map,+ )++ if len(index_error_map[variant_index]) > errors_count_before_prices:+ continue++ listings_to_create.append(channel_listing)++ cleaned_input["channel_listings"] = listings_to_create++ @classmethod+ def clean_stocks(+ cls,+ cleaned_input,+ warehouse_global_id_to_instance_map,+ errors,+ variant_index,+ index_error_map,+ ):+ stocks = cleaned_input.get("stocks")+ stocks_to_create = []+ warehouse_ids = [stock["warehouse"] for stock in stocks]++ wrong_warehouse_ids = {+ warehouse_id+ for warehouse_id in warehouse_ids+ if warehouse_id not in warehouse_global_id_to_instance_map.keys()+ }++ if wrong_warehouse_ids:+ message = "Not existing warehouse ID."+ index_error_map[variant_index].append(+ ProductVariantBulkError(+ field="warehouses",+ message=message,+ code=ProductVariantBulkErrorCode.NOT_FOUND.value,+ warehouses=wrong_warehouse_ids,+ )+ )+ if errors is not None:+ errors["warehouses"] = ValidationError(+ message,+ code=ProductVariantBulkErrorCode.NOT_FOUND.value,+ params={"warehouses": wrong_warehouse_ids, "index": variant_index},+ )++ duplicates = get_duplicated_values(warehouse_ids)+ if duplicates:+ message = "Duplicated warehouse ID."+ index_error_map[variant_index].append(+ ProductVariantBulkError(+ field="stocks",+ message=message,+ code=ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.value,+ warehouses=duplicates,+ )+ )+ if errors is not None:+ errors["stocks"] = ValidationError(+ message,+ code=ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.value,+ params={"warehouses": duplicates, "index": variant_index},+ )++ for stock_data in stocks:+ if (+ stock_data["warehouse"] in duplicates+ or stock_data["warehouse"] in wrong_warehouse_ids+ ):+ continue+ else:+ stock_data["warehouse"] = warehouse_global_id_to_instance_map[+ stock_data["warehouse"]+ ]+ stocks_to_create.append(stock_data)++ cleaned_input["stocks"] = stocks_to_create++ @classmethod+ def add_indexes_to_errors(cls, index, error, error_dict, index_error_map):+ """Append errors with index in params to mutation error dict."""+ for key, value in error.error_dict.items():+ for e in value:+ if e.params:+ e.params["index"] = index+ else:+ e.params = {"index": index}+ index_error_map[index].append(+ ProductVariantBulkError(+ field=to_camel_case(key),+ message=e.messages[0],+ code=e.code,+ )+ )+ error_dict[key].extend(value)++ @classmethod+ def save(cls, info, instance, cleaned_input):+ instance.save()++ attributes = cleaned_input.get("attributes")+ if attributes:+ AttributeAssignmentMixin.save(instance, attributes)+ if not instance.name:+ generate_and_set_variant_name(instance, cleaned_input.get("sku"))++ @classmethod+ def create_variants(+ cls, info, cleaned_inputs_map, product, errors, index_error_map+ ):+ instances_data_and_errors_list = []++ 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+ try:+ instance = models.ProductVariant()+ cleaned_input["product"] = product+ instance = cls.construct_instance(instance, cleaned_input)+ cls.clean_instance(info, instance)+ instances_data_and_errors_list.append(+ {+ "instance": instance,+ "errors": index_error_map[index],+ "cleaned_input": cleaned_input,+ }+ )+ except ValidationError as exc:+ cls.add_indexes_to_errors(index, exc, errors, index_error_map)+ instances_data_and_errors_list.append(+ {"instance": None, "errors": index_error_map[index]}+ )+ return instances_data_and_errors_list++ @classmethod+ def validate_base_fields(+ cls, cleaned_input, duplicated_sku, errors, index_error_map, index+ ):+ base_fields_errors_count = 0+ weight = cleaned_input.get("weight")+ if weight and weight.value < 0:+ message = "Product variant can't have negative weight."+ code = ProductVariantBulkErrorCode.INVALID.value+ index_error_map[index].append(+ ProductVariantBulkError(+ field="weight",+ message=message,+ code=code,+ )+ )+ if errors is not None:+ errors["weight"].append(+ ValidationError(message, code, params={"index": index})+ )+ base_fields_errors_count += 1++ quantity_limit = cleaned_input.get("quantity_limit_per_customer")+ if quantity_limit is not None and quantity_limit < 1:+ message = (+ "Product variant can't have "+ "quantity_limit_per_customer lower than 1."+ )+ code = ProductVariantBulkErrorCode.INVALID.value+ index_error_map[index].append(+ ProductVariantBulkError(+ field="quantity_limit_per_customer",+ message=message,+ code=code,+ )+ )+ if errors is not None:+ errors["quantity_limit_per_customer"].append(+ ValidationError(message, code, params={"index": index})+ )+ base_fields_errors_count += 1++ sku = cleaned_input.get("sku")+ if sku is not None and sku in duplicated_sku:+ message = "Duplicated SKU."+ code = ProductVariantBulkErrorCode.UNIQUE.value+ index_error_map[index].append(+ ProductVariantBulkError(field="sku", message=message, code=code)+ )+ if errors is not None:+ errors["sku"].append(+ ValidationError(message, code, params={"index": index})+ )+ base_fields_errors_count += 1++ return base_fields_errors_count++ @classmethod+ def clean_variant(+ cls,+ info,+ variant_data,+ product_channel_global_id_to_instance_map,+ warehouse_global_id_to_instance_map,+ used_attribute_values,+ variant_attributes_ids,+ duplicated_sku,+ index_error_map,+ index,+ errors,+ input_class=ProductVariantBulkCreateInput,+ ):+ cleaned_input = ModelMutation.clean_input(+ info, None, variant_data, input_cls=input_class+ )++ sku = cleaned_input.get("sku")+ if sku is not None:+ cleaned_input["sku"] = clean_variant_sku(sku)++ preorder_settings = cleaned_input.get("preorder")+ if preorder_settings:+ cleaned_input["is_preorder"] = True+ cleaned_input["preorder_global_threshold"] = preorder_settings.get(+ "global_threshold"+ )+ cleaned_input["preorder_end_date"] = preorder_settings.get("end_date")++ base_fields_errors_count = cls.validate_base_fields(+ cleaned_input, duplicated_sku, errors, index_error_map, index+ )++ attributes_errors_count = cls.clean_attributes(+ cleaned_input,+ variant_data["product_type"],+ variant_attributes_ids,+ used_attribute_values,+ errors,+ index,+ index_error_map,+ )++ if cleaned_input.get("channel_listings"):+ cls.clean_channel_listings(+ cleaned_input,+ product_channel_global_id_to_instance_map,+ errors,+ index,+ index_error_map,+ )++ if cleaned_input.get("stocks"):+ cls.clean_stocks(+ cleaned_input,+ warehouse_global_id_to_instance_map,+ errors,+ index,+ index_error_map,+ )++ if base_fields_errors_count > 0 or attributes_errors_count > 0:+ return None+ else:+ return cleaned_input if cleaned_input else None++ @classmethod+ def clean_variants(cls, info, variants, product, errors, index_error_map):+ cleaned_inputs_map = {}+ warehouse_global_id_to_instance_map = {+ graphene.Node.to_global_id("Warehouse", warehouse.id): warehouse+ for warehouse in warehouse_models.Warehouse.objects.all()+ }+ product_channel_global_id_to_instance_map = {+ graphene.Node.to_global_id("Channel", listing.channel_id): listing.channel+ for listing in models.ProductChannelListing.objects.select_related(+ "channel"+ ).filter(product=product.id)+ }+ used_attribute_values = get_used_variants_attribute_values(product)+ variant_attributes_ids = {+ graphene.Node.to_global_id("Attribute", attr_id)+ for attr_id in list(+ product.product_type.variant_attributes.all().values_list(+ "pk", flat=True+ )+ )+ }+ duplicated_sku = get_duplicated_values(+ [variant.sku for variant in variants if variant.sku]+ )++ for index, variant_data in enumerate(variants):+ variant_data["product_type"] = product.product_type+ variant_data["product"] = product++ cleaned_input = cls.clean_variant(+ info,+ variant_data,+ product_channel_global_id_to_instance_map,+ warehouse_global_id_to_instance_map,+ used_attribute_values,+ variant_attributes_ids,+ duplicated_sku,+ index_error_map,+ index,+ errors,+ )+ cleaned_inputs_map[index] = cleaned_input++ return cleaned_inputs_map++ @classmethod+ def create_variant_channel_listings(cls, variant, cleaned_input):+ channel_listings_data = cleaned_input.get("channel_listings")++ if not channel_listings_data:+ return++ variant_channel_listings = []+ for channel_listing_data in channel_listings_data:+ channel = channel_listing_data["channel"]+ price = channel_listing_data["price"]+ cost_price = channel_listing_data.get("cost_price")+ preorder_quantity_threshold = channel_listing_data.get("preorder_threshold")+ variant_channel_listings.append(+ models.ProductVariantChannelListing(+ channel=channel,+ variant=variant,+ price_amount=price,+ cost_price_amount=cost_price,+ currency=channel.currency_code,+ preorder_quantity_threshold=preorder_quantity_threshold,+ )+ )+ models.ProductVariantChannelListing.objects.bulk_create(+ variant_channel_listings+ )++ @classmethod+ @traced_atomic_transaction()+ def save_variants(cls, info, instances_data_with_errors_list, product):+ for instance_data in instances_data_with_errors_list:+ instance = instance_data["instance"]+ if instance:+ cleaned_input = instance_data.pop("cleaned_input")+ cls.save(info, instance_data["instance"], cleaned_input)+ cls.create_variant_stocks(instance, cleaned_input)+ cls.create_variant_channel_listings(instance, cleaned_input)++ if not product.default_variant:+ product.default_variant = instance+ product.save(update_fields=["default_variant", "updated_at"])++ @classmethod+ def create_variant_stocks(cls, variant, cleaned_input):+ stocks = cleaned_input.get("stocks")++ if not stocks:+ return++ try:+ warehouse_models.Stock.objects.bulk_create(+ [+ warehouse_models.Stock(+ product_variant=variant,+ warehouse=stock_data["warehouse"],+ quantity=stock_data["quantity"],+ )+ for stock_data in stocks+ ]+ )+ except IntegrityError:+ msg = "Stock for one of warehouses already exists for this product variant."+ raise ValidationError(msg)++ @classmethod+ @traced_atomic_transaction()+ def perform_mutation(cls, _root, info, **data):+ product = cast(+ models.Product,+ cls.get_node_or_error(info, data["product_id"], only_type="Product"),+ )+ error_policy = data["error_policy"]+ errors: dict = defaultdict(list)+ index_error_map: dict = defaultdict(list)++ cleaned_inputs_map = cls.clean_variants(+ info, data["variants"], product, errors, index_error_map+ )+ instances_data_with_errors_list = cls.create_variants(+ info, cleaned_inputs_map, product, errors, index_error_map+ )++ if errors:+ if error_policy == ErrorPolicyEnum.REJECT_EVERYTHING.value:+ results = [+ ProductVariantBulkResult(+ product_variant=None, errors=data.get("errors")+ )+ for data in instances_data_with_errors_list+ ]+ return ProductVariantBulkCreate(+ count=0,+ results=results,+ errors=validation_error_to_error_type(+ ValidationError(errors), cls._meta.error_type_class+ ),+ )++ if error_policy == ErrorPolicyEnum.REJECT_FAILED_ROWS.value:+ for data in instances_data_with_errors_list:+ if data["errors"] and data["instance"]:+ data["instance"] = None++ cls.save_variants(info, instances_data_with_errors_list, product)++ instances = [+ ChannelContext(node=instance_data["instance"], channel_slug=None)+ for instance_data in instances_data_with_errors_list+ if instance_data["instance"]+ ]++ # Recalculate the "discounted price" for the parent product+ update_product_discounted_price_task.delay(product.pk)++ update_product_search_vector(product)+ manager = get_plugin_manager_promise(info.context).get()+ transaction.on_commit(+ lambda: [+ manager.product_variant_created(instance.node) for instance in instances+ ]+ )++ results = [+ ProductVariantBulkResult(+ product_variant=ChannelContext(+ node=data.get("instance"), channel_slug=None+ ),+ errors=data.get("errors"),+ )+ if data.get("instance")+ else ProductVariantBulkResult(+ product_variant=None, errors=data.get("errors")+ )+ for data in instances_data_with_errors_list+ ]++ return ProductVariantBulkCreate(+ count=len(instances),+ product_variants=instances,+ results=results,+ errors=validation_error_to_error_type(+ ValidationError(errors), cls._meta.error_type_class+ )+ if errors+ else None,+ )diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.pynew file mode 100644index 0000000000..74ab9bac95--- /dev/null+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py@@ -0,0 +1,165 @@+from typing import Iterable++import graphene+from django.core.exceptions import ValidationError+from django.db import transaction+from django.db.models import Exists, OuterRef, Subquery+from django.db.models.fields import IntegerField+from django.db.models.functions import Coalesce++from ....attribute import AttributeInputType+from ....attribute import models as attribute_models+from ....core.postgres import FlatConcatSearchVector+from ....core.tracing import traced_atomic_transaction+from ....order import events as order_events+from ....order import models as order_models+from ....order.tasks import recalculate_orders_task+from ....permission.enums import ProductPermissions+from ....product import models+from ....product.search import prepare_product_search_vector_value+from ...app.dataloaders import get_app_promise+from ...core import ResolveInfo+from ...core.descriptions import ADDED_IN_38+from ...core.mutations import ModelBulkDeleteMutation+from ...core.types import NonNullList, ProductError+from ...core.validators import validate_one_of_args_is_in_mutation+from ...plugins.dataloaders import get_plugin_manager_promise+from ..types import ProductVariant+from ..utils import get_draft_order_lines_data_for_variants+++class ProductVariantBulkDelete(ModelBulkDeleteMutation):+ class Arguments:+ ids = NonNullList(+ graphene.ID,+ required=False,+ description="List of product variant IDs to delete.",+ )+ skus = NonNullList(+ graphene.String,+ required=False,+ description="List of product variant SKUs to delete." + ADDED_IN_38,+ )++ class Meta:+ description = "Deletes product variants."+ model = models.ProductVariant+ object_type = ProductVariant+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = ProductError+ error_type_field = "product_errors"++ @classmethod+ @traced_atomic_transaction()+ def perform_mutation(cls, _root, info: ResolveInfo, /, ids=None, skus=None, **data):+ validate_one_of_args_is_in_mutation("skus", skus, "ids", ids)++ if ids:+ try:+ pks = cls.get_global_ids_or_error(ids, ProductVariant)+ except ValidationError as error:+ return 0, error+ else:+ pks = models.ProductVariant.objects.filter(sku__in=skus).values_list(+ "pk", flat=True+ )+ ids = [graphene.Node.to_global_id("ProductVariant", pk) for pk in pks]++ draft_order_lines_data = get_draft_order_lines_data_for_variants(pks)++ product_pks = list(+ models.Product.objects.filter(variants__in=pks)+ .distinct()+ .values_list("pk", flat=True)+ )++ # Get cached variants with related fields to fully populate webhook payload.+ variants = list(+ models.ProductVariant.objects.filter(id__in=pks).prefetch_related(+ "channel_listings",+ "attributes__values",+ "variant_media",+ )+ )++ cls.delete_assigned_attribute_values(pks)+ cls.delete_product_channel_listings_without_available_variants(product_pks, pks)+ response = super().perform_mutation(_root, info, ids=ids, **data)+ manager = get_plugin_manager_promise(info.context).get()+ transaction.on_commit(+ lambda: [manager.product_variant_deleted(variant) for variant in variants]+ )++ # delete order lines for deleted variants+ order_models.OrderLine.objects.filter(+ pk__in=draft_order_lines_data.line_pks+ ).delete()++ app = get_app_promise(info.context).get()+ # run order event for deleted lines+ for order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():+ order_events.order_line_variant_removed_event(+ order, info.context.user, app, order_lines+ )++ order_pks = draft_order_lines_data.order_pks+ if order_pks:+ recalculate_orders_task.delay(list(order_pks))++ # set new product default variant if any has been removed+ products = models.Product.objects.filter(+ pk__in=product_pks, default_variant__isnull=True+ )+ for product in products:+ product.search_vector = FlatConcatSearchVector(+ *prepare_product_search_vector_value(product)+ )+ product.default_variant = product.variants.first()+ product.save(+ update_fields=[+ "default_variant",+ "search_vector",+ "updated_at",+ ]+ )++ return response++ @staticmethod+ def delete_assigned_attribute_values(instance_pks):+ attribute_models.AttributeValue.objects.filter(+ variantassignments__variant_id__in=instance_pks,+ attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,+ ).delete()++ @staticmethod+ def delete_product_channel_listings_without_available_variants(+ product_pks: Iterable[int], variant_pks: Iterable[int]+ ):+ """Delete invalid channel listings.++ Delete product channel listings for product and channel for which+ the last available variant has been deleted.+ """+ variants = models.ProductVariant.objects.filter(+ product_id__in=product_pks+ ).exclude(id__in=variant_pks)++ variant_subquery = Subquery(+ queryset=variants.filter(id=OuterRef("variant_id")).values("product_id"),+ output_field=IntegerField(),+ )+ variant_channel_listings = models.ProductVariantChannelListing.objects.annotate(+ product_id=Coalesce(variant_subquery, 0)+ )++ invalid_product_channel_listings = models.ProductChannelListing.objects.filter(+ product_id__in=product_pks+ ).exclude(+ Exists(+ variant_channel_listings.filter(+ channel_id=OuterRef("channel_id"), product_id=OuterRef("product_id")+ )+ )+ )+ invalid_product_channel_listings.delete()diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.pynew file mode 100644index 0000000000..9ac1602da7--- /dev/null+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py@@ -0,0 +1,333 @@+from collections import defaultdict+from typing import cast++import graphene+from django.core.exceptions import ValidationError+from django.db import transaction+from graphene.utils.str_converters import to_camel_case++from ....core.tracing import traced_atomic_transaction+from ....permission.enums import ProductPermissions+from ....product import models+from ....product.error_codes import ProductErrorCode+from ....product.search import update_product_search_vector+from ....product.tasks import update_product_discounted_price_task+from ....warehouse import models as warehouse_models+from ...channel import ChannelContext+from ...core.descriptions import ADDED_IN_311, PREVIEW_FEATURE+from ...core.enums import ErrorPolicyEnum+from ...core.mutations import BaseMutation+from ...core.types import NonNullList, ProductVariantBulkError+from ...core.utils import get_duplicated_values+from ...plugins.dataloaders import get_plugin_manager_promise+from ..utils import get_used_variants_attribute_values+from .product_variant_bulk_create import (+ BulkAttributeValueInput,+ ProductVariantBulkCreate,+ ProductVariantBulkCreateInput,+ ProductVariantBulkResult,+)+++class ProductVariantBulkUpdateInput(ProductVariantBulkCreateInput):+ id = graphene.ID(description="ID of the product variant to update.", required=True)+ attributes = NonNullList(+ BulkAttributeValueInput,+ required=False,+ description="List of attributes specific to this variant.",+ )++ class Meta:+ description = "Input fields to update product variants." + ADDED_IN_311+++class ProductVariantBulkUpdate(BaseMutation):+ count = graphene.Int(+ required=True,+ default_value=0,+ description="Returns how many objects were updated.",+ )+ results = NonNullList(+ ProductVariantBulkResult,+ required=True,+ default_value=[],+ description="List of the updated variants.",+ )++ class Arguments:+ variants = NonNullList(+ ProductVariantBulkUpdateInput,+ required=True,+ description="Input list of product variants to update.",+ )+ product_id = graphene.ID(+ description="ID of the product to update the variants for.",+ name="product",+ required=True,+ )+ error_policy = ErrorPolicyEnum(+ required=False,+ default_value=ErrorPolicyEnum.REJECT_EVERYTHING.value,+ description=(+ "Policies of error handling. DEFAULT: "+ + ErrorPolicyEnum.REJECT_EVERYTHING.name+ ),+ )++ class Meta:+ description = (+ "Update multiple product variants." + ADDED_IN_311 + PREVIEW_FEATURE+ )+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = ProductVariantBulkError++ @classmethod+ def save(cls, info, instance, cleaned_input):+ ProductVariantBulkCreate.save(info, instance, cleaned_input)++ @classmethod+ def clean_variants(+ cls,+ info,+ variants,+ product,+ variants_global_id_to_instance_map,+ index_error_map,+ ):+ cleaned_inputs_map = {}+ warehouse_global_id_to_instance_map = {+ graphene.Node.to_global_id("Warehouse", warehouse.id): warehouse+ for warehouse in warehouse_models.Warehouse.objects.all()+ }+ product_channel_global_id_to_instance_map = {+ graphene.Node.to_global_id("Channel", listing.channel_id): listing.channel+ for listing in models.ProductChannelListing.objects.select_related(+ "channel"+ ).filter(product=product.id)+ }+ used_attribute_values = get_used_variants_attribute_values(product)+ variant_attributes_ids = {+ graphene.Node.to_global_id("Attribute", attr_id)+ for attr_id in list(+ product.product_type.variant_attributes.all().values_list(+ "pk", flat=True+ )+ )+ }+ duplicated_sku = get_duplicated_values(+ [variant.sku for variant in variants if variant.sku]+ )++ for index, variant_data in enumerate(variants):+ variant_id = variant_data["id"]+ variant_data["product_type"] = product.product_type+ variant_data["product"] = product++ if variant_id not in variants_global_id_to_instance_map.keys():+ message = f"Variant #{variant_id} does not exist."+ index_error_map[index].append(+ ProductVariantBulkError(+ field="id", message=message, code=ProductErrorCode.INVALID+ )+ )+ continue++ cleaned_input = ProductVariantBulkCreate.clean_variant(+ info,+ variant_data,+ product_channel_global_id_to_instance_map,+ warehouse_global_id_to_instance_map,+ used_attribute_values,+ variant_attributes_ids,+ duplicated_sku,+ index_error_map,+ index,+ errors=None,+ input_class=ProductVariantBulkUpdateInput,+ )++ cleaned_inputs_map[index] = cleaned_input+ return cleaned_inputs_map++ @classmethod+ def update_variants(cls, info, cleaned_inputs_map, index_error_map):+ instances_data_and_errors_list = []++ 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+ try:+ metadata_list = cleaned_input.pop("metadata", None)+ private_metadata_list = cleaned_input.pop("private_metadata", None)+ instance = cleaned_input.pop("id")+ instance = cls.construct_instance(instance, cleaned_input)+ cls.validate_and_update_metadata(+ instance, metadata_list, private_metadata_list+ )+ cls.clean_instance(info, instance)+ instances_data_and_errors_list.append(+ {+ "instance": instance,+ "errors": index_error_map[index],+ "cleaned_input": cleaned_input,+ }+ )+ except ValidationError as exc:+ for key, value in exc.error_dict.items():+ for e in value:+ index_error_map[index].append(+ ProductVariantBulkError(+ field=to_camel_case(key),+ message=e.messages[0],+ code=e.code,+ )+ )+ instances_data_and_errors_list.append(+ {"instance": None, "errors": index_error_map[index]}+ )+ return instances_data_and_errors_list++ @classmethod+ @traced_atomic_transaction()+ def update_or_create_variant_stocks(cls, variant, cleaned_input, manager):+ stocks = []+ if stocks_data := cleaned_input.get("stocks"):+ for stock_data in stocks_data:+ stock, is_created = warehouse_models.Stock.objects.get_or_create(+ product_variant=variant, warehouse=stock_data["warehouse"]+ )++ if is_created or (stock.quantity <= 0 and stock_data["quantity"] > 0):+ transaction.on_commit(+ lambda: manager.product_variant_back_in_stock(stock)+ )++ if stock_data["quantity"] <= 0:+ transaction.on_commit(+ lambda: manager.product_variant_out_of_stock(stock)+ )++ stock.quantity = stock_data["quantity"]+ stocks.append(stock)++ warehouse_models.Stock.objects.bulk_update(stocks, ["quantity"])++ @classmethod+ def update_or_create_variant_channel_listings(cls, variant, cleaned_input):+ channel_listings_data = cleaned_input.get("channel_listings")+ if not channel_listings_data:+ return++ for channel_listing_data in channel_listings_data:+ channel = channel_listing_data["channel"]+ price = channel_listing_data["price"]+ cost_price = channel_listing_data.get("cost_price")+ preorder_quantity_threshold = channel_listing_data.get("preorder_threshold")++ defaults = {+ "price_amount": price,+ "currency": channel.currency_code,+ }++ if "preorder_threshold" in channel_listing_data:+ defaults["preorder_quantity_threshold"] = preorder_quantity_threshold++ if "cost_price" in channel_listing_data:+ defaults["cost_price_amount"] = cost_price++ models.ProductVariantChannelListing.objects.update_or_create(+ variant=variant, channel=channel, defaults=defaults+ )++ @classmethod+ @traced_atomic_transaction()+ def save_variants(cls, info, manager, instances_data_with_errors_list):+ for instance_data in instances_data_with_errors_list:+ instance = instance_data["instance"]+ if instance:+ cleaned_input = instance_data.pop("cleaned_input")+ cls.save(info, instance, cleaned_input)+ cls.update_or_create_variant_stocks(instance, cleaned_input, manager)+ cls.update_or_create_variant_channel_listings(instance, cleaned_input)++ @classmethod+ @traced_atomic_transaction()+ def perform_mutation(cls, _root, info, **data):+ index_error_map: dict = defaultdict(list)+ error_policy = data["error_policy"]++ product = cast(+ models.Product,+ cls.get_node_or_error(info, data["product_id"], only_type="Product"),+ )+ variants_global_id_to_instance_map = {+ graphene.Node.to_global_id("ProductVariant", variant.id): variant+ for variant in product.variants.all()+ }++ cleaned_inputs_map = cls.clean_variants(+ info,+ data["variants"],+ product,+ variants_global_id_to_instance_map,+ index_error_map,+ )++ instances_data_with_errors_list = cls.update_variants(+ info, cleaned_inputs_map, index_error_map+ )++ has_errors = any(+ [True if error else False for error in index_error_map.values()]+ )+ if has_errors:+ if error_policy == ErrorPolicyEnum.REJECT_EVERYTHING.value:+ results = [+ ProductVariantBulkResult(+ product_variant=None, errors=data.get("errors")+ )+ for data in instances_data_with_errors_list+ ]+ return ProductVariantBulkUpdate(count=0, results=results)++ if error_policy == ErrorPolicyEnum.REJECT_FAILED_ROWS.value:+ for data in instances_data_with_errors_list:+ if data["errors"] and data["instance"]:+ data["instance"] = None++ manager = get_plugin_manager_promise(info.context).get()+ cls.save_variants(info, manager, instances_data_with_errors_list)++ instances = [+ ChannelContext(node=instance_data["instance"], channel_slug=None)+ for instance_data in instances_data_with_errors_list+ if instance_data["instance"]+ ]++ # Recalculate the "discounted price" for the parent product+ update_product_discounted_price_task.delay(product.pk)+ update_product_search_vector(product)+ transaction.on_commit(+ lambda: [+ manager.product_variant_updated(instance.node) for instance in instances+ ]+ )++ results = [+ ProductVariantBulkResult(+ product_variant=ChannelContext(+ node=data.get("instance"), channel_slug=None+ ),+ errors=data.get("errors"),+ )+ if data.get("instance")+ else ProductVariantBulkResult(+ product_variant=None, errors=data.get("errors")+ )+ for data in instances_data_with_errors_list+ ]++ return ProductVariantBulkCreate(count=len(instances), results=results)diff --git a/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.py b/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.pynew file mode 100644index 0000000000..48845343f3--- /dev/null+++ b/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.py@@ -0,0 +1,118 @@+from collections import defaultdict+from typing import List++import graphene+from django.core.exceptions import ValidationError+from django.db import transaction++from ....core.tracing import traced_atomic_transaction+from ....permission.enums import ProductPermissions+from ....warehouse.error_codes import StockErrorCode+from ...channel import ChannelContext+from ...core import ResolveInfo+from ...core.mutations import BaseMutation+from ...core.types import BulkStockError, NonNullList+from ...plugins.dataloaders import get_plugin_manager_promise+from ...warehouse.dataloaders import (+ StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader,+)+from ...warehouse.types import Warehouse+from ..mutations.product.product_create import StockInput+from ..types import ProductVariant+from ..utils import create_stocks+++class ProductVariantStocksCreate(BaseMutation):+ product_variant = graphene.Field(+ ProductVariant, description="Updated product variant."+ )++ class Arguments:+ variant_id = graphene.ID(+ required=True,+ description="ID of a product variant for which stocks will be created.",+ )+ stocks = NonNullList(+ StockInput,+ required=True,+ description="Input list of stocks to create.",+ )++ class Meta:+ description = "Creates stocks for product variant."+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = BulkStockError+ error_type_field = "bulk_stock_errors"++ @classmethod+ @traced_atomic_transaction()+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):+ manager = get_plugin_manager_promise(info.context).get()+ errors: defaultdict[str, List[ValidationError]] = defaultdict(list)+ stocks = data["stocks"]+ variant = cls.get_node_or_error(+ info, data["variant_id"], only_type=ProductVariant+ )+ if stocks:+ warehouses = cls.clean_stocks_input(variant, stocks, errors)+ if errors:+ raise ValidationError(errors)+ new_stocks = create_stocks(variant, stocks, warehouses)++ for stock in new_stocks:+ transaction.on_commit(+ lambda: manager.product_variant_back_in_stock(stock)+ )++ StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(+ info.context+ ).clear((variant.id, None, None))++ variant = ChannelContext(node=variant, channel_slug=None)+ return cls(product_variant=variant)++ @classmethod+ def clean_stocks_input(cls, variant, stocks_data, errors):+ warehouse_ids = [stock["warehouse"] for stock in stocks_data]+ cls.check_for_duplicates(warehouse_ids, errors)+ warehouses = cls.get_nodes_or_error(+ warehouse_ids, "warehouse", only_type=Warehouse+ )+ existing_stocks = variant.stocks.filter(warehouse__in=warehouses).values_list(+ "warehouse__pk", flat=True+ )+ error_msg = "Stock for this warehouse already exists for this product variant."+ indexes = []+ for warehouse_pk in existing_stocks:+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse_pk)+ indexes.extend(+ [i for i, id in enumerate(warehouse_ids) if id == warehouse_id]+ )+ cls.update_errors(+ errors, error_msg, "warehouse", StockErrorCode.UNIQUE, indexes+ )++ return warehouses++ @classmethod+ def check_for_duplicates(+ cls, warehouse_ids, errors: defaultdict[str, List[ValidationError]]+ ):+ duplicates = {id for id in warehouse_ids if warehouse_ids.count(id) > 1}+ error_msg = "Duplicated warehouse ID."+ indexes = []+ for duplicated_id in duplicates:+ indexes.append(+ [i for i, id in enumerate(warehouse_ids) if id == duplicated_id][-1]+ )+ cls.update_errors(+ errors, error_msg, "warehouse", StockErrorCode.UNIQUE, indexes+ )++ @classmethod+ def update_errors(+ cls, errors: defaultdict[str, List[ValidationError]], msg, field, code, indexes+ ):+ for index in indexes:+ error = ValidationError(msg, code=code, params={"index": index})+ errors[field].append(error)diff --git a/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.py b/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.pynew file mode 100644index 0000000000..5707fbd964--- /dev/null+++ b/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.py@@ -0,0 +1,85 @@+import graphene+from django.core.exceptions import ValidationError+from django.db import transaction++from ....core.tracing import traced_atomic_transaction+from ....permission.enums import ProductPermissions+from ....product import models+from ....warehouse import models as warehouse_models+from ...channel import ChannelContext+from ...core import ResolveInfo+from ...core.mutations import BaseMutation+from ...core.types import NonNullList, StockError+from ...core.validators import validate_one_of_args_is_in_mutation+from ...plugins.dataloaders import get_plugin_manager_promise+from ...warehouse.dataloaders import (+ StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader,+)+from ...warehouse.types import Warehouse+from ..types import ProductVariant+++class ProductVariantStocksDelete(BaseMutation):+ product_variant = graphene.Field(+ ProductVariant, description="Updated product variant."+ )++ class Arguments:+ variant_id = graphene.ID(+ required=False,+ description="ID of product variant for which stocks will be deleted.",+ )+ sku = graphene.String(+ required=False,+ description="SKU of product variant for which stocks will be deleted.",+ )+ warehouse_ids = NonNullList(+ graphene.ID, description="Input list of warehouse IDs."+ )++ class Meta:+ description = "Delete stocks from product variant."+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = StockError+ error_type_field = "stock_errors"++ @classmethod+ @traced_atomic_transaction()+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):+ sku = data.get("sku")+ variant_id = data.get("variant_id")+ validate_one_of_args_is_in_mutation("sku", sku, "variant_id", variant_id)++ manager = get_plugin_manager_promise(info.context).get()++ if variant_id:+ variant = cls.get_node_or_error(info, variant_id, only_type=ProductVariant)+ else:+ variant = models.ProductVariant.objects.filter(sku=sku).first()+ if not variant:+ raise ValidationError(+ {+ "sku": ValidationError(+ f"Couldn't resolve to a node: {sku}", code="not_found"+ )+ }+ )++ warehouses_pks = cls.get_global_ids_or_error(+ data["warehouse_ids"], Warehouse, field="warehouse_ids"+ )+ stocks_to_delete = warehouse_models.Stock.objects.filter(+ product_variant=variant, warehouse__pk__in=warehouses_pks+ )++ for stock in stocks_to_delete:+ transaction.on_commit(lambda: manager.product_variant_out_of_stock(stock))++ stocks_to_delete.delete()++ StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(+ info.context+ ).clear((variant.id, None, None))++ variant = ChannelContext(node=variant, channel_slug=None)+ return cls(product_variant=variant)diff --git a/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py b/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.pynew file mode 100644index 0000000000..6f2f361ab5--- /dev/null+++ b/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py@@ -0,0 +1,118 @@+from collections import defaultdict+from typing import List++import graphene+from django.core.exceptions import ValidationError+from django.db import transaction++from ....core.tracing import traced_atomic_transaction+from ....permission.enums import ProductPermissions+from ....product import models+from ....warehouse import models as warehouse_models+from ...channel import ChannelContext+from ...core import ResolveInfo+from ...core.types import BulkStockError, NonNullList+from ...core.validators import validate_one_of_args_is_in_mutation+from ...plugins.dataloaders import get_plugin_manager_promise+from ...warehouse.dataloaders import (+ StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader,+)+from ...warehouse.types import Warehouse+from ..mutations.product.product_create import StockInput+from ..types import ProductVariant+from .product_variant_stocks_create import ProductVariantStocksCreate+++class ProductVariantStocksUpdate(ProductVariantStocksCreate):+ class Meta:+ description = "Update stocks for product variant."+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = BulkStockError+ error_type_field = "bulk_stock_errors"++ class Arguments:+ variant_id = graphene.ID(+ required=False,+ description="ID of a product variant for which stocks will be updated.",+ )+ sku = graphene.String(+ required=False,+ description="SKU of product variant for which stocks will be updated.",+ )+ stocks = NonNullList(+ StockInput,+ required=True,+ description="Input list of stocks to create or update.",+ )++ @classmethod+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):+ errors: defaultdict[str, List[ValidationError]] = defaultdict(list)+ stocks = data["stocks"]+ sku = data.get("sku")+ variant_id = data.get("variant_id")++ validate_one_of_args_is_in_mutation("sku", sku, "variant_id", variant_id)++ if variant_id:+ variant = cls.get_node_or_error(info, variant_id, only_type=ProductVariant)+ if sku:+ variant = models.ProductVariant.objects.filter(sku=sku).first()+ if not variant:+ raise ValidationError(+ {+ "sku": ValidationError(+ f"Couldn't resolve to a node: {sku}", code="not_found"+ )+ }+ )++ if stocks:+ warehouse_ids = [stock["warehouse"] for stock in stocks]+ cls.check_for_duplicates(warehouse_ids, errors)+ if errors:+ raise ValidationError(errors)+ warehouses = cls.get_nodes_or_error(+ warehouse_ids, "warehouse", only_type=Warehouse+ )++ manager = get_plugin_manager_promise(info.context).get()+ cls.update_or_create_variant_stocks(variant, stocks, warehouses, manager)++ StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(+ info.context+ ).clear((variant.id, None, None))++ variant = ChannelContext(node=variant, channel_slug=None)+ return cls(product_variant=variant)++ @classmethod+ @traced_atomic_transaction()+ def update_or_create_variant_stocks(cls, variant, stocks_data, warehouses, manager):++ stocks = []+ for stock_data, warehouse in zip(stocks_data, warehouses):+ stock, is_created = warehouse_models.Stock.objects.get_or_create(+ product_variant=variant, warehouse=warehouse+ )+ if is_created or (+ (stock.quantity - stock.quantity_allocated)+ <= 0+ < stock_data["quantity"]+ ):+ transaction.on_commit(+ lambda: manager.product_variant_back_in_stock(stock)+ )++ if stock_data["quantity"] <= 0 or (+ stock_data["quantity"] - stock.quantity_allocated <= 0+ ):+ transaction.on_commit(+ lambda: manager.product_variant_out_of_stock(stock)+ )++ stock.quantity = stock_data["quantity"]+ stocks.append(stock)+ transaction.on_commit(lambda: manager.product_variant_stock_updated(stock))++ warehouse_models.Stock.objects.bulk_update(stocks, ["quantity"])diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.pydeleted file mode 100644index d1b69086e5..0000000000--- a/saleor/graphql/product/bulk_mutations/products.py+++ /dev/null@@ -1,1035 +0,0 @@-from collections import defaultdict-from typing import Dict, Iterable, List, Optional--import graphene-from django.core.exceptions import ValidationError-from django.db import transaction-from django.db.models import Exists, OuterRef, Q, Subquery-from django.db.models.fields import IntegerField-from django.db.models.functions import Coalesce-from graphene.types import InputObjectType--from ....attribute import AttributeInputType-from ....attribute import models as attribute_models-from ....core.postgres import FlatConcatSearchVector-from ....core.tracing import traced_atomic_transaction-from ....order import events as order_events-from ....order import models as order_models-from ....order.tasks import recalculate_orders_task-from ....permission.enums import ProductPermissions, ProductTypePermissions-from ....product import models-from ....product.error_codes import ProductErrorCode-from ....product.search import (- prepare_product_search_vector_value,- update_product_search_vector,-)-from ....product.tasks import update_product_discounted_price_task-from ....product.utils import delete_categories-from ....product.utils.variants import generate_and_set_variant_name-from ....warehouse import models as warehouse_models-from ....warehouse.error_codes import StockErrorCode-from ...app.dataloaders import get_app_promise-from ...attribute.utils import AttributeAssignmentMixin-from ...channel import ChannelContext-from ...channel.types import Channel-from ...core import ResolveInfo-from ...core.descriptions import ADDED_IN_38-from ...core.mutations import BaseMutation, ModelBulkDeleteMutation, ModelMutation-from ...core.types import (- BulkProductError,- BulkStockError,- CollectionError,- NonNullList,- ProductError,- StockError,-)-from ...core.utils import get_duplicated_values-from ...core.validators import (- validate_one_of_args_is_in_mutation,- validate_price_precision,-)-from ...plugins.dataloaders import get_plugin_manager_promise-from ...warehouse.dataloaders import (- StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader,-)-from ...warehouse.types import Warehouse-from ..mutations.channels import ProductVariantChannelListingAddInput-from ..mutations.product.product_create import StockInput-from ..mutations.product_variant.product_variant_create import (- ProductVariantCreate,- ProductVariantInput,-)-from ..types import (- Category,- Collection,- Product,- ProductMedia,- ProductType,- ProductVariant,-)-from ..utils import (- clean_variant_sku,- create_stocks,- get_draft_order_lines_data_for_variants,- get_used_variants_attribute_values,-)---class CategoryBulkDelete(ModelBulkDeleteMutation):- class Arguments:- ids = NonNullList(- graphene.ID, required=True, description="List of category IDs to delete."- )-- class Meta:- description = "Deletes categories."- model = models.Category- object_type = Category- permissions = (ProductPermissions.MANAGE_PRODUCTS,)- error_type_class = ProductError- error_type_field = "product_errors"-- @classmethod- def bulk_action(cls, info: ResolveInfo, queryset, /):- manager = get_plugin_manager_promise(info.context).get()- delete_categories(queryset.values_list("pk", flat=True), manager)---class CollectionBulkDelete(ModelBulkDeleteMutation):- class Arguments:- ids = NonNullList(- graphene.ID, required=True, description="List of collection IDs to delete."- )-- class Meta:- description = "Deletes collections."- model = models.Collection- object_type = Collection- permissions = (ProductPermissions.MANAGE_PRODUCTS,)- error_type_class = CollectionError- error_type_field = "collection_errors"-- @classmethod- def bulk_action(cls, info: ResolveInfo, queryset, /):- collections_ids = queryset.values_list("id", flat=True)- products = list(- models.Product.objects.prefetched_for_webhook(single_object=False)- .filter(collections__in=collections_ids)- .distinct()- )- manager = get_plugin_manager_promise(info.context).get()- for collection in queryset.iterator():- manager.collection_deleted(collection)- queryset.delete()-- for product in products:- manager.product_updated(product)---class ProductBulkDelete(ModelBulkDeleteMutation):- class Arguments:- ids = NonNullList(- graphene.ID, required=True, description="List of product IDs to delete."- )-- class Meta:- description = "Deletes products."- model = models.Product- object_type = Product- permissions = (ProductPermissions.MANAGE_PRODUCTS,)- error_type_class = ProductError- error_type_field = "product_errors"-- @classmethod- @traced_atomic_transaction()- def perform_mutation( # type: ignore[override]- cls, _root, info: ResolveInfo, /, *, ids- ):- try:- pks = cls.get_global_ids_or_error(ids, Product)- except ValidationError as error:- return 0, error- product_to_variant = list(- models.ProductVariant.objects.filter(product__pk__in=pks).values_list(- "product_id", "id"- )- )- variants_ids = [variant_id for _, variant_id in product_to_variant]-- cls.delete_assigned_attribute_values(pks)-- draft_order_lines_data = get_draft_order_lines_data_for_variants(variants_ids)-- response = super().perform_mutation(- _root, info, ids=ids, product_to_variant=product_to_variant- )-- # delete order lines for deleted variants- order_models.OrderLine.objects.filter(- pk__in=draft_order_lines_data.line_pks- ).delete()-- app = get_app_promise(info.context).get()- # run order event for deleted lines- for order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():- order_events.order_line_product_removed_event(- order, info.context.user, app, order_lines- )-- order_pks = draft_order_lines_data.order_pks- if order_pks:- recalculate_orders_task.delay(list(order_pks))-- return response-- @staticmethod- def delete_assigned_attribute_values(instance_pks):- attribute_models.AttributeValue.objects.filter(- productassignments__product_id__in=instance_pks,- attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,- ).delete()-- @classmethod- def bulk_action( # type: ignore[override]- cls, info: ResolveInfo, queryset, /, *, product_to_variant- ):- product_variant_map = defaultdict(list)- for product, variant in product_to_variant:- product_variant_map[product].append(variant)-- products = [product for product in queryset]- queryset.delete()- manager = get_plugin_manager_promise(info.context).get()- for product in products:- variants = product_variant_map.get(product.id, [])- manager.product_deleted(product, variants)---class BulkAttributeValueInput(InputObjectType):- id = graphene.ID(description="ID of the selected attribute.")- values = NonNullList(- graphene.String,- required=False,- description=(- "The value or slug of an attribute to resolve. "- "If the passed value is non-existent, it will be created."- ),- )- boolean = graphene.Boolean(- required=False,- description=(- "The boolean value of an attribute to resolve. "- "If the passed value is non-existent, it will be created."- ),- )---class ProductVariantBulkCreateInput(ProductVariantInput):- attributes = NonNullList(- BulkAttributeValueInput,- required=True,- description="List of attributes specific to this variant.",- )- stocks = NonNullList(- StockInput,- description="Stocks of a product available for sale.",- required=False,- )- channel_listings = NonNullList(- ProductVariantChannelListingAddInput,- description="List of prices assigned to channels.",- required=False,- )- sku = graphene.String(description="Stock keeping unit.")---class ProductVariantBulkCreate(BaseMutation):- count = graphene.Int(- required=True,- default_value=0,- description="Returns how many objects were created.",- )- product_variants = NonNullList(- ProductVariant,- required=True,- default_value=[],- description="List of the created variants.",- )-- class Arguments:- variants = NonNullList(- ProductVariantBulkCreateInput,- required=True,- description="Input list of product variants to create.",- )- product_id = graphene.ID(- description="ID of the product to create the variants for.",- name="product",- required=True,- )-- class Meta:- description = "Creates product variants for a given product."- permissions = (ProductPermissions.MANAGE_PRODUCTS,)- error_type_class = BulkProductError- error_type_field = "bulk_product_errors"-- @classmethod- def clean_variant_input(- cls,- info,- instance: Optional[models.ProductVariant],- data: dict,- errors: Dict[str, ValidationError],- variant_index: int,- ):- cleaned_input = ModelMutation.clean_input(- info, instance, data, input_cls=ProductVariantBulkCreateInput- )-- attributes = cleaned_input.get("attributes")- if attributes:- try:- cleaned_input["attributes"] = ProductVariantCreate.clean_attributes(- attributes, data["product_type"]- )- except ValidationError as exc:- exc.params = {"index": variant_index}- errors["attributes"] = exc-- channel_listings = cleaned_input.get("channel_listings")- if channel_listings:- cleaned_input["channel_listings"] = cls.clean_channel_listings(- channel_listings, errors, data["product"], variant_index- )-- stocks = cleaned_input.get("stocks")- if stocks:- cls.clean_stocks(stocks, errors, variant_index)-- cleaned_input["sku"] = clean_variant_sku(cleaned_input.get("sku"))-- preorder_settings = cleaned_input.get("preorder")- if preorder_settings:- cleaned_input["is_preorder"] = True- cleaned_input["preorder_global_threshold"] = preorder_settings.get(- "global_threshold"- )- cleaned_input["preorder_end_date"] = preorder_settings.get("end_date")-- return cleaned_input-- @classmethod- def clean_price(- cls, price, field_name, currency, channel_id, variant_index, errors- ):- try:- validate_price_precision(price, currency)- except ValidationError as error:- error.code = ProductErrorCode.INVALID.value- error.params = {- "channels": [channel_id],- "index": variant_index,- }- errors[field_name].append(error)-- @classmethod- def clean_channel_listings(cls, channels_data, errors, product, variant_index):- channel_ids = [- channel_listing["channel_id"] for channel_listing in channels_data- ]- duplicates = get_duplicated_values(channel_ids)- if duplicates:- errors["channel_listings"] = ValidationError(- "Duplicated channel ID.",- code=ProductErrorCode.DUPLICATED_INPUT_ITEM.value,- params={"channels": duplicates, "index": variant_index},- )- return channels_data- channels = cls.get_nodes_or_error(- channel_ids, "channel_listings", only_type=Channel- )- for index, channel_listing_data in enumerate(channels_data):- channel_listing_data["channel"] = channels[index]-- for channel_listing_data in channels_data:- price = channel_listing_data.get("price")- cost_price = channel_listing_data.get("cost_price")- channel_id = channel_listing_data["channel_id"]- currency_code = channel_listing_data["channel"].currency_code- cls.clean_price(- price, "price", currency_code, channel_id, variant_index, errors- )- cls.clean_price(- cost_price,- "cost_price",- currency_code,- channel_id,- variant_index,- errors,- )-- channels_not_assigned_to_product = []- channels_assigned_to_product = list(- models.ProductChannelListing.objects.filter(product=product.id).values_list(- "channel_id", flat=True- )- )- for channel_listing_data in channels_data:- if channel_listing_data["channel"].id not in channels_assigned_to_product:- channels_not_assigned_to_product.append(- channel_listing_data["channel_id"]- )- if channels_not_assigned_to_product:- errors["channel_id"].append(- ValidationError(- "Product not available in channels.",- code=ProductErrorCode.PRODUCT_NOT_ASSIGNED_TO_CHANNEL.value,- params={- "index": variant_index,- "channels": channels_not_assigned_to_product,- },- )- )- return channels_data-- @classmethod- def clean_stocks(cls, stocks_data, errors, variant_index):- warehouse_ids = [stock["warehouse"] for stock in stocks_data]- duplicates = get_duplicated_values(warehouse_ids)- if duplicates:- errors["stocks"] = ValidationError(- "Duplicated warehouse ID.",- code=ProductErrorCode.DUPLICATED_INPUT_ITEM.value,- params={"warehouses": duplicates, "index": variant_index},- )-- @classmethod- def add_indexes_to_errors(cls, index, error, error_dict):- """Append errors with index in params to mutation error dict."""- for key, value in error.error_dict.items():- for e in value:- if e.params:- e.params["index"] = index- else:- e.params = {"index": index}- error_dict[key].extend(value)-- @classmethod- def save(cls, info: ResolveInfo, instance, cleaned_input):- instance.save()-- attributes = cleaned_input.get("attributes")- if attributes:- AttributeAssignmentMixin.save(instance, attributes)- if not instance.name:- generate_and_set_variant_name(instance, cleaned_input.get("sku"))-- @classmethod- def create_variants(cls, info: ResolveInfo, cleaned_inputs, product, errors):- instances = []- for index, cleaned_input in enumerate(cleaned_inputs):- if not cleaned_input:- continue- try:- instance = models.ProductVariant()- cleaned_input["product"] = product- instance = cls.construct_instance(instance, cleaned_input)- cls.clean_instance(info, instance)- instances.append(instance)- except ValidationError as exc:- cls.add_indexes_to_errors(index, exc, errors)- return instances-- @classmethod- def validate_duplicated_sku(cls, sku, index, sku_list: List[str], errors):- if sku in sku_list:- errors["sku"].append(- ValidationError(- "Duplicated SKU.",- ProductErrorCode.UNIQUE.value,- params={"index": index},- )- )- sku_list.append(sku)-- @classmethod- def validate_duplicated_attribute_values(- cls, attributes_data, used_attribute_values, instance=None- ):- attribute_values = defaultdict(list)- for attr in attributes_data:- if "boolean" in attr:- attribute_values[attr.id] = attr["boolean"]- else:- attribute_values[attr.id].extend(attr.get("values", []))- if attribute_values in used_attribute_values:- raise ValidationError(- "Duplicated attribute values for product variant.",- ProductErrorCode.DUPLICATED_INPUT_ITEM.value,- )- used_attribute_values.append(attribute_values)-- @classmethod- def clean_variants(cls, info: ResolveInfo, variants, product, errors):- cleaned_inputs = []- sku_list: List[str] = []- used_attribute_values = get_used_variants_attribute_values(product)- for index, variant_data in enumerate(variants):- if variant_data.attributes:- try:- cls.validate_duplicated_attribute_values(- variant_data.attributes, used_attribute_values- )- except ValidationError as exc:- errors["attributes"].append(- ValidationError(exc.message, exc.code, params={"index": index})- )-- variant_data["product_type"] = product.product_type- variant_data["product"] = product- cleaned_input = cls.clean_variant_input(- info, None, variant_data, errors, index- )-- cleaned_inputs.append(cleaned_input if cleaned_input else None)-- if cleaned_input["sku"]:- cls.validate_duplicated_sku(- cleaned_input["sku"], index, sku_list, errors- )- return cleaned_inputs-- @classmethod- def create_variant_channel_listings(cls, variant, cleaned_input):- channel_listings_data = cleaned_input.get("channel_listings")- if not channel_listings_data:- return- variant_channel_listings = []- for channel_listing_data in channel_listings_data:- channel = channel_listing_data["channel"]- price = channel_listing_data["price"]- cost_price = channel_listing_data.get("cost_price")- preorder_quantity_threshold = channel_listing_data.get("preorder_threshold")- variant_channel_listings.append(- models.ProductVariantChannelListing(- channel=channel,- variant=variant,- price_amount=price,- cost_price_amount=cost_price,- currency=channel.currency_code,- preorder_quantity_threshold=preorder_quantity_threshold,- )- )- models.ProductVariantChannelListing.objects.bulk_create(- variant_channel_listings- )-- @classmethod- @traced_atomic_transaction()- def save_variants(cls, info: ResolveInfo, instances, product, cleaned_inputs):- assert len(instances) == len(- cleaned_inputs- ), "There should be the same number of instances and cleaned inputs."- for instance, cleaned_input in zip(instances, cleaned_inputs):- cls.save(info, instance, cleaned_input)- cls.create_variant_stocks(instance, cleaned_input)- cls.create_variant_channel_listings(instance, cleaned_input)-- if not product.default_variant:- product.default_variant = instances[0]- product.save(update_fields=["default_variant", "updated_at"])-- @classmethod- def create_variant_stocks(cls, variant, cleaned_input):- stocks = cleaned_input.get("stocks")- if not stocks:- return- warehouse_ids = [stock["warehouse"] for stock in stocks]- warehouses = cls.get_nodes_or_error(- warehouse_ids, "warehouse", only_type=Warehouse- )- create_stocks(variant, stocks, warehouses)-- @classmethod- @traced_atomic_transaction()- def perform_mutation( # type: ignore[override]- cls, _root, info: ResolveInfo, /, *, product_id: str, variants- ):- product = cls.get_node_or_error(info, product_id, only_type=Product)- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)-- cleaned_inputs = cls.clean_variants(info, variants, product, errors)- instances = cls.create_variants(info, cleaned_inputs, product, errors)- if errors:- raise ValidationError(errors)- cls.save_variants(info, instances, product, cleaned_inputs)-- # Recalculate the "discounted price" for the parent product- update_product_discounted_price_task.delay(product.pk)-- instances = [- ChannelContext(node=instance, channel_slug=None) for instance in instances- ]-- update_product_search_vector(product)- manager = get_plugin_manager_promise(info.context).get()- transaction.on_commit(- lambda: [- manager.product_variant_created(instance.node) for instance in instances- ]- )-- return ProductVariantBulkCreate(- count=len(instances), product_variants=instances- )---class ProductVariantBulkDelete(ModelBulkDeleteMutation):- class Arguments:- ids = NonNullList(- graphene.ID,- required=False,- description="List of product variant IDs to delete.",- )- skus = NonNullList(- graphene.String,- required=False,- description="List of product variant SKUs to delete." + ADDED_IN_38,- )-- class Meta:- description = "Deletes product variants."- model = models.ProductVariant- object_type = ProductVariant- permissions = (ProductPermissions.MANAGE_PRODUCTS,)- error_type_class = ProductError- error_type_field = "product_errors"-- @classmethod- @traced_atomic_transaction()- def perform_mutation(cls, _root, info: ResolveInfo, /, ids=None, skus=None, **data):- validate_one_of_args_is_in_mutation("skus", skus, "ids", ids)-- if ids:- try:- pks = cls.get_global_ids_or_error(ids, ProductVariant)- except ValidationError as error:- return 0, error- else:- pks = models.ProductVariant.objects.filter(sku__in=skus).values_list(- "pk", flat=True- )- ids = [graphene.Node.to_global_id("ProductVariant", pk) for pk in pks]-- draft_order_lines_data = get_draft_order_lines_data_for_variants(pks)-- product_pks = list(- models.Product.objects.filter(variants__in=pks)- .distinct()- .values_list("pk", flat=True)- )-- # Get cached variants with related fields to fully populate webhook payload.- variants = list(- models.ProductVariant.objects.filter(id__in=pks).prefetch_related(- "channel_listings",- "attributes__values",- "variant_media",- )- )-- cls.delete_assigned_attribute_values(pks)- cls.delete_product_channel_listings_without_available_variants(product_pks, pks)- response = super().perform_mutation(_root, info, ids=ids, **data)- manager = get_plugin_manager_promise(info.context).get()- transaction.on_commit(- lambda: [manager.product_variant_deleted(variant) for variant in variants]- )-- # delete order lines for deleted variants- order_models.OrderLine.objects.filter(- pk__in=draft_order_lines_data.line_pks- ).delete()-- app = get_app_promise(info.context).get()- # run order event for deleted lines- for order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():- order_events.order_line_variant_removed_event(- order, info.context.user, app, order_lines- )-- order_pks = draft_order_lines_data.order_pks- if order_pks:- recalculate_orders_task.delay(list(order_pks))-- # set new product default variant if any has been removed- products = models.Product.objects.filter(- pk__in=product_pks, default_variant__isnull=True- )- for product in products:- product.search_vector = FlatConcatSearchVector(- *prepare_product_search_vector_value(product)- )- product.default_variant = product.variants.first()- product.save(- update_fields=[- "default_variant",- "search_vector",- "updated_at",- ]- )-- return response-- @staticmethod- def delete_assigned_attribute_values(instance_pks):- attribute_models.AttributeValue.objects.filter(- variantassignments__variant_id__in=instance_pks,- attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,- ).delete()-- @staticmethod- def delete_product_channel_listings_without_available_variants(- product_pks: Iterable[int], variant_pks: Iterable[int]- ):- """Delete invalid channel listings.-- Delete product channel listings for product and channel for which- the last available variant has been deleted.- """- variants = models.ProductVariant.objects.filter(- product_id__in=product_pks- ).exclude(id__in=variant_pks)-- variant_subquery = Subquery(- queryset=variants.filter(id=OuterRef("variant_id")).values("product_id"),- output_field=IntegerField(),- )- variant_channel_listings = models.ProductVariantChannelListing.objects.annotate(- product_id=Coalesce(variant_subquery, 0)- )-- invalid_product_channel_listings = models.ProductChannelListing.objects.filter(- product_id__in=product_pks- ).exclude(- Exists(- variant_channel_listings.filter(- channel_id=OuterRef("channel_id"), product_id=OuterRef("product_id")- )- )- )- invalid_product_channel_listings.delete()---class ProductVariantStocksCreate(BaseMutation):- product_variant = graphene.Field(- ProductVariant, description="Updated product variant."- )-- class Arguments:- variant_id = graphene.ID(- required=True,- description="ID of a product variant for which stocks will be created.",- )- stocks = NonNullList(- StockInput,- required=True,- description="Input list of stocks to create.",- )-- class Meta:- description = "Creates stocks for product variant."- permissions = (ProductPermissions.MANAGE_PRODUCTS,)- error_type_class = BulkStockError- error_type_field = "bulk_stock_errors"-- @classmethod- @traced_atomic_transaction()- def perform_mutation(cls, _root, info: ResolveInfo, /, **data):- manager = get_plugin_manager_promise(info.context).get()- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)- stocks = data["stocks"]- variant = cls.get_node_or_error(- info, data["variant_id"], only_type=ProductVariant- )- if stocks:- warehouses = cls.clean_stocks_input(variant, stocks, errors)- if errors:- raise ValidationError(errors)- new_stocks = create_stocks(variant, stocks, warehouses)-- for stock in new_stocks:- transaction.on_commit(- lambda: manager.product_variant_back_in_stock(stock)- )-- StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(- info.context- ).clear((variant.id, None, None))-- variant = ChannelContext(node=variant, channel_slug=None)- return cls(product_variant=variant)-- @classmethod- def clean_stocks_input(cls, variant, stocks_data, errors):- warehouse_ids = [stock["warehouse"] for stock in stocks_data]- cls.check_for_duplicates(warehouse_ids, errors)- warehouses = cls.get_nodes_or_error(- warehouse_ids, "warehouse", only_type=Warehouse- )- existing_stocks = variant.stocks.filter(warehouse__in=warehouses).values_list(- "warehouse__pk", flat=True- )- error_msg = "Stock for this warehouse already exists for this product variant."- indexes = []- for warehouse_pk in existing_stocks:- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse_pk)- indexes.extend(- [i for i, id in enumerate(warehouse_ids) if id == warehouse_id]- )- cls.update_errors(- errors, error_msg, "warehouse", StockErrorCode.UNIQUE, indexes- )-- return warehouses-- @classmethod- def check_for_duplicates(- cls, warehouse_ids, errors: defaultdict[str, List[ValidationError]]- ):- duplicates = {id for id in warehouse_ids if warehouse_ids.count(id) > 1}- error_msg = "Duplicated warehouse ID."- indexes = []- for duplicated_id in duplicates:- indexes.append(- [i for i, id in enumerate(warehouse_ids) if id == duplicated_id][-1]- )- cls.update_errors(- errors, error_msg, "warehouse", StockErrorCode.UNIQUE, indexes- )-- @classmethod- def update_errors(- cls, errors: defaultdict[str, List[ValidationError]], msg, field, code, indexes- ):- for index in indexes:- error = ValidationError(msg, code=code, params={"index": index})- errors[field].append(error)---class ProductVariantStocksUpdate(ProductVariantStocksCreate):- class Meta:- description = "Update stocks for product variant."- permissions = (ProductPermissions.MANAGE_PRODUCTS,)- error_type_class = BulkStockError- error_type_field = "bulk_stock_errors"-- class Arguments:- variant_id = graphene.ID(- required=False,- description="ID of a product variant for which stocks will be updated.",- )- sku = graphene.String(- required=False,- description="SKU of product variant for which stocks will be updated.",- )- stocks = NonNullList(- StockInput,- required=True,- description="Input list of stocks to create or update.",- )-- @classmethod- def perform_mutation(cls, _root, info: ResolveInfo, /, **data):- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)- stocks = data["stocks"]- sku = data.get("sku")- variant_id = data.get("variant_id")-- validate_one_of_args_is_in_mutation("sku", sku, "variant_id", variant_id)-- if variant_id:- variant = cls.get_node_or_error(info, variant_id, only_type=ProductVariant)- if sku:- variant = models.ProductVariant.objects.filter(sku=sku).first()- if not variant:- raise ValidationError(- {- "sku": ValidationError(- f"Couldn't resolve to a node: {sku}", code="not_found"- )- }- )-- if stocks:- warehouse_ids = [stock["warehouse"] for stock in stocks]- cls.check_for_duplicates(warehouse_ids, errors)- if errors:- raise ValidationError(errors)- warehouses = cls.get_nodes_or_error(- warehouse_ids, "warehouse", only_type=Warehouse- )-- manager = get_plugin_manager_promise(info.context).get()- cls.update_or_create_variant_stocks(variant, stocks, warehouses, manager)-- StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(- info.context- ).clear((variant.id, None, None))-- variant = ChannelContext(node=variant, channel_slug=None)- return cls(product_variant=variant)-- @classmethod- @traced_atomic_transaction()- def update_or_create_variant_stocks(cls, variant, stocks_data, warehouses, manager):-- stocks = []- for stock_data, warehouse in zip(stocks_data, warehouses):- stock, is_created = warehouse_models.Stock.objects.get_or_create(- product_variant=variant, warehouse=warehouse- )- if is_created or (- (stock.quantity - stock.quantity_allocated)- <= 0- < stock_data["quantity"]- ):- transaction.on_commit(- lambda: manager.product_variant_back_in_stock(stock)- )-- if stock_data["quantity"] <= 0 or (- stock_data["quantity"] - stock.quantity_allocated <= 0- ):- transaction.on_commit(- lambda: manager.product_variant_out_of_stock(stock)- )-- stock.quantity = stock_data["quantity"]- stocks.append(stock)- transaction.on_commit(lambda: manager.product_variant_stock_updated(stock))-- warehouse_models.Stock.objects.bulk_update(stocks, ["quantity"])---class ProductVariantStocksDelete(BaseMutation):- product_variant = graphene.Field(- ProductVariant, description="Updated product variant."- )-- class Arguments:- variant_id = graphene.ID(- required=False,- description="ID of product variant for which stocks will be deleted.",- )- sku = graphene.String(- required=False,- description="SKU of product variant for which stocks will be deleted.",- )- warehouse_ids = NonNullList(- graphene.ID, description="Input list of warehouse IDs."- )-- class Meta:- description = "Delete stocks from product variant."- permissions = (ProductPermissions.MANAGE_PRODUCTS,)- error_type_class = StockError- error_type_field = "stock_errors"-- @classmethod- @traced_atomic_transaction()- def perform_mutation(cls, _root, info: ResolveInfo, /, **data):- sku = data.get("sku")- variant_id = data.get("variant_id")- validate_one_of_args_is_in_mutation("sku", sku, "variant_id", variant_id)-- manager = get_plugin_manager_promise(info.context).get()-- if variant_id:- variant = cls.get_node_or_error(info, variant_id, only_type=ProductVariant)- else:- variant = models.ProductVariant.objects.filter(sku=sku).first()- if not variant:- raise ValidationError(- {- "sku": ValidationError(- f"Couldn't resolve to a node: {sku}", code="not_found"- )- }- )-- warehouses_pks = cls.get_global_ids_or_error(- data["warehouse_ids"], Warehouse, field="warehouse_ids"- )- stocks_to_delete = warehouse_models.Stock.objects.filter(- product_variant=variant, warehouse__pk__in=warehouses_pks- )-- for stock in stocks_to_delete:- transaction.on_commit(lambda: manager.product_variant_out_of_stock(stock))-- stocks_to_delete.delete()-- StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(- info.context- ).clear((variant.id, None, None))-- variant = ChannelContext(node=variant, channel_slug=None)- return cls(product_variant=variant)---class ProductTypeBulkDelete(ModelBulkDeleteMutation):- class Arguments:- ids = NonNullList(- graphene.ID,- required=True,- description="List of product type IDs to delete.",- )-- class Meta:- description = "Deletes product types."- model = models.ProductType- object_type = ProductType- permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)- error_type_class = ProductError- error_type_field = "product_errors"-- @classmethod- @traced_atomic_transaction()- def perform_mutation( # type: ignore[override]- cls, _root, info: ResolveInfo, /, *, ids- ):- try:- pks = cls.get_global_ids_or_error(ids, ProductType)- except ValidationError as error:- return 0, error- cls.delete_assigned_attribute_values(pks)- return super().perform_mutation(_root, info, ids=ids)-- @staticmethod- def delete_assigned_attribute_values(instance_pks):- attribute_models.AttributeValue.objects.filter(- Q(attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES)- & (- Q(productassignments__assignment__product_type_id__in=instance_pks)- | Q(variantassignments__assignment__product_type_id__in=instance_pks)- )- ).delete()---class ProductMediaBulkDelete(ModelBulkDeleteMutation):- class Arguments:- ids = NonNullList(- graphene.ID,- required=True,- description="List of product media IDs to delete.",- )-- class Meta:- description = "Deletes product media."- model = models.ProductMedia- object_type = ProductMedia- permissions = (ProductPermissions.MANAGE_PRODUCTS,)- error_type_class = ProductError- error_type_field = "product_errors"diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex 25962eff5e..000eb4bbeb 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -24,7 +24,7 @@ from ..translations.mutations import (ProductVariantTranslate,)from ..utils import get_user_or_app_from_context-from .bulk_mutations.products import (+from .bulk_mutations import (CategoryBulkDelete,CollectionBulkDelete,ProductBulkDelete,@@ -32,6 +32,7 @@ from .bulk_mutations.products import (ProductTypeBulkDelete,ProductVariantBulkCreate,ProductVariantBulkDelete,+ ProductVariantBulkUpdate,ProductVariantStocksCreate,ProductVariantStocksDelete,ProductVariantStocksUpdate,@@ -565,6 +566,7 @@ class ProductMutations(graphene.ObjectType):product_variant_create = ProductVariantCreate.Field()product_variant_delete = ProductVariantDelete.Field()product_variant_bulk_create = ProductVariantBulkCreate.Field()+ product_variant_bulk_update = ProductVariantBulkUpdate.Field()product_variant_bulk_delete = ProductVariantBulkDelete.Field()product_variant_stocks_create = ProductVariantStocksCreate.Field()product_variant_stocks_delete = ProductVariantStocksDelete.Field()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.pynew file mode 100644index 0000000000..9a801fcf60--- /dev/null+++ b/saleor/graphql/product/tests/deprecated/test_product_variant_bulk_create.py@@ -0,0 +1,1144 @@+from datetime import datetime, timedelta+from unittest.mock import ANY, patch+from uuid import uuid4++import graphene++from .....attribute import AttributeInputType+from .....product.error_codes import ProductVariantBulkErrorCode+from .....product.models import ProductChannelListing, ProductVariant+from .....tests.utils import flush_post_commit_hooks+from ....tests.utils import get_graphql_content++PRODUCT_VARIANT_BULK_CREATE_MUTATION = """+ mutation ProductVariantBulkCreate(+ $variants: [ProductVariantBulkCreateInput!]!, $productId: ID!+ ) {+ productVariantBulkCreate(variants: $variants, product: $productId) {+ errors {+ field+ message+ code+ index+ warehouses+ channels+ }+ productVariants{+ id+ name+ sku+ stocks {+ warehouse {+ slug+ }+ quantity+ }+ channelListings {+ channel {+ slug+ }+ price {+ currency+ amount+ }+ costPrice {+ currency+ amount+ }+ preorderThreshold {+ quantity+ }+ }+ preorder {+ globalThreshold+ endDate+ }+ }+ count+ }+ }+"""+++@patch("saleor.plugins.manager.PluginsManager.product_variant_created")+def test_product_variant_bulk_create_by_name(+ product_variant_created_webhook_mock,+ staff_api_client,+ product,+ size_attribute,+ permission_manage_products,+):+ # given+ product_variant_count = ProductVariant.objects.count()+ attribute_value_count = size_attribute.values.count()+ 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-anem"+ variants = [+ {+ "sku": sku,+ "weight": 2.5,+ "trackInventory": True,+ "name": name,+ "attributes": [{"id": attribut_id, "values": [attribute_value.name]}],+ }+ ]++ 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["errors"]+ assert data["count"] == 1+ assert data["productVariants"][0]["name"] == name+ assert product_variant_count + 1 == ProductVariant.objects.count()+ assert attribute_value_count == size_attribute.values.count()+ product_variant = ProductVariant.objects.get(sku=sku)+ product.refresh_from_db()+ assert product.default_variant == product_variant+ assert product_variant_created_webhook_mock.call_count == data["count"]+++@patch("saleor.plugins.manager.PluginsManager.product_variant_created")+def test_product_variant_bulk_create_by_attribute_id(+ product_variant_created_webhook_mock,+ staff_api_client,+ product,+ size_attribute,+ permission_manage_products,+):+ product_variant_count = ProductVariant.objects.count()+ attribute_value_count = size_attribute.values.count()+ 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]+ variants = [+ {+ "sku": sku,+ "weight": 2.5,+ "trackInventory": True,+ "attributes": [{"id": attribut_id, "values": [attribute_value.name]}],+ }+ ]++ 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)+ flush_post_commit_hooks()+ data = content["data"]["productVariantBulkCreate"]++ assert not data["errors"]+ assert data["count"] == 1+ assert data["productVariants"][0]["name"] == attribute_value.name+ assert product_variant_count + 1 == ProductVariant.objects.count()+ assert attribute_value_count == size_attribute.values.count()+ product_variant = ProductVariant.objects.get(sku=sku)+ product.refresh_from_db()+ assert product.default_variant == product_variant+ assert product_variant_created_webhook_mock.call_count == data["count"]+++def test_product_variant_bulk_create_with_swatch_attribute(+ staff_api_client, product, swatch_attribute, permission_manage_products+):+ product_variant_count = ProductVariant.objects.count()+ product.product_type.variant_attributes.set(+ [swatch_attribute], through_defaults={"variant_selection": True}+ )+ attribute_value_count = swatch_attribute.values.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_id = graphene.Node.to_global_id("Attribute", swatch_attribute.pk)+ attribute_value_1 = swatch_attribute.values.first()+ attribute_value_2 = swatch_attribute.values.last()+ sku = str(uuid4())[:12]+ variants = [+ {+ "sku": sku,+ "weight": 2.5,+ "trackInventory": True,+ "attributes": [{"id": attribute_id, "values": [attribute_value_1.name]}],+ },+ {+ "sku": sku + "a",+ "weight": 2.5,+ "trackInventory": True,+ "attributes": [{"id": attribute_id, "values": [attribute_value_2.name]}],+ },+ ]++ 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 not data["errors"]+ assert data["count"] == 2+ assert {variant["name"] for variant in data["productVariants"]} == {+ attribute_value_1.name,+ attribute_value_2.name,+ }+ assert product_variant_count + 2 == ProductVariant.objects.count()+ assert attribute_value_count == swatch_attribute.values.count()+ product_variant = ProductVariant.objects.get(sku=sku)+ product.refresh_from_db()+ assert product.default_variant == product_variant+++def test_product_variant_bulk_create_only_not_variant_selection_attributes(+ staff_api_client, product, size_attribute, permission_manage_products+):+ """Ensure that sku is set as variant name when only variant selection attributes+ are assigned.+ """+ product_variant_count = ProductVariant.objects.count()+ attribute_value_count = size_attribute.values.count()++ size_attribute.input_type = AttributeInputType.MULTISELECT+ variant_attribute = size_attribute.attributevariant.get()+ variant_attribute.variant_selection = False+ variant_attribute.save(update_fields=["variant_selection"])++ size_attribute.save(update_fields=["input_type"])++ 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]+ variants = [+ {+ "sku": sku,+ "weight": 2.5,+ "trackInventory": True,+ "attributes": [{"id": attribut_id, "values": [attribute_value.name]}],+ }+ ]++ 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 not data["errors"]+ assert data["count"] == 1+ assert data["productVariants"][0]["name"] == sku+ assert product_variant_count + 1 == ProductVariant.objects.count()+ assert attribute_value_count == size_attribute.values.count()+ product_variant = ProductVariant.objects.get(sku=sku)+ product.refresh_from_db()+ assert product.default_variant == product_variant+++def test_product_variant_bulk_create_empty_attribute(+ staff_api_client,+ product_with_single_variant,+ size_attribute,+ permission_manage_products,+):+ product = product_with_single_variant+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ variants = [{"sku": str(uuid4())[:12], "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 not data["errors"]+ assert data["count"] == 1+ product.refresh_from_db()+ assert product_variant_count + 1 == ProductVariant.objects.count()+++def test_product_variant_bulk_create_with_new_attribute_value(+ staff_api_client,+ product,+ size_attribute,+ permission_manage_products,+ boolean_attribute,+):+ product_variant_count = ProductVariant.objects.count()+ size_attribute_value_count = size_attribute.values.count()+ boolean_attribute_value_count = boolean_attribute.values.count()+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ boolean_attribute_id = graphene.Node.to_global_id("Attribute", boolean_attribute.pk)+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_value = size_attribute.values.last()+ variants = [+ {+ "sku": str(uuid4())[:12],+ "attributes": [+ {"id": size_attribute_id, "values": [attribute_value.name]},+ {"id": boolean_attribute_id, "boolean": None},+ ],+ },+ {+ "sku": str(uuid4())[:12],+ "attributes": [+ {"id": size_attribute_id, "values": ["Test-attribute"]},+ {"id": boolean_attribute_id, "boolean": True},+ ],+ },+ ]++ product.product_type.variant_attributes.add(boolean_attribute)++ 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 not data["errors"]+ assert data["count"] == 2+ assert product_variant_count + 2 == ProductVariant.objects.count()+ assert size_attribute_value_count + 1 == size_attribute.values.count()+ assert boolean_attribute_value_count == boolean_attribute.values.count()+++def test_product_variant_bulk_create_variant_selection_and_other_attributes(+ staff_api_client,+ product,+ size_attribute,+ file_attribute,+ permission_manage_products,+):+ """Ensure that only values for variant selection attributes are required."""+ product_type = product.product_type+ product_type.variant_attributes.add(file_attribute)++ product_variant_count = ProductVariant.objects.count()+ attribute_value_count = size_attribute.values.count()++ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)++ attribute_value = size_attribute.values.last()+ sku = str(uuid4())[:12]+ variants = [+ {+ "sku": sku,+ "weight": 2.5,+ "trackInventory": True,+ "attributes": [{"id": attribute_id, "values": [attribute_value.name]}],+ }+ ]++ 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 not data["errors"]+ assert data["count"] == 1+ assert product_variant_count + 1 == ProductVariant.objects.count()+ assert attribute_value_count == size_attribute.values.count()+ product_variant = ProductVariant.objects.get(sku=sku)+ product.refresh_from_db()+ assert product.default_variant == product_variant+++def test_product_variant_bulk_create_stocks_input(+ staff_api_client, product, permission_manage_products, warehouses, size_attribute+):+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_value_count = size_attribute.values.count()+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ attribute_value = size_attribute.values.last()+ variants = [+ {+ "sku": str(uuid4())[:12],+ "stocks": [+ {+ "quantity": 10,+ "warehouse": graphene.Node.to_global_id(+ "Warehouse", warehouses[0].pk+ ),+ }+ ],+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],+ },+ {+ "sku": str(uuid4())[:12],+ "attributes": [{"id": size_attribute_id, "values": ["Test-attribute"]}],+ "stocks": [+ {+ "quantity": 15,+ "warehouse": graphene.Node.to_global_id(+ "Warehouse", warehouses[0].pk+ ),+ },+ {+ "quantity": 15,+ "warehouse": graphene.Node.to_global_id(+ "Warehouse", warehouses[1].pk+ ),+ },+ ],+ },+ ]++ 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 not data["errors"]+ assert data["count"] == 2+ assert product_variant_count + 2 == ProductVariant.objects.count()+ assert attribute_value_count + 1 == size_attribute.values.count()++ expected_result = {+ variants[0]["sku"]: {+ "sku": variants[0]["sku"],+ "stocks": [+ {+ "warehouse": {"slug": warehouses[0].slug},+ "quantity": variants[0]["stocks"][0]["quantity"],+ }+ ],+ },+ variants[1]["sku"]: {+ "sku": variants[1]["sku"],+ "stocks": [+ {+ "warehouse": {"slug": warehouses[0].slug},+ "quantity": variants[1]["stocks"][0]["quantity"],+ },+ {+ "warehouse": {"slug": warehouses[1].slug},+ "quantity": variants[1]["stocks"][1]["quantity"],+ },+ ],+ },+ }+ for variant_data in data["productVariants"]:+ variant_data.pop("id")+ assert variant_data["sku"] in expected_result+ expected_variant = expected_result[variant_data["sku"]]+ expected_stocks = expected_variant["stocks"]+ assert all([stock in expected_stocks for stock in variant_data["stocks"]])+++def test_product_variant_bulk_create_duplicated_warehouses(+ staff_api_client, product, permission_manage_products, warehouses, size_attribute+):+ product_id = graphene.Node.to_global_id("Product", product.pk)+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ attribute_value = size_attribute.values.last()+ warehouse1_id = graphene.Node.to_global_id("Warehouse", warehouses[0].pk)+ variants = [+ {+ "sku": str(uuid4())[:12],+ "stocks": [+ {+ "quantity": 10,+ "warehouse": graphene.Node.to_global_id(+ "Warehouse", warehouses[1].pk+ ),+ }+ ],+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],+ },+ {+ "sku": str(uuid4())[:12],+ "attributes": [{"id": size_attribute_id, "values": ["Test-attribute"]}],+ "stocks": [+ {"quantity": 15, "warehouse": warehouse1_id},+ {"quantity": 15, "warehouse": warehouse1_id},+ ],+ },+ ]++ 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"]+ errors = data["errors"]++ assert not data["productVariants"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "stocks"+ assert error["index"] == 1+ assert error["code"] == ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.name+ assert error["warehouses"] == [warehouse1_id]+++def test_product_variant_bulk_create_channel_listings_input(+ staff_api_client,+ product_available_in_many_channels,+ permission_manage_products,+ warehouses,+ size_attribute,+ channel_USD,+ channel_PLN,+):+ product = product_available_in_many_channels+ ProductChannelListing.objects.filter(product=product, channel=channel_PLN).update(+ is_published=False+ )+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_value_count = size_attribute.values.count()+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ attribute_value = size_attribute.values.last()+ variants = [+ {+ "sku": str(uuid4())[:12],+ "channelListings": [+ {+ "price": 10.0,+ "costPrice": 11.0,+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),+ }+ ],+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],+ },+ {+ "sku": str(uuid4())[:12],+ "attributes": [{"id": size_attribute_id, "values": ["Test-attribute"]}],+ "channelListings": [+ {+ "price": 15.0,+ "costPrice": 16.0,+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),+ },+ {+ "price": 12.0,+ "costPrice": 13.0,+ "channelId": graphene.Node.to_global_id("Channel", channel_PLN.pk),+ },+ ],+ },+ ]++ 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 not data["errors"]+ assert data["count"] == 2+ assert product_variant_count + 2 == ProductVariant.objects.count()+ assert attribute_value_count + 1 == size_attribute.values.count()++ expected_result = {+ variants[0]["sku"]: {+ "sku": variants[0]["sku"],+ "channelListings": [+ {+ "channel": {"slug": channel_USD.slug},+ "price": {+ "amount": variants[0]["channelListings"][0]["price"],+ "currency": channel_USD.currency_code,+ },+ "costPrice": {+ "amount": variants[0]["channelListings"][0]["costPrice"],+ "currency": channel_USD.currency_code,+ },+ "preorderThreshold": {"quantity": None},+ }+ ],+ },+ variants[1]["sku"]: {+ "sku": variants[1]["sku"],+ "channelListings": [+ {+ "channel": {"slug": channel_USD.slug},+ "price": {+ "amount": variants[1]["channelListings"][0]["price"],+ "currency": channel_USD.currency_code,+ },+ "costPrice": {+ "amount": variants[1]["channelListings"][0]["costPrice"],+ "currency": channel_USD.currency_code,+ },+ "preorderThreshold": {"quantity": None},+ },+ {+ "channel": {"slug": channel_PLN.slug},+ "price": {+ "amount": variants[1]["channelListings"][1]["price"],+ "currency": channel_PLN.currency_code,+ },+ "costPrice": {+ "amount": variants[1]["channelListings"][1]["costPrice"],+ "currency": channel_PLN.currency_code,+ },+ "preorderThreshold": {"quantity": None},+ },+ ],+ },+ }+ for variant_data in data["productVariants"]:+ variant_data.pop("id")+ assert variant_data["sku"] in expected_result+ expected_variant = expected_result[variant_data["sku"]]+ expected_channel_listing = expected_variant["channelListings"]+ assert all(+ [+ channelListing in expected_channel_listing+ for channelListing in variant_data["channelListings"]+ ]+ )+++def test_product_variant_bulk_create_preorder_channel_listings_input(+ staff_api_client,+ product_available_in_many_channels,+ permission_manage_products,+ size_attribute,+ channel_USD,+ channel_PLN,+):+ product = product_available_in_many_channels+ ProductChannelListing.objects.filter(product=product, channel=channel_PLN).update(+ is_published=False+ )+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_value_count = size_attribute.values.count()+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ attribute_value = size_attribute.values.last()++ global_threshold = 10+ end_date = (+ (datetime.now() + timedelta(days=3))+ .astimezone()+ .replace(microsecond=0)+ .isoformat()+ )++ variants = [+ {+ "sku": str(uuid4())[:12],+ "channelListings": [+ {+ "price": 10.0,+ "costPrice": 11.0,+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),+ "preorderThreshold": 5,+ }+ ],+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],+ "preorder": {+ "globalThreshold": global_threshold,+ "endDate": end_date,+ },+ },+ {+ "sku": str(uuid4())[:12],+ "attributes": [{"id": size_attribute_id, "values": ["Test-attribute"]}],+ "channelListings": [+ {+ "price": 15.0,+ "costPrice": 16.0,+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),+ "preorderThreshold": None,+ },+ {+ "price": 12.0,+ "costPrice": 13.0,+ "channelId": graphene.Node.to_global_id("Channel", channel_PLN.pk),+ "preorderThreshold": 4,+ },+ ],+ "preorder": {+ "globalThreshold": global_threshold,+ "endDate": end_date,+ },+ },+ ]++ 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 not data["errors"]+ assert data["count"] == 2+ assert product_variant_count + 2 == ProductVariant.objects.count()+ assert attribute_value_count + 1 == size_attribute.values.count()++ expected_result = {+ variants[0]["sku"]: {+ "sku": variants[0]["sku"],+ "channelListings": [{"preorderThreshold": {"quantity": 5}}],+ "preorder": {+ "globalThreshold": global_threshold,+ "endDate": end_date,+ },+ },+ variants[1]["sku"]: {+ "sku": variants[1]["sku"],+ "channelListings": [+ {"preorderThreshold": {"quantity": None}},+ {"preorderThreshold": {"quantity": 4}},+ ],+ "preorder": {+ "globalThreshold": global_threshold,+ "endDate": end_date,+ },+ },+ }+ for variant_data in data["productVariants"]:+ variant_data.pop("id")+ assert variant_data["sku"] in expected_result+ expected_variant = expected_result[variant_data["sku"]]+ expected_channel_listing_thresholds = [+ channel_listing["preorderThreshold"]["quantity"]+ for channel_listing in expected_variant["channelListings"]+ ]+ assert all(+ [+ channel_listing["preorderThreshold"]["quantity"]+ in expected_channel_listing_thresholds+ for channel_listing in variant_data["channelListings"]+ ]+ )+ preorder_data = variant_data["preorder"]+ assert preorder_data["globalThreshold"] == global_threshold+ assert preorder_data["endDate"] == end_date+++def test_product_variant_bulk_create_duplicated_channels(+ staff_api_client,+ product_available_in_many_channels,+ permission_manage_products,+ warehouses,+ size_attribute,+ channel_USD,+):+ product = product_available_in_many_channels+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ attribute_value = size_attribute.values.last()+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)+ variants = [+ {+ "sku": str(uuid4())[:12],+ "channelListings": [+ {"price": 10.0, "channelId": channel_id},+ {"price": 10.0, "channelId": channel_id},+ ],+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],+ },+ ]++ 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"] == "channelListings"+ assert error["code"] == ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.name+ assert error["index"] == 0+ assert error["channels"] == [channel_id]+ assert product_variant_count == ProductVariant.objects.count()+++def test_product_variant_bulk_create_too_many_decimal_places_in_price(+ staff_api_client,+ product_available_in_many_channels,+ permission_manage_products,+ size_attribute,+ channel_USD,+ channel_PLN,+):+ product = product_available_in_many_channels+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ attribute_value = size_attribute.values.last()+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)+ variants = [+ {+ "sku": str(uuid4())[:12],+ "channelListings": [+ {"price": 10.1234, "costPrice": 10.1234, "channelId": channel_id},+ {"price": 10.12345, "costPrice": 10.12345, "channelId": channel_pln_id},+ ],+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],+ },+ ]++ 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"]) == 4+ errors = data["errors"]+ assert errors[0]["field"] == "price"+ assert errors[0]["code"] == ProductVariantBulkErrorCode.INVALID_PRICE.name+ assert errors[0]["index"] == 0+ assert errors[0]["channels"] == [channel_id]+ assert errors[1]["field"] == "price"+ assert errors[1]["code"] == ProductVariantBulkErrorCode.INVALID_PRICE.name+ assert errors[1]["index"] == 0+ assert errors[1]["channels"] == [channel_pln_id]+ assert errors[2]["field"] == "costPrice"+ assert errors[2]["code"] == ProductVariantBulkErrorCode.INVALID_PRICE.name+ assert errors[2]["index"] == 0+ assert errors[2]["channels"] == [channel_id]+ assert errors[3]["field"] == "costPrice"+ assert errors[3]["code"] == ProductVariantBulkErrorCode.INVALID_PRICE.name+ assert errors[3]["index"] == 0+ assert errors[3]["channels"] == [channel_pln_id]+ assert product_variant_count == ProductVariant.objects.count()+++def test_product_variant_bulk_create_product_not_assigned_to_channel(+ staff_api_client,+ product,+ permission_manage_products,+ warehouses,+ size_attribute,+ channel_PLN,+):+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ assert not ProductChannelListing.objects.filter(+ product=product, channel=channel_PLN+ ).exists()+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ attribute_value = size_attribute.values.last()+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)+ variants = [+ {+ "sku": str(uuid4())[:12],+ "channelListings": [{"price": 10.0, "channelId": channel_id}],+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],+ },+ ]++ 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]+ code = ProductVariantBulkErrorCode.PRODUCT_NOT_ASSIGNED_TO_CHANNEL.name+ assert error["field"] == "channelId"+ assert error["code"] == code+ assert error["index"] == 0+ assert error["channels"] == [channel_id]+ assert product_variant_count == ProductVariant.objects.count()+++def test_product_variant_bulk_create_duplicated_sku(+ staff_api_client,+ product,+ product_with_default_variant,+ size_attribute,+ permission_manage_products,+):+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ sku = product.variants.first().sku+ sku2 = product_with_default_variant.variants.first().sku+ assert not sku == sku2+ variants = [+ {+ "sku": sku,+ "attributes": [{"id": size_attribute_id, "values": ["Test-value"]}],+ },+ {+ "sku": sku2,+ "attributes": [{"id": size_attribute_id, "values": ["Test-valuee"]}],+ },+ ]++ 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"]) == 2+ errors = data["errors"]+ for index, error in enumerate(errors):+ assert error["field"] == "sku"+ assert error["code"] == ProductVariantBulkErrorCode.UNIQUE.name+ assert error["index"] == index+ assert product_variant_count == ProductVariant.objects.count()+++def test_product_variant_bulk_create_duplicated_sku_in_input(+ staff_api_client, product, size_attribute, permission_manage_products+):+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ sku = str(uuid4())[:12]+ variants = [+ {+ "sku": sku,+ "attributes": [{"id": size_attribute_id, "values": ["Test-value"]}],+ },+ {+ "sku": sku,+ "attributes": [{"id": size_attribute_id, "values": ["Test-value2"]}],+ },+ ]++ 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"]) == 2+ error = data["errors"][0]+ assert error["field"] == "sku"+ assert error["code"] == ProductVariantBulkErrorCode.UNIQUE.name+ assert error["index"] == 0+ assert product_variant_count == ProductVariant.objects.count()+++def test_product_variant_bulk_create_without_sku(+ staff_api_client, product, size_attribute, permission_manage_products+):+ product_variant_count = ProductVariant.objects.count()+ attribute_value_count = size_attribute.values.count()+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_value = size_attribute.values.last()+ variants = [+ {+ "sku": " ",+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],+ },+ {+ "sku": None,+ "attributes": [{"id": size_attribute_id, "values": ["Test-attribute"]}],+ },+ ]++ 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 not data["errors"]+ assert data["count"] == 2+ assert product_variant_count + 2 == ProductVariant.objects.count()+ assert attribute_value_count + 1 == size_attribute.values.count()+ assert ProductVariant.objects.filter(sku__isnull=True).count() == 2+++def test_product_variant_bulk_create_many_errors(+ staff_api_client, product, size_attribute, permission_manage_products+):+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ non_existent_attribute_pk = 0+ invalid_attribute_id = graphene.Node.to_global_id(+ "Attribute", non_existent_attribute_pk+ )+ sku = product.variants.first().sku+ variants = [+ {+ "sku": str(uuid4())[:12],+ "attributes": [{"id": size_attribute_id, "values": ["Test-value1"]}],+ },+ {+ "sku": str(uuid4())[:12],+ "attributes": [{"id": size_attribute_id, "values": ["Test-value4"]}],+ },+ {+ "sku": sku,+ "attributes": [{"id": size_attribute_id, "values": ["Test-value2"]}],+ },+ {+ "sku": str(uuid4())[:12],+ "attributes": [{"id": invalid_attribute_id, "values": ["Test-value3"]}],+ },+ ]++ 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"]) == 3+ errors = data["errors"]+ expected_errors = [+ {+ "field": "sku",+ "index": 2,+ "code": ProductVariantBulkErrorCode.UNIQUE.name,+ "message": ANY,+ "warehouses": None,+ "channels": None,+ },+ {+ "field": "attributes",+ "index": 3,+ "code": ProductVariantBulkErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.name,+ "message": ANY,+ "warehouses": None,+ "channels": None,+ },+ ]+ for expected_error in expected_errors:+ assert expected_error in 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,+ 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": ["big"]},+ ],+ }+ ]+ 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 not data["errors"]+ assert data["count"] == 1+ assert product_variant_count + 1 == ProductVariant.objects.count()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 edb84188cc..3d0fb045ad 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@@ -5,55 +5,61 @@ from uuid import uuid4import graphenefrom .....attribute import AttributeInputType-from .....product.error_codes import ProductErrorCode+from .....product.error_codes import ProductVariantBulkErrorCodefrom .....product.models import ProductChannelListing, ProductVariantfrom .....tests.utils import flush_post_commit_hooks+from ....core.enums import ErrorPolicyEnumfrom ....tests.utils import get_graphql_contentPRODUCT_VARIANT_BULK_CREATE_MUTATION = """mutation ProductVariantBulkCreate(- $variants: [ProductVariantBulkCreateInput!]!, $productId: ID!+ $variants: [ProductVariantBulkCreateInput!]!,+ $productId: ID!,+ $errorPolicy: ErrorPolicyEnum) {- productVariantBulkCreate(variants: $variants, product: $productId) {- errors {- field- message- code- index- warehouses- channels- }- productVariants{- id- name- sku- stocks {- warehouse {- slug+ productVariantBulkCreate(+ variants: $variants, product: $productId, errorPolicy: $errorPolicy+ ) {+ results{+ productVariant{+ id+ name+ sku+ stocks {+ warehouse {+ slug+ }+ quantity+ }+ channelListings {+ channel {+ slug+ }+ price {+ currency+ amount+ }+ costPrice {+ currency+ amount+ }+ preorderThreshold {+ quantity+ }+ }+ preorder {+ globalThreshold+ endDate+ }}- quantity- }- channelListings {- channel {- slug- }- price {- currency- amount- }- costPrice {- currency- amount- }- preorderThreshold {- quantity+ errors {+ field+ message+ code+ warehouses+ channels}}- preorder {- globalThreshold- endDate- }- }count}}@@ -93,14 +99,14 @@ def test_product_variant_bulk_create_by_name(response = staff_api_client.post_graphql(PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables)- content = get_graphql_content(response)+ content = get_graphql_content(response, ignore_errors=True)flush_post_commit_hooks()data = content["data"]["productVariantBulkCreate"]# then- assert not data["errors"]+ assert not data["results"][0]["errors"]assert data["count"] == 1- assert data["productVariants"][0]["name"] == name+ assert data["results"][0]["productVariant"]["name"] == nameassert product_variant_count + 1 == ProductVariant.objects.count()assert attribute_value_count == size_attribute.values.count()product_variant = ProductVariant.objects.get(sku=sku)@@ -117,6 +123,7 @@ def test_product_variant_bulk_create_by_attribute_id(size_attribute,permission_manage_products,):+ # givenproduct_variant_count = ProductVariant.objects.count()attribute_value_count = size_attribute.values.count()product_id = graphene.Node.to_global_id("Product", product.pk)@@ -133,6 +140,8 @@ def test_product_variant_bulk_create_by_attribute_id(]variables = {"productId": product_id, "variants": variants}++ # whenstaff_api_client.user.user_permissions.add(permission_manage_products)response = staff_api_client.post_graphql(PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables@@ -141,9 +150,10 @@ def test_product_variant_bulk_create_by_attribute_id(flush_post_commit_hooks()data = content["data"]["productVariantBulkCreate"]- assert not data["errors"]+ # then+ assert not data["results"][0]["errors"]assert data["count"] == 1- assert data["productVariants"][0]["name"] == attribute_value.name+ assert data["results"][0]["productVariant"]["name"] == attribute_value.nameassert product_variant_count + 1 == ProductVariant.objects.count()assert attribute_value_count == size_attribute.values.count()product_variant = ProductVariant.objects.get(sku=sku)@@ -155,6 +165,7 @@ def test_product_variant_bulk_create_by_attribute_id(def test_product_variant_bulk_create_with_swatch_attribute(staff_api_client, product, swatch_attribute, permission_manage_products):+ # givenproduct_variant_count = ProductVariant.objects.count()product.product_type.variant_attributes.set([swatch_attribute], through_defaults={"variant_selection": True}@@ -181,15 +192,20 @@ def test_product_variant_bulk_create_with_swatch_attribute(]variables = {"productId": product_id, "variants": variants}++ # whenstaff_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 not data["errors"]++ # then+ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]assert data["count"] == 2- assert {variant["name"] for variant in data["productVariants"]} == {+ assert {result["productVariant"]["name"] for result in data["results"]} == {attribute_value_1.name,attribute_value_2.name,}@@ -206,6 +222,8 @@ def test_product_variant_bulk_create_only_not_variant_selection_attributes("""Ensure that sku is set as variant name when only variant selection attributesare assigned."""++ # givenproduct_variant_count = ProductVariant.objects.count()attribute_value_count = size_attribute.values.count()@@ -231,15 +249,19 @@ def test_product_variant_bulk_create_only_not_variant_selection_attributes(]variables = {"productId": product_id, "variants": variants}++ # whenstaff_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 not data["errors"]++ # then+ assert not data["results"][0]["errors"]assert data["count"] == 1- assert data["productVariants"][0]["name"] == sku+ assert data["results"][0]["productVariant"]["name"] == skuassert product_variant_count + 1 == ProductVariant.objects.count()assert attribute_value_count == size_attribute.values.count()product_variant = ProductVariant.objects.get(sku=sku)@@ -265,7 +287,7 @@ def test_product_variant_bulk_create_empty_attribute()content = get_graphql_content(response)data = content["data"]["productVariantBulkCreate"]- assert not data["errors"]+ assert not data["results"][0]["errors"]assert data["count"] == 1product.refresh_from_db()assert product_variant_count + 1 == ProductVariant.objects.count()@@ -278,6 +300,7 @@ def test_product_variant_bulk_create_with_new_attribute_value(permission_manage_products,boolean_attribute,):+ # givenproduct_variant_count = ProductVariant.objects.count()size_attribute_value_count = size_attribute.values.count()boolean_attribute_value_count = boolean_attribute.values.count()@@ -303,15 +326,19 @@ def test_product_variant_bulk_create_with_new_attribute_value(]product.product_type.variant_attributes.add(boolean_attribute)-variables = {"productId": product_id, "variants": variants}++ # whenstaff_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 not data["errors"]++ # then+ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]assert data["count"] == 2assert product_variant_count + 2 == ProductVariant.objects.count()assert size_attribute_value_count + 1 == size_attribute.values.count()@@ -326,6 +353,8 @@ def test_product_variant_bulk_create_variant_selection_and_other_attributes(permission_manage_products,):"""Ensure that only values for variant selection attributes are required."""++ # givenproduct_type = product.product_typeproduct_type.variant_attributes.add(file_attribute)@@ -345,15 +374,18 @@ def test_product_variant_bulk_create_variant_selection_and_other_attributes("attributes": [{"id": attribute_id, "values": [attribute_value.name]}],}]-variables = {"productId": product_id, "variants": variants}++ # whenstaff_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 not data["errors"]++ # then+ assert not data["results"][0]["errors"]assert data["count"] == 1assert product_variant_count + 1 == ProductVariant.objects.count()assert attribute_value_count == size_attribute.values.count()@@ -365,6 +397,7 @@ def test_product_variant_bulk_create_variant_selection_and_other_attributes(def test_product_variant_bulk_create_stocks_input(staff_api_client, product, permission_manage_products, warehouses, size_attribute):+ # givenproduct_variant_count = ProductVariant.objects.count()product_id = graphene.Node.to_global_id("Product", product.pk)attribute_value_count = size_attribute.values.count()@@ -402,19 +435,15 @@ def test_product_variant_bulk_create_stocks_input(],},]-variables = {"productId": product_id, "variants": variants}++ # whenstaff_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 not data["errors"]- assert data["count"] == 2- assert product_variant_count + 2 == ProductVariant.objects.count()- assert attribute_value_count + 1 == size_attribute.values.count()-expected_result = {variants[0]["sku"]: {"sku": variants[0]["sku"],@@ -439,7 +468,16 @@ def test_product_variant_bulk_create_stocks_input(],},}- for variant_data in data["productVariants"]:++ # then+ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]+ assert data["count"] == 2+ assert product_variant_count + 2 == ProductVariant.objects.count()+ assert attribute_value_count + 1 == size_attribute.values.count()++ for result in data["results"]:+ variant_data = result["productVariant"]variant_data.pop("id")assert variant_data["sku"] in expected_resultexpected_variant = expected_result[variant_data["sku"]]@@ -450,6 +488,7 @@ def test_product_variant_bulk_create_stocks_input(def test_product_variant_bulk_create_duplicated_warehouses(staff_api_client, product, permission_manage_products, warehouses, size_attribute):+ # givenproduct_id = graphene.Node.to_global_id("Product", product.pk)size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)attribute_value = size_attribute.values.last()@@ -476,22 +515,83 @@ def test_product_variant_bulk_create_duplicated_warehouses(],},]-variables = {"productId": product_id, "variants": variants}++ # whenstaff_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"]- errors = data["errors"]+ errors = data["results"][1]["errors"]- assert not data["productVariants"]+ # then+ assert not data["results"][0]["errors"]+ assert not data["results"][0]["productVariant"]+ assert not data["results"][1]["productVariant"]assert len(errors) == 1error = errors[0]assert error["field"] == "stocks"- assert error["index"] == 1- assert error["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name+ assert error["code"] == ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.name+ assert error["warehouses"] == [warehouse1_id]+++def test_product_variant_bulk_create_duplicated_warehouses_when_ignore_failed(+ staff_api_client, product, permission_manage_products, warehouses, size_attribute+):+ # given+ product_id = graphene.Node.to_global_id("Product", product.pk)+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ attribute_value = size_attribute.values.last()+ warehouse1_id = graphene.Node.to_global_id("Warehouse", warehouses[0].pk)+ variants = [+ {+ "sku": str(uuid4())[:12],+ "stocks": [+ {+ "quantity": 10,+ "warehouse": graphene.Node.to_global_id(+ "Warehouse", warehouses[1].pk+ ),+ }+ ],+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],+ },+ {+ "sku": str(uuid4())[:12],+ "attributes": [{"id": size_attribute_id, "values": ["Test-attribute"]}],+ "stocks": [+ {"quantity": 15, "warehouse": warehouse1_id},+ {"quantity": 15, "warehouse": warehouse1_id},+ ],+ },+ ]++ variables = {+ "errorPolicy": ErrorPolicyEnum.IGNORE_FAILED.name,+ "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"]+ errors = data["results"][1]["errors"]++ # then+ assert not data["results"][0]["errors"]+ assert data["results"][0]["productVariant"]+ assert data["results"][1]["productVariant"]+ assert not data["results"][1]["productVariant"]["stocks"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "stocks"+ assert error["code"] == ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.nameassert error["warehouses"] == [warehouse1_id]@@ -504,6 +604,7 @@ def test_product_variant_bulk_create_channel_listings_input(channel_USD,channel_PLN,):+ # givenproduct = product_available_in_many_channelsProductChannelListing.objects.filter(product=product, channel=channel_PLN).update(is_published=False@@ -542,19 +643,15 @@ def test_product_variant_bulk_create_channel_listings_input(],},]-variables = {"productId": product_id, "variants": variants}++ # whenstaff_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 not data["errors"]- assert data["count"] == 2- assert product_variant_count + 2 == ProductVariant.objects.count()- assert attribute_value_count + 1 == size_attribute.values.count()-expected_result = {variants[0]["sku"]: {"sku": variants[0]["sku"],@@ -603,7 +700,16 @@ def test_product_variant_bulk_create_channel_listings_input(],},}- for variant_data in data["productVariants"]:++ # then+ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]+ assert data["count"] == 2+ assert product_variant_count + 2 == ProductVariant.objects.count()+ assert attribute_value_count + 1 == size_attribute.values.count()++ for result in data["results"]:+ variant_data = result["productVariant"]variant_data.pop("id")assert variant_data["sku"] in expected_resultexpected_variant = expected_result[variant_data["sku"]]@@ -624,6 +730,7 @@ def test_product_variant_bulk_create_preorder_channel_listings_input(channel_USD,channel_PLN,):+ # givenproduct = product_available_in_many_channelsProductChannelListing.objects.filter(product=product, channel=channel_PLN).update(is_published=False@@ -684,17 +791,14 @@ def test_product_variant_bulk_create_preorder_channel_listings_input(]variables = {"productId": product_id, "variants": variants}++ # whenstaff_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 not data["errors"]- assert data["count"] == 2- assert product_variant_count + 2 == ProductVariant.objects.count()- assert attribute_value_count + 1 == size_attribute.values.count()-expected_result = {variants[0]["sku"]: {"sku": variants[0]["sku"],@@ -716,7 +820,16 @@ def test_product_variant_bulk_create_preorder_channel_listings_input(},},}- for variant_data in data["productVariants"]:++ # then+ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]+ assert data["count"] == 2+ assert product_variant_count + 2 == ProductVariant.objects.count()+ assert attribute_value_count + 1 == size_attribute.values.count()++ for result in data["results"]:+ variant_data = result["productVariant"]variant_data.pop("id")assert variant_data["sku"] in expected_resultexpected_variant = expected_result[variant_data["sku"]]@@ -744,6 +857,7 @@ def test_product_variant_bulk_create_duplicated_channels(size_attribute,channel_USD,):+ # givenproduct = product_available_in_many_channelsproduct_variant_count = ProductVariant.objects.count()product_id = graphene.Node.to_global_id("Product", product.pk)@@ -762,21 +876,75 @@ def test_product_variant_bulk_create_duplicated_channels(]variables = {"productId": product_id, "variants": variants}++ # whenstaff_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]++ # then+ assert len(data["results"][0]["errors"]) == 1+ error = data["results"][0]["errors"][0]assert error["field"] == "channelListings"- assert error["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name- assert error["index"] == 0+ assert error["code"] == ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.nameassert error["channels"] == [channel_id]assert product_variant_count == ProductVariant.objects.count()+def test_product_variant_bulk_create_duplicated_channels_when_ignore_failed(+ staff_api_client,+ product_available_in_many_channels,+ permission_manage_products,+ warehouses,+ size_attribute,+ channel_USD,+):+ # given+ product = product_available_in_many_channels+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ attribute_value = size_attribute.values.last()+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)+ variants = [+ {+ "sku": str(uuid4())[:12],+ "channelListings": [+ {"price": 10.0, "channelId": channel_id},+ {"price": 10.0, "channelId": channel_id},+ ],+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],+ },+ ]++ variables = {+ "productId": product_id,+ "variants": variants,+ "errorPolicy": ErrorPolicyEnum.IGNORE_FAILED.name,+ }++ # 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+ assert len(data["results"][0]["errors"]) == 1+ assert data["results"][0]["productVariant"]+ assert not data["results"][0]["productVariant"]["channelListings"]+ error = data["results"][0]["errors"][0]+ assert error["field"] == "channelListings"+ assert error["code"] == ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.name+ assert error["channels"] == [channel_id]+ assert product_variant_count + 1 == ProductVariant.objects.count()++def test_product_variant_bulk_create_too_many_decimal_places_in_price(staff_api_client,product_available_in_many_channels,@@ -785,6 +953,7 @@ def test_product_variant_bulk_create_too_many_decimal_places_in_price(channel_USD,channel_PLN,):+ # givenproduct = product_available_in_many_channelsproduct_variant_count = ProductVariant.objects.count()product_id = graphene.Node.to_global_id("Product", product.pk)@@ -804,33 +973,94 @@ def test_product_variant_bulk_create_too_many_decimal_places_in_price(]variables = {"productId": product_id, "variants": variants}++ # whenstaff_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"]) == 4- errors = data["errors"]++ # then+ errors = data["results"][0]["errors"]+ assert len(errors) == 4assert errors[0]["field"] == "price"- assert errors[0]["code"] == ProductErrorCode.INVALID.name- assert errors[0]["index"] == 0+ assert errors[0]["code"] == ProductVariantBulkErrorCode.INVALID_PRICE.nameassert errors[0]["channels"] == [channel_id]- assert errors[1]["field"] == "price"- assert errors[1]["code"] == ProductErrorCode.INVALID.name- assert errors[1]["index"] == 0- assert errors[1]["channels"] == [channel_pln_id]- assert errors[2]["field"] == "costPrice"- assert errors[2]["code"] == ProductErrorCode.INVALID.name- assert errors[2]["index"] == 0- assert errors[2]["channels"] == [channel_id]+ assert errors[1]["field"] == "costPrice"+ assert errors[1]["code"] == ProductVariantBulkErrorCode.INVALID_PRICE.name+ assert errors[1]["channels"] == [channel_id]+ assert errors[2]["field"] == "price"+ assert errors[2]["code"] == ProductVariantBulkErrorCode.INVALID_PRICE.name+ assert errors[2]["channels"] == [channel_pln_id]assert errors[3]["field"] == "costPrice"- assert errors[3]["code"] == ProductErrorCode.INVALID.name- assert errors[3]["index"] == 0+ assert errors[3]["code"] == ProductVariantBulkErrorCode.INVALID_PRICE.nameassert errors[3]["channels"] == [channel_pln_id]assert product_variant_count == ProductVariant.objects.count()+def test_product_variant_bulk_create_too_many_price_decimal_places_when_ignore_failed(+ staff_api_client,+ product_available_in_many_channels,+ permission_manage_products,+ size_attribute,+ channel_USD,+ channel_PLN,+):+ # given+ product = product_available_in_many_channels+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ attribute_value = size_attribute.values.last()+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)+ variants = [+ {+ "sku": str(uuid4())[:12],+ "channelListings": [+ {"price": 10.1234, "costPrice": 10.1234, "channelId": channel_id},+ {"price": 10.12345, "costPrice": 10.12345, "channelId": channel_pln_id},+ ],+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],+ },+ ]++ variables = {+ "productId": product_id,+ "variants": variants,+ "errorPolicy": ErrorPolicyEnum.IGNORE_FAILED.name,+ }++ # 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"]+ errors = data["results"][0]["errors"]++ # then+ assert data["results"][0]["productVariant"]+ assert not data["results"][0]["productVariant"]["channelListings"]+ assert len(errors) == 4+ assert errors[0]["field"] == "price"+ assert errors[0]["code"] == ProductVariantBulkErrorCode.INVALID_PRICE.name+ assert errors[0]["channels"] == [channel_id]+ assert errors[1]["field"] == "costPrice"+ assert errors[1]["code"] == ProductVariantBulkErrorCode.INVALID_PRICE.name+ assert errors[1]["channels"] == [channel_id]+ assert errors[2]["field"] == "price"+ assert errors[2]["code"] == ProductVariantBulkErrorCode.INVALID_PRICE.name+ assert errors[2]["channels"] == [channel_pln_id]+ assert errors[3]["field"] == "costPrice"+ assert errors[3]["code"] == ProductVariantBulkErrorCode.INVALID_PRICE.name+ assert errors[3]["channels"] == [channel_pln_id]+ assert product_variant_count + 1 == ProductVariant.objects.count()++def test_product_variant_bulk_create_product_not_assigned_to_channel(staff_api_client,product,@@ -839,6 +1069,7 @@ def test_product_variant_bulk_create_product_not_assigned_to_channel(size_attribute,channel_PLN,):+ # givenproduct_variant_count = ProductVariant.objects.count()product_id = graphene.Node.to_global_id("Product", product.pk)assert not ProductChannelListing.objects.filter(@@ -856,17 +1087,21 @@ def test_product_variant_bulk_create_product_not_assigned_to_channel(]variables = {"productId": product_id, "variants": variants}++ # whenstaff_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]++ # then+ assert len(data["results"][0]["errors"]) == 1+ error = data["results"][0]["errors"][0]+ code = ProductVariantBulkErrorCode.PRODUCT_NOT_ASSIGNED_TO_CHANNEL.nameassert error["field"] == "channelId"- assert error["code"] == ProductErrorCode.PRODUCT_NOT_ASSIGNED_TO_CHANNEL.name- assert error["index"] == 0+ assert error["code"] == codeassert error["channels"] == [channel_id]assert product_variant_count == ProductVariant.objects.count()@@ -878,6 +1113,7 @@ def test_product_variant_bulk_create_duplicated_sku(size_attribute,permission_manage_products,):+ # givenproduct_variant_count = ProductVariant.objects.count()product_id = graphene.Node.to_global_id("Product", product.pk)size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)@@ -896,24 +1132,82 @@ def test_product_variant_bulk_create_duplicated_sku(]variables = {"productId": product_id, "variants": variants}++ # whenstaff_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"]) == 2- errors = data["errors"]- for index, error in enumerate(errors):- assert error["field"] == "sku"- assert error["code"] == ProductErrorCode.UNIQUE.name- assert error["index"] == index++ # then+ input_1_errors = data["results"][0]["errors"]+ input_2_errors = data["results"][1]["errors"]+ assert input_1_errors+ assert input_2_errors+ assert input_1_errors[0]["field"] == "sku"+ assert input_1_errors[0]["code"] == ProductVariantBulkErrorCode.UNIQUE.name+ assert input_2_errors[0]["field"] == "sku"+ assert input_2_errors[0]["code"] == ProductVariantBulkErrorCode.UNIQUE.name+ assert product_variant_count == ProductVariant.objects.count()+++def test_product_variant_bulk_create_duplicated_sku_when_ignore_failed(+ staff_api_client,+ product,+ product_with_default_variant,+ size_attribute,+ permission_manage_products,+):+ # given+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ sku = product.variants.first().sku+ sku2 = product_with_default_variant.variants.first().sku+ assert not sku == sku2+ variants = [+ {+ "sku": sku,+ "attributes": [{"id": size_attribute_id, "values": ["Test-value"]}],+ },+ {+ "sku": sku2,+ "attributes": [{"id": size_attribute_id, "values": ["Test-valuee"]}],+ },+ ]++ variables = {+ "productId": product_id,+ "variants": variants,+ "errorPolicy": ErrorPolicyEnum.IGNORE_FAILED.name,+ }++ # 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_1_errors = data["results"][0]["errors"]+ input_2_errors = data["results"][1]["errors"]+ assert input_1_errors+ assert input_2_errors+ assert input_1_errors[0]["field"] == "sku"+ assert input_1_errors[0]["code"] == ProductVariantBulkErrorCode.UNIQUE.name+ assert input_2_errors[0]["field"] == "sku"+ assert input_2_errors[0]["code"] == ProductVariantBulkErrorCode.UNIQUE.nameassert product_variant_count == ProductVariant.objects.count()def test_product_variant_bulk_create_duplicated_sku_in_input(staff_api_client, product, size_attribute, permission_manage_products):+ # givenproduct_variant_count = ProductVariant.objects.count()product_id = graphene.Node.to_global_id("Product", product.pk)size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)@@ -930,23 +1224,74 @@ def test_product_variant_bulk_create_duplicated_sku_in_input(]variables = {"productId": product_id, "variants": variants}++ # whenstaff_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"] == "sku"- assert error["code"] == ProductErrorCode.UNIQUE.name- assert error["index"] == 1++ # then+ input_2_errors = data["results"][1]["errors"]+ assert data["results"][0]["errors"]+ assert len(input_2_errors) == 1+ assert input_2_errors[0]["field"] == "sku"+ assert input_2_errors[0]["code"] == ProductVariantBulkErrorCode.UNIQUE.name+ assert product_variant_count == ProductVariant.objects.count()+++def test_product_variant_bulk_create_duplicated_sku_in_input_when_ignore_failed(+ staff_api_client, product, size_attribute, permission_manage_products+):+ # given+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ sku = str(uuid4())[:12]+ variants = [+ {+ "sku": sku,+ "attributes": [{"id": size_attribute_id, "values": ["Test-value"]}],+ },+ {+ "sku": sku,+ "attributes": [{"id": size_attribute_id, "values": ["Test-value2"]}],+ },+ ]++ variables = {+ "productId": product_id,+ "variants": variants,+ "errorPolicy": ErrorPolicyEnum.IGNORE_FAILED.name,+ }++ # 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_1_errors = data["results"][0]["errors"]+ input_2_errors = data["results"][1]["errors"]+ assert not data["results"][0]["productVariant"]+ assert len(input_2_errors) == 1+ assert len(input_1_errors) == 1+ assert input_1_errors[0]["field"] == "sku"+ assert input_1_errors[0]["code"] == ProductVariantBulkErrorCode.UNIQUE.name+ assert input_2_errors[0]["field"] == "sku"+ assert input_2_errors[0]["code"] == ProductVariantBulkErrorCode.UNIQUE.nameassert product_variant_count == ProductVariant.objects.count()def test_product_variant_bulk_create_without_sku(staff_api_client, product, size_attribute, permission_manage_products):+ # givenproduct_variant_count = ProductVariant.objects.count()attribute_value_count = size_attribute.values.count()size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)@@ -964,13 +1309,18 @@ def test_product_variant_bulk_create_without_sku(]variables = {"productId": product_id, "variants": variants}++ # whenstaff_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 not data["errors"]++ # then+ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]assert data["count"] == 2assert product_variant_count + 2 == ProductVariant.objects.count()assert attribute_value_count + 1 == size_attribute.values.count()@@ -980,6 +1330,7 @@ def test_product_variant_bulk_create_without_sku(def test_product_variant_bulk_create_many_errors(staff_api_client, product, size_attribute, permission_manage_products):+ # givenproduct_variant_count = ProductVariant.objects.count()product_id = graphene.Node.to_global_id("Product", product.pk)size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)@@ -1008,35 +1359,176 @@ def test_product_variant_bulk_create_many_errors(]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_3_errors = data["results"][2]["errors"]+ input_4_errors = data["results"][3]["errors"]+ assert input_3_errors[0] == {+ "field": "sku",+ "code": ProductVariantBulkErrorCode.UNIQUE.name,+ "message": ANY,+ "warehouses": None,+ "channels": None,+ }+ assert input_4_errors[0] == {+ "field": "attributes",+ "code": ProductVariantBulkErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.name,+ "message": ANY,+ "warehouses": None,+ "channels": None,+ }+ assert product_variant_count == ProductVariant.objects.count()+++def test_product_variant_bulk_create_many_errors_with_ignore_failed(+ staff_api_client, product, size_attribute, warehouses, permission_manage_products+):+ # given+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ non_existent_attribute_pk = 0+ invalid_attribute_id = graphene.Node.to_global_id(+ "Attribute", non_existent_attribute_pk+ )+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouses[0].pk)++ sku = product.variants.first().sku+ variants = [+ {+ "sku": str(uuid4())[:12],+ "attributes": [{"id": size_attribute_id, "values": ["Test-value1"]}],+ "stocks": [+ {"quantity": 15, "warehouse": warehouse_id},+ {"quantity": 15, "warehouse": warehouse_id},+ ],+ },+ {+ "sku": str(uuid4())[:12],+ "attributes": [{"id": size_attribute_id, "values": ["Test-value4"]}],+ },+ {+ "sku": sku,+ "attributes": [{"id": size_attribute_id, "values": ["Test-value2"]}],+ },+ {+ "sku": str(uuid4())[:12],+ "attributes": [{"id": invalid_attribute_id, "values": ["Test-value3"]}],+ },+ ]++ variables = {+ "productId": product_id,+ "variants": variants,+ "errorPolicy": ErrorPolicyEnum.IGNORE_FAILED.name,+ }++ # whenstaff_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"]) == 2- errors = data["errors"]- expected_errors = [++ # then+ input_3_errors = data["results"][2]["errors"]+ input_4_errors = data["results"][3]["errors"]+ assert input_3_errors[0] == {+ "field": "sku",+ "code": ProductVariantBulkErrorCode.UNIQUE.name,+ "message": ANY,+ "warehouses": None,+ "channels": None,+ }+ assert input_4_errors[0] == {+ "field": "attributes",+ "code": ProductVariantBulkErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.name,+ "message": ANY,+ "warehouses": None,+ "channels": None,+ }+ assert product_variant_count + 2 == ProductVariant.objects.count()+++def test_product_variant_bulk_create_many_errors_with_reject_failed_rows(+ staff_api_client, product, size_attribute, warehouses, permission_manage_products+):+ # given+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ non_existent_attribute_pk = 0+ invalid_attribute_id = graphene.Node.to_global_id(+ "Attribute", non_existent_attribute_pk+ )+ sku = product.variants.first().sku+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouses[0].pk)++ variants = [{- "field": "sku",- "index": 2,- "code": ProductErrorCode.UNIQUE.name,- "message": ANY,- "warehouses": None,- "channels": None,+ "sku": str(uuid4())[:12],+ "attributes": [{"id": size_attribute_id, "values": ["Test-value1"]}],+ "stocks": [+ {"quantity": 15, "warehouse": warehouse_id},+ {"quantity": 15, "warehouse": warehouse_id},+ ],},{- "field": "attributes",- "index": 3,- "code": ProductErrorCode.NOT_FOUND.name,- "message": ANY,- "warehouses": None,- "channels": None,+ "sku": str(uuid4())[:12],+ "attributes": [{"id": size_attribute_id, "values": ["Test-value4"]}],+ },+ {+ "sku": sku,+ "attributes": [{"id": size_attribute_id, "values": ["Test-value2"]}],+ },+ {+ "sku": str(uuid4())[:12],+ "attributes": [{"id": invalid_attribute_id, "values": ["Test-value3"]}],},]- for expected_error in expected_errors:- assert expected_error in errors- assert product_variant_count == ProductVariant.objects.count()++ variables = {+ "productId": product_id,+ "variants": variants,+ "errorPolicy": ErrorPolicyEnum.REJECT_FAILED_ROWS.name,+ }++ # 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_3_errors = data["results"][2]["errors"]+ input_4_errors = data["results"][3]["errors"]+ assert input_3_errors[0] == {+ "field": "sku",+ "code": ProductVariantBulkErrorCode.UNIQUE.name,+ "message": ANY,+ "warehouses": None,+ "channels": None,+ }++ assert input_4_errors[0] == {+ "field": "attributes",+ "code": ProductVariantBulkErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.name,+ "message": ANY,+ "warehouses": None,+ "channels": None,+ }+ assert product_variant_count + 1 == ProductVariant.objects.count()def test_product_variant_bulk_create_two_variants_duplicated_attribute_value(@@ -1046,6 +1538,7 @@ def test_product_variant_bulk_create_two_variants_duplicated_attribute_value(size_attribute,permission_manage_products,):+ # givenproduct = product_with_variant_with_two_attributesproduct_variant_count = ProductVariant.objects.count()product_id = graphene.Node.to_global_id("Product", product.pk)@@ -1061,17 +1554,21 @@ def test_product_variant_bulk_create_two_variants_duplicated_attribute_value(}]variables = {"productId": product_id, "variants": variants}++ # whenstaff_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]++ # then+ input_errors = data["results"][0]["errors"]+ assert len(input_errors) == 1+ error = input_errors[0]assert error["field"] == "attributes"- assert error["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name- assert error["index"] == 0+ assert error["code"] == ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.nameassert product_variant_count == ProductVariant.objects.count()@@ -1082,6 +1579,7 @@ def test_product_variant_bulk_create_two_variants_duplicated_attribute_value_in_color_attribute,size_attribute,):+ # givenproduct = product_with_variant_with_two_attributesproduct_id = graphene.Node.to_global_id("Product", product.pk)product_variant_count = ProductVariant.objects.count()@@ -1096,17 +1594,21 @@ def test_product_variant_bulk_create_two_variants_duplicated_attribute_value_in_{"sku": str(uuid4())[:12], "attributes": attributes},]variables = {"productId": product_id, "variants": variants}++ # whenstaff_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]++ # 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"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name- assert error["index"] == 1+ assert error["code"] == ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.nameassert product_variant_count == ProductVariant.objects.count()@@ -1117,6 +1619,7 @@ def test_product_variant_bulk_create_two_variants_duplicated_one_attribute_valuesize_attribute,permission_manage_products,):+ # givenproduct = product_with_variant_with_two_attributesproduct_variant_count = ProductVariant.objects.count()product_id = graphene.Node.to_global_id("Product", product.pk)@@ -1132,12 +1635,16 @@ def test_product_variant_bulk_create_two_variants_duplicated_one_attribute_value}]variables = {"productId": product_id, "variants": variants}++ # whenstaff_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 not data["errors"]++ # then+ assert not data["results"][0]["errors"]assert data["count"] == 1assert product_variant_count + 1 == ProductVariant.objects.count()diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.pynew file mode 100644index 0000000000..cf45cafc6c--- /dev/null+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py@@ -0,0 +1,345 @@+from unittest.mock import patch++import graphene++from .....product.error_codes import ProductVariantBulkErrorCode+from .....product.models import ProductChannelListing+from .....tests.utils import flush_post_commit_hooks+from ....tests.utils import get_graphql_content++PRODUCT_VARIANT_BULK_UPDATE_MUTATION = """+ mutation ProductVariantBulkUpdate(+ $variants: [ProductVariantBulkUpdateInput!]!,+ $productId: ID!,+ $errorPolicy: ErrorPolicyEnum+ ) {+ productVariantBulkUpdate(+ variants: $variants, product: $productId, errorPolicy: $errorPolicy+ ) {+ results{+ errors {+ field+ message+ code+ warehouses+ channels+ }+ productVariant{+ id+ name+ sku+ stocks {+ warehouse {+ slug+ }+ quantity+ }+ channelListings {+ channel {+ slug+ }+ price {+ currency+ amount+ }+ costPrice {+ currency+ amount+ }+ preorderThreshold {+ quantity+ }+ }+ preorder {+ globalThreshold+ endDate+ }+ }+ }+ count+ }+ }+"""+++@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+def test_product_variant_bulk_update(+ product_variant_created_webhook_mock,+ staff_api_client,+ product_with_single_variant,+ size_attribute,+ permission_manage_products,+):+ # given+ variant = product_with_single_variant.variants.last()+ product_id = graphene.Node.to_global_id("Product", product_with_single_variant.pk)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ old_name = variant.name+ new_name = "new-random-name"++ variants = [{"id": variant_id, "name": new_name}]++ 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_UPDATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantBulkUpdate"]++ # then+ assert not data["results"][0]["errors"]+ assert data["count"] == 1+ assert data["results"][0]["productVariant"]["name"] == new_name+ assert product_with_single_variant.variants.count() == 1+ assert old_name != new_name+ assert product_variant_created_webhook_mock.call_count == data["count"]+++def test_product_variant_bulk_update_stocks(+ staff_api_client,+ variant_with_many_stocks,+ warehouse,+ size_attribute,+ permission_manage_products,+):+ # given+ variant = variant_with_many_stocks+ product_id = graphene.Node.to_global_id("Product", variant.product_id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ stocks = variant.stocks.all()+ assert len(stocks) == 2+ stock_to_update = stocks[0]+ new_quantity = 999+ assert stock_to_update.quantity != new_quantity+ new_stock_quantity = 100++ variants = [+ {+ "id": variant_id,+ "stocks": [+ {+ "quantity": new_quantity,+ "warehouse": graphene.Node.to_global_id(+ "Warehouse", stock_to_update.warehouse.pk+ ),+ },+ {+ "quantity": new_stock_quantity,+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),+ },+ ],+ }+ ]++ 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_UPDATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantBulkUpdate"]++ # then+ stock_to_update.refresh_from_db()+ assert not data["results"][0]["errors"]+ assert data["count"] == 1+ assert stock_to_update.quantity == new_quantity+ assert variant.stocks.count() == 3+ assert variant.stocks.last().quantity == new_stock_quantity+++def test_product_variant_bulk_update_stocks_with_invalid_warehouse(+ staff_api_client,+ variant_with_many_stocks,+ warehouse,+ size_attribute,+ permission_manage_products,+):+ # given+ variant = variant_with_many_stocks+ product_id = graphene.Node.to_global_id("Product", variant.product_id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ stocks = variant.stocks.all()+ assert len(stocks) == 2+ stock_to_update = stocks[0]+ not_existing_warehouse_id = "aaa="++ variants = [+ {+ "id": variant_id,+ "stocks": [{"quantity": 10, "warehouse": not_existing_warehouse_id}],+ }+ ]++ 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_UPDATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantBulkUpdate"]+ stock_to_update.refresh_from_db()++ # then+ assert not data["results"][0]["productVariant"]+ assert data["results"][0]["errors"]+ assert data["count"] == 0+ error = data["results"][0]["errors"][0]+ assert error["field"] == "warehouses"+ assert error["code"] == ProductVariantBulkErrorCode.NOT_FOUND.name+ assert error["warehouses"] == [not_existing_warehouse_id]+++def test_product_variant_bulk_update_channel_listings_input(+ staff_api_client,+ variant,+ permission_manage_products,+ warehouses,+ size_attribute,+ channel_USD,+ channel_PLN,+):+ # given+ product = variant.product+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ ProductChannelListing.objects.create(product=product, channel=channel_PLN)+ existing_variant_listing = variant.channel_listings.last()++ assert variant.channel_listings.count() == 1+ product_id = graphene.Node.to_global_id("Product", product.pk)++ new_price_for_existing_variant_listing = 50.0+ not_existing_variant_listing_price = 20.0++ variants = [+ {+ "id": variant_id,+ "channelListings": [+ {+ "price": new_price_for_existing_variant_listing,+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),+ },+ {+ "price": not_existing_variant_listing_price,+ "channelId": graphene.Node.to_global_id("Channel", channel_PLN.pk),+ },+ ],+ },+ ]++ # when+ 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_UPDATE_MUTATION, variables+ )+ content = get_graphql_content(response, ignore_errors=True)+ data = content["data"]["productVariantBulkUpdate"]+ existing_variant_listing.refresh_from_db()++ # then+ assert not data["results"][0]["errors"]+ assert data["count"] == 1+ assert variant.channel_listings.count() == 2+ new_variant_channel_listing = variant.channel_listings.last()+ assert (+ new_variant_channel_listing.price_amount == not_existing_variant_listing_price+ )+ assert new_variant_channel_listing.channel == channel_PLN+ assert (+ existing_variant_listing.price_amount == new_price_for_existing_variant_listing+ )+++def test_product_variant_bulk_update_channel_listings_with_invalid_price(+ staff_api_client,+ variant,+ permission_manage_products,+ warehouses,+ size_attribute,+ channel_USD,+ channel_PLN,+):+ # given+ product = variant.product+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ ProductChannelListing.objects.create(product=product, channel=channel_PLN)+ existing_variant_listing = variant.channel_listings.last()++ assert variant.channel_listings.count() == 1+ product_id = graphene.Node.to_global_id("Product", product.pk)+ variants = [+ {+ "id": variant_id,+ "name": "RandomName",+ "channelListings": [+ {+ "price": 0.99999,+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),+ },+ ],+ },+ ]++ # when+ 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_UPDATE_MUTATION, variables+ )+ content = get_graphql_content(response, ignore_errors=True)+ data = content["data"]["productVariantBulkUpdate"]+ existing_variant_listing.refresh_from_db()++ # then+ assert data["results"][0]["errors"]+ assert data["count"] == 0+ assert not data["results"][0]["productVariant"]+ error = data["results"][0]["errors"][0]+ assert error["field"] == "price"+ assert error["code"] == ProductVariantBulkErrorCode.INVALID_PRICE.name+++def test_product_variant_bulk_update_with_already_existing_sku(+ staff_api_client,+ product_with_two_variants,+ size_attribute,+ permission_manage_products,+):+ # given+ variants = product_with_two_variants.variants.all()+ variant_1 = variants[0]+ variant_2 = variants[1]+ product_id = graphene.Node.to_global_id("Product", product_with_two_variants.pk)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant_1.pk)++ variants = [{"id": variant_id, "sku": variant_2.sku}]++ 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_UPDATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantBulkUpdate"]++ # then+ assert data["results"][0]["errors"]+ error = data["results"][0]["errors"][0]+ assert error["field"] == "sku"+ assert error["code"] == ProductVariantBulkErrorCode.UNIQUE.namediff --git a/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.pyindex fc503ebc1a..9df6ab9584 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py@@ -10,7 +10,7 @@ from .....tests.utils import flush_post_commit_hooksfrom .....warehouse.error_codes import StockErrorCodefrom .....warehouse.models import Stock, Warehousefrom ....tests.utils import get_graphql_content-from ...bulk_mutations.products import ProductVariantStocksUpdate+from ...bulk_mutations import ProductVariantStocksUpdatefrom ...utils import create_stocksVARIANT_STOCKS_UPDATE_MUTATIONS = """diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex a8e261d804..af31493e8d 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -12926,6 +12926,15 @@ type Mutation {Requires one of the following permissions: MANAGE_PRODUCTS."""productVariantBulkCreate(+ """+ Policies of error handling. DEFAULT: REJECT_EVERYTHING++ Added in Saleor 3.11.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ errorPolicy: ErrorPolicyEnum = reject_everything+"""ID of the product to create the variants for."""product: ID!@@ -12933,6 +12942,26 @@ type Mutation {variants: [ProductVariantBulkCreateInput!]!): ProductVariantBulkCreate+ """+ Update multiple product variants.++ Added in Saleor 3.11.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.++ Requires one of the following permissions: MANAGE_PRODUCTS.+ """+ productVariantBulkUpdate(+ """Policies of error handling. DEFAULT: REJECT_EVERYTHING"""+ errorPolicy: ErrorPolicyEnum = reject_everything++ """ID of the product to update the variants for."""+ product: ID!++ """Input list of product variants to update."""+ variants: [ProductVariantBulkUpdateInput!]!+ ): ProductVariantBulkUpdate+"""Deletes product variants.@@ -17206,6 +17235,7 @@ enum ProductErrorCode {DUPLICATED_INPUT_ITEMGRAPHQL_ERRORINVALID+ INVALID_PRICEPRODUCT_WITHOUT_CATEGORYNOT_PRODUCTS_IMAGENOT_PRODUCTS_VARIANT@@ -18517,12 +18547,68 @@ type ProductVariantBulkCreate {"""Returns how many objects were created."""count: Int!- """List of the created variants."""+ """List of the created variants.This field will be removed in Saleor 4.0."""productVariants: [ProductVariant!]!++ """+ List of the created variants.++ Added in Saleor 3.11.+ """+ results: [ProductVariantBulkResult!]!bulkProductErrors: [BulkProductError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")errors: [BulkProductError!]!}+type ProductVariantBulkResult {+ """Product variant data."""+ productVariant: ProductVariant++ """List of errors occurred on create attempt."""+ errors: [ProductVariantBulkError!]+}++type ProductVariantBulkError {+ """+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.+ """+ field: String++ """The error message."""+ message: String++ """The error code."""+ code: ProductVariantBulkErrorCode!++ """List of attributes IDs which causes the error."""+ attributes: [ID!]++ """List of attribute values IDs which causes the error."""+ values: [ID!]++ """List of warehouse IDs which causes the error."""+ warehouses: [ID!]++ """List of channel IDs which causes the error."""+ channels: [ID!]+}++"""An enumeration."""+enum ProductVariantBulkErrorCode {+ ATTRIBUTE_ALREADY_ASSIGNED+ ATTRIBUTE_CANNOT_BE_ASSIGNED+ ATTRIBUTE_VARIANTS_DISABLED+ DUPLICATED_INPUT_ITEM+ GRAPHQL_ERROR+ INVALID+ INVALID_PRICE+ NOT_PRODUCTS_VARIANT+ NOT_FOUND+ REQUIRED+ UNIQUE+ PRODUCT_NOT_ASSIGNED_TO_CHANNEL+}+type BulkProductError {"""Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.@@ -18551,6 +18637,19 @@ type BulkProductError {channels: [ID!]}+enum ErrorPolicyEnum {+ """+ Save what is possible within a single row. If there are errors in an input data row, try to save it partially and skip the invalid part.+ """+ IGNORE_FAILED++ """Reject all rows if there is at least one error in any of them."""+ REJECT_EVERYTHING++ """Reject rows with errors."""+ REJECT_FAILED_ROWS+}+input ProductVariantBulkCreateInput {"""List of attributes specific to this variant."""attributes: [BulkAttributeValueInput!]!@@ -18650,6 +18749,96 @@ input ProductVariantChannelListingAddInput {preorderThreshold: Int}+"""+Update multiple product variants.++Added in Saleor 3.11.++Note: this API is currently in Feature Preview and can be subject to changes at later point.++Requires one of the following permissions: MANAGE_PRODUCTS.+"""+type ProductVariantBulkUpdate {+ """Returns how many objects were updated."""+ count: Int!++ """List of the updated variants."""+ results: [ProductVariantBulkResult!]!+ errors: [ProductVariantBulkError!]!+}++"""+Input fields to update product variants.++Added in Saleor 3.11.+"""+input ProductVariantBulkUpdateInput {+ """List of attributes specific to this variant."""+ attributes: [BulkAttributeValueInput!]++ """Stock keeping unit."""+ sku: String++ """Variant name."""+ name: String++ """+ Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item.+ """+ trackInventory: Boolean++ """Weight of the Product Variant."""+ weight: WeightScalar++ """+ Determines if variant is in preorder.++ Added in Saleor 3.1.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ preorder: PreorderSettingsInput++ """+ Determines maximum quantity of `ProductVariant`,that can be bought in a single checkout.++ Added in Saleor 3.1.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ quantityLimitPerCustomer: Int++ """+ Fields required to update the product variant metadata.++ Added in Saleor 3.8.+ """+ metadata: [MetadataInput!]++ """+ Fields required to update the product variant private metadata.++ Added in Saleor 3.8.+ """+ privateMetadata: [MetadataInput!]++ """+ External ID of this product variant.++ Added in Saleor 3.10.+ """+ externalReference: String++ """Stocks of a product available for sale."""+ stocks: [StockInput!]++ """List of prices assigned to channels."""+ channelListings: [ProductVariantChannelListingAddInput!]++ """ID of the product variant to update."""+ id: ID!+}+"""Deletes product variants.diff --git a/saleor/graphql/tests/utils.py b/saleor/graphql/tests/utils.pyindex 7ca64ce4ba..60fa55486b 100644--- a/saleor/graphql/tests/utils.py+++ b/saleor/graphql/tests/utils.py@@ -43,7 +43,7 @@ def assert_graphql_error_with_message(response, message):def get_multipart_request_body(query, variables, file, file_name):"""Create request body for multipart GraphQL requests.- Multipart requests are different than standard GraphQL requests, because+ Multipart requests are different from standard GraphQL requests, becauseof additional 'operations' and 'map' keys."""return {@@ -53,3 +53,19 @@ def get_multipart_request_body(query, variables, file, file_name):"map": json.dumps({file_name: ["variables.file"]}, cls=DjangoJSONEncoder),file_name: file,}+++def get_multipart_request_body_with_multiple_files(query, variables, files, map_dict):+ """Create request body for multipart GraphQL requests to send multiple files.++ Multipart requests are different from standard GraphQL requests, because+ of additional 'operations' and 'map' keys.+ """++ return {+ "operations": json.dumps(+ {"query": query, "variables": variables}, cls=DjangoJSONEncoder+ ),+ "map": json.dumps(map_dict, cls=DjangoJSONEncoder),+ **{index: file for index, file in enumerate(files)},+ }diff --git a/saleor/product/error_codes.py b/saleor/product/error_codes.pyindex ce1098d9ae..f1914ffe04 100644--- a/saleor/product/error_codes.py+++ b/saleor/product/error_codes.py@@ -10,6 +10,7 @@ class ProductErrorCode(Enum):DUPLICATED_INPUT_ITEM = "duplicated_input_item"GRAPHQL_ERROR = "graphql_error"INVALID = "invalid"+ INVALID_PRICE = "invalid_price"PRODUCT_WITHOUT_CATEGORY = "product_without_category"NOT_PRODUCTS_IMAGE = "not_products_image"NOT_PRODUCTS_VARIANT = "not_products_variant"@@ -31,3 +32,18 @@ class CollectionErrorCode(Enum):REQUIRED = "required"UNIQUE = "unique"CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT = "cannot_manage_product_without_variant"+++class ProductVariantBulkErrorCode(Enum):+ ATTRIBUTE_ALREADY_ASSIGNED = "attribute_already_assigned"+ ATTRIBUTE_CANNOT_BE_ASSIGNED = "attribute_cannot_be_assigned"+ ATTRIBUTE_VARIANTS_DISABLED = "attribute_variants_disabled"+ DUPLICATED_INPUT_ITEM = "duplicated_input_item"+ GRAPHQL_ERROR = "graphql_error"+ INVALID = "invalid"+ INVALID_PRICE = "invalid_price"+ NOT_PRODUCTS_VARIANT = "not_products_variant"+ NOT_FOUND = "not_found"+ REQUIRED = "required"+ UNIQUE = "unique"+ PRODUCT_NOT_ASSIGNED_TO_CHANNEL = "product_not_assigned_to_channel"