Skip to content

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

Add ProductBulkCreate mutation (#12177)

SzymJ416b4dcad5c2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c493152a5a..8e7906110c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -114,6 +114,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Add new field `author` to `Manifest` and `App` object types - #12166 by @przlada
- Add backwards compatibility for `taxCode` field - #12325 by @maarcingebala
- Support resolving `Order` as an entity in Apollo Federation - #12328 by @binary-koan
+- [Preview] Add `ProductBulkCreate` mutation - #12177 by @SzymJ
- [Preview] Add `CustomerBulkUpdate` mutation - #12268 by @SzymJ
### Other changes
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index 1f47308645..bbed2c0324 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -175,6 +175,9 @@ PermissionGroupErrorCode = graphene.Enum.from_enum(
account_error_codes.PermissionGroupErrorCode
)
ProductErrorCode = graphene.Enum.from_enum(product_error_codes.ProductErrorCode)
+ProductBulkCreateErrorCode = graphene.Enum.from_enum(
+ product_error_codes.ProductBulkCreateErrorCode
+)
ProductVariantBulkErrorCode = graphene.Enum.from_enum(
product_error_codes.ProductVariantBulkErrorCode
)
diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.py
index 4e7d2e066f..221573adf8 100644
--- a/saleor/graphql/core/types/__init__.py
+++ b/saleor/graphql/core/types/__init__.py
@@ -40,6 +40,7 @@ from .common import (
PluginError,
PriceInput,
PriceRangeInput,
+ ProductBulkCreateError,
ProductChannelListingError,
ProductError,
ProductVariantBulkError,
@@ -126,6 +127,7 @@ __all__ = [
"PriceRangeInput",
"ProductChannelListingError",
"ProductError",
+ "ProductBulkCreateError",
"ProductWithoutVariantError",
"ProductVariantBulkError",
"ReducedRate",
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index f8c8c42dd0..ca3a1cc488 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -38,6 +38,7 @@ from ..enums import (
PermissionEnum,
PermissionGroupErrorCode,
PluginErrorCode,
+ ProductBulkCreateErrorCode,
ProductErrorCode,
ProductVariantBulkErrorCode,
ShippingErrorCode,
@@ -351,6 +352,30 @@ class BulkProductError(ProductError):
)
+class ProductBulkCreateError(BulkError):
+ code = ProductBulkCreateErrorCode(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 ProductVariantBulkError(Error):
code = ProductVariantBulkErrorCode(description="The error code.", required=True)
attributes = NonNullList(
diff --git a/saleor/graphql/product/bulk_mutations/__init__.py b/saleor/graphql/product/bulk_mutations/__init__.py
index 9154d00410..272054481b 100644
--- a/saleor/graphql/product/bulk_mutations/__init__.py
+++ b/saleor/graphql/product/bulk_mutations/__init__.py
@@ -1,5 +1,6 @@
from .category_bulk_delete import CategoryBulkDelete
from .collection_bulk_delete import CollectionBulkDelete
+from .product_bulk_create import ProductBulkCreate
from .product_bulk_delete import ProductBulkDelete
from .product_media_bulk_delete import ProductMediaBulkDelete
from .product_type_bulk_delete import ProductTypeBulkDelete
@@ -16,6 +17,7 @@ __all__ = [
"ProductBulkDelete",
"ProductMediaBulkDelete",
"ProductTypeBulkDelete",
+ "ProductBulkCreate",
"ProductVariantBulkCreate",
"ProductVariantBulkDelete",
"ProductVariantBulkUpdate",
diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
new file mode 100644
index 0000000000..c42cc658a8
--- /dev/null
+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
@@ -0,0 +1,865 @@
+from collections import defaultdict
+from datetime import datetime
+
+import graphene
+import pytz
+import requests
+from django.core.exceptions import ValidationError
+from django.core.files import File
+from django.db.models import F
+from django.utils.text import slugify
+from graphene.utils.str_converters import to_camel_case
+from text_unidecode import unidecode
+
+from ....core.tracing import traced_atomic_transaction
+from ....core.utils import prepare_unique_slug
+from ....core.utils.editorjs import clean_editor_js
+from ....core.utils.validators import get_oembed_data
+from ....permission.enums import ProductPermissions
+from ....product import ProductMediaTypes, models
+from ....product.error_codes import ProductBulkCreateErrorCode
+from ....warehouse.models import Warehouse
+from ...attribute.types import AttributeValueInput
+from ...attribute.utils import AttributeAssignmentMixin
+from ...channel import ChannelContext
+from ...core.descriptions import ADDED_IN_313, PREVIEW_FEATURE, RICH_CONTENT
+from ...core.doc_category import DOC_CATEGORY_PRODUCTS
+from ...core.enums import ErrorPolicyEnum
+from ...core.fields import JSONString
+from ...core.mutations import BaseMutation, ModelMutation
+from ...core.scalars import WeightScalar
+from ...core.types import (
+ BaseInputObjectType,
+ BaseObjectType,
+ MediaInput,
+ NonNullList,
+ ProductBulkCreateError,
+ SeoInput,
+)
+from ...core.utils import get_duplicated_values
+from ...core.validators import clean_seo_fields
+from ...core.validators.file import (
+ clean_image_file,
+ get_filename_from_url,
+ is_image_url,
+ validate_image_url,
+)
+from ...meta.mutations import MetadataInput
+from ...plugins.dataloaders import get_plugin_manager_promise
+from ..mutations.product.product_create import ProductCreateInput
+from ..types import Product
+from .product_variant_bulk_create import (
+ ProductVariantBulkCreate,
+ ProductVariantBulkCreateInput,
+)
+
+
+def get_results(instances_data_with_errors_list, reject_everything=False):
+ if reject_everything:
+ return [
+ ProductBulkResult(product=None, errors=data.get("errors"))
+ for data in instances_data_with_errors_list
+ ]
+ return [
+ ProductBulkResult(
+ product=ChannelContext(node=data.get("instance"), channel_slug=None),
+ errors=data.get("errors"),
+ )
+ if data.get("instance")
+ else ProductBulkResult(product=None, errors=data.get("errors"))
+ for data in instances_data_with_errors_list
+ ]
+
+
+class ProductChannelListingCreateInput(BaseInputObjectType):
+ channel_id = graphene.ID(required=True, description="ID of a channel.")
+ is_published = graphene.Boolean(
+ description="Determines if object is visible to customers."
+ )
+ published_at = graphene.types.datetime.DateTime(
+ description="Publication date time. ISO 8601 standard."
+ )
+ visible_in_listings = graphene.Boolean(
+ description=(
+ "Determines if product is visible in product listings "
+ "(doesn't apply to product collections)."
+ )
+ )
+ is_available_for_purchase = graphene.Boolean(
+ description="Determine if product should be available for purchase.",
+ )
+ available_for_purchase_at = graphene.DateTime(
+ description=(
+ "A start date time from which a product will be available "
+ "for purchase. When not set and `isAvailable` is set to True, "
+ "the current day is assumed."
+ )
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PRODUCTS
+
+
+class ProductBulkResult(BaseObjectType):
+ product = graphene.Field(Product, description="Product data.")
+ errors = NonNullList(
+ ProductBulkCreateError,
+ required=False,
+ description="List of errors occurred on create attempt.",
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PRODUCTS
+
+
+class ProductBulkCreateInput(ProductCreateInput):
+ attributes = NonNullList(AttributeValueInput, description="List of attributes.")
+ category = graphene.ID(description="ID of the product's category.", name="category")
+ collections = NonNullList(
+ graphene.ID,
+ description="List of IDs of collections that the product belongs to.",
+ name="collections",
+ )
+ description = JSONString(description="Product description." + RICH_CONTENT)
+ name = graphene.String(description="Product name.")
+ slug = graphene.String(description="Product slug.")
+ tax_class = graphene.ID(
+ description=(
+ "ID of a tax class to assign to this product. If not provided, product "
+ "will use the tax class which is assigned to the product type."
+ ),
+ required=False,
+ )
+ seo = SeoInput(description="Search engine optimization fields.")
+ weight = WeightScalar(description="Weight of the Product.", required=False)
+ rating = graphene.Float(description="Defines the product rating value.")
+ metadata = NonNullList(
+ MetadataInput,
+ description="Fields required to update the product metadata.",
+ required=False,
+ )
+ private_metadata = NonNullList(
+ MetadataInput,
+ description=("Fields required to update the product private metadata."),
+ required=False,
+ )
+ external_reference = graphene.String(
+ description="External ID of this product.", required=False
+ )
+ product_type = graphene.ID(
+ description="ID of the type that product belongs to.",
+ name="productType",
+ required=True,
+ )
+ media = NonNullList(
+ MediaInput,
+ description="List of media inputs associated with the product.",
+ required=False,
+ )
+ channel_listings = NonNullList(
+ ProductChannelListingCreateInput,
+ description="List of channels in which the product is available.",
+ required=False,
+ )
+ variants = NonNullList(
+ ProductVariantBulkCreateInput,
+ required=False,
+ description="Input list of product variants to create.",
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PRODUCTS
+
+
+class ProductBulkCreate(BaseMutation):
+ count = graphene.Int(
+ required=True,
+ description="Returns how many objects were created.",
+ )
+ results = NonNullList(
+ ProductBulkResult,
+ required=True,
+ default_value=[],
+ description="List of the created products.",
+ )
+
+ class Arguments:
+ products = NonNullList(
+ ProductBulkCreateInput,
+ required=True,
+ description="Input list of products to create.",
+ )
+ error_policy = ErrorPolicyEnum(
+ required=False,
+ default_value=ErrorPolicyEnum.REJECT_EVERYTHING.value,
+ description="Policies of error handling.",
+ )
+
+ class Meta:
+ description = "Creates products." + ADDED_IN_313 + PREVIEW_FEATURE
+ doc_category = DOC_CATEGORY_PRODUCTS
+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)
+ error_type_class = ProductBulkCreateError
+ support_meta_field = True
+ support_private_meta_field = True
+
+ @classmethod
+ def generate_unique_slug(cls, slugable_value, new_slugs):
+ slug = slugify(unidecode(slugable_value))
+
+ search_field = "slug__iregex"
+ pattern = rf"{slug}-\d+$|{slug}$"
+ lookup = {search_field: pattern}
+
+ slug_values = models.Product.objects.filter(**lookup).values_list(
+ "slug", flat=True
+ )
+ slug_values = list(slug_values) + new_slugs
+ unique_slug = prepare_unique_slug(slug, slug_values)
+ new_slugs.append(unique_slug)
+
+ return unique_slug
+
+ @classmethod
+ def clean_base_fields(
+ cls, cleaned_input, new_slugs, product_index, index_error_map
+ ):
+ base_fields_errors_count = 0
+
+ weight = cleaned_input.get("weight")
+ if weight and weight.value < 0:
+ index_error_map[product_index].append(
+ ProductBulkCreateError(
+ path="weight",
+ message="Product can't have negative weight.",
+ code=ProductBulkCreateErrorCode.INVALID.value,
+ )
+ )
+ base_fields_errors_count += 1
+
+ description = cleaned_input.get("description")
+ cleaned_input["description_plaintext"] = (
+ clean_editor_js(description, to_string=True) if description else ""
+ )
+
+ slug = cleaned_input.get("slug")
+ if not slug and "name" in cleaned_input:
+ slug = cls.generate_unique_slug(cleaned_input["name"], new_slugs)
+ cleaned_input["slug"] = slug
+
+ clean_seo_fields(cleaned_input)
+
+ return base_fields_errors_count
+
+ @classmethod
+ def add_indexes_to_errors(cls, index, error, index_error_map, path_prefix=None):
+ for key, value in error.error_dict.items():
+ for e in value:
+ code = (
+ ProductBulkCreateErrorCode.INVALID.value
+ if e.code == ProductBulkCreateErrorCode.GRAPHQL_ERROR.value
+ else e.code
+ )
+ if path_prefix:
+ path = to_camel_case(f"{path_prefix}.{key}")
+ else:
+ path = to_camel_case(key)
+ index_error_map[index].append(
+ ProductBulkCreateError(
+ path=path,
+ message=e.messages[0],
+ code=code,
+ )
+ )
+
+ @classmethod
+ def clean_attributes(cls, cleaned_input, product_index, index_error_map):
+ attributes_errors_count = 0
+
+ if attributes := cleaned_input.get("attributes"):
+ try:
+ attributes_qs = cleaned_input["product_type"].product_attributes.all()
+ attributes = AttributeAssignmentMixin.clean_input(
+ attributes, attributes_qs
+ )
+ cleaned_input["attributes"] = attributes
+ except ValidationError as exc:
+ if hasattr(exc, "error_dict"):
+ cls.add_indexes_to_errors(
+ product_index, exc, index_error_map, "attributes"
+ )
+ else:
+ index_error_map[product_index].append(
+ ProductBulkCreateError(
+ path="attributes",
+ message=exc.message,
+ code=exc.code,
+ )
+ )
+ attributes_errors_count += 1
+ return attributes_errors_count
+
+ @classmethod
+ def _clean_channel_listing(
+ cls, listings_data, channels_global_ids, product_index, index_error_map
+ ):
+ input_channel_ids = [
+ channel_listing["channel_id"] for channel_listing in listings_data
+ ]
+
+ wrong_channel_ids = {
+ channel_id
+ for channel_id in input_channel_ids
+ if channel_id not in channels_global_ids.keys()
+ }
+ if wrong_channel_ids:
+ index_error_map[product_index].append(
+ ProductBulkCreateError(
+ path="channelListings",
+ message="Not existing channel ID.",
+ code=ProductBulkCreateErrorCode.NOT_FOUND.value,
+ channels=wrong_channel_ids,
+ )
+ )
+
+ duplicates = get_duplicated_values(input_channel_ids)
+ if duplicates:
+ index_error_map[product_index].append(
+ ProductBulkCreateError(
+ path="channelListings",
+ message="Duplicated channel ID.",
+ code=ProductBulkCreateErrorCode.DUPLICATED_INPUT_ITEM.value,
+ channels=duplicates,
+ )
+ )
+ return duplicates, wrong_channel_ids
+
+ @staticmethod
+ def set_available_for_purchase_at(
+ is_available_for_purchase, available_for_purchase_at, channel_data
+ ):
+ if is_available_for_purchase is False:
+ channel_data["available_for_purchase_at"] = None
+ elif is_available_for_purchase is True and not available_for_purchase_at:
+ channel_data["available_for_purchase_at"] = datetime.now(pytz.UTC)
+ else:
+ channel_data["available_for_purchase_at"] = available_for_purchase_at
+
+ @staticmethod
+ def set_published_at(channel_data):
+ if channel_data.get("is_published") and not channel_data.get("published_at"):
+ channel_data["published_at"] = datetime.now(pytz.UTC)
+
+ @classmethod
+ def clean_product_channel_listings(
+ cls,
+ listings_data,
+ channel_global_id_to_instance_map,
+ product_index,
+ used_channels_map,
+ index_error_map,
+ ):
+ listings_to_create = []
+
+ duplicates, wrong_channel_ids = cls._clean_channel_listing(
+ listings_data,
+ channel_global_id_to_instance_map,
+ product_index,
+ index_error_map,
+ )
+
+ if not duplicates and not wrong_channel_ids:
+ invalid_available_for_purchase = []
+
+ for index, listing_data in enumerate(listings_data):
+ is_available_for_purchase = listing_data.pop(
+ "is_available_for_purchase", None
+ )
+ available_for_purchase_at = listing_data.get(
+ "available_for_purchase_at"
+ )
+
+ if is_available_for_purchase is False and available_for_purchase_at:
+ invalid_available_for_purchase.append(listing_data["channel_id"])
+
+ if invalid_available_for_purchase:
+ message = (
+ "Cannot set available for purchase at when"
+ " isAvailableForPurchase is false."
+ )
+ index_error_map[product_index].append(
+ ProductBulkCreateError(
+ path=f"channelListings.{index}",
+ message=message,
+ code=ProductBulkCreateErrorCode.NOT_FOUND.value,
+ channels=invalid_available_for_purchase,
+ )
+ )
+ continue
+
+ channel = channel_global_id_to_instance_map[listing_data["channel_id"]]
+ listing_data["channel"] = channel
+ listing_data["currency"] = channel.currency_code
+ cls.set_published_at(listing_data)
+
+ if is_available_for_purchase is not None:
+ cls.set_available_for_purchase_at(
+ is_available_for_purchase,
+ available_for_purchase_at,
+ listing_data,
+ )
+ used_channels_map[listing_data["channel_id"]] = channel
+ listings_to_create.append(listing_data)
+ return listings_to_create
+
+ @classmethod
+ def clean_media(cls, media_inputs, product_index, index_error_map):
+ media_to_create = []
+
+ for index, media_input in enumerate(media_inputs):
+ image = media_input.get("image")
+ media_url = media_input.get("media_url")
+
+ if not image and not media_url:
+ index_error_map[product_index].append(
+ ProductBulkCreateError(
+ path=f"media.{index}",
+ message="Image or external URL is required.",
+ code=ProductBulkCreateErrorCode.REQUIRED.value,
+ )
+ )
+ continue
+
+ if image and media_url:
+ index_error_map[product_index].append(
+ ProductBulkCreateError(
+ path=f"media.{index}",
+ message="Either image or external URL is required.",
+ code=ProductBulkCreateErrorCode.DUPLICATED_INPUT_ITEM.value,
+ )
+ )
+ continue
+ media_to_create.append(media_input)
+
+ return media_to_create
+
+ @classmethod
+ def clean_variants(
+ cls,
+ info,
+ variant_inputs,
+ product_channel_global_id_to_instance_map,
+ warehouse_global_id_to_instance_map,
+ duplicated_sku,
+ product_type,
+ product_index,
+ index_error_map,
+ ):
+ variants_to_create: list = []
+ variant_index_error_map: dict = defaultdict(list)
+
+ variant_attributes = product_type.variant_attributes.annotate(
+ variant_selection=F("attributevariant__variant_selection")
+ )
+
+ variant_attributes_ids = {
+ graphene.Node.to_global_id("Attribute", variant_attribute.id)
+ for variant_attribute in variant_attributes
+ }
+
+ for index, variant_data in enumerate(variant_inputs):
+ variant_data["product_type"] = product_type
+ cleaned_input = ProductVariantBulkCreate.clean_variant(
+ info,
+ variant_data,
+ product_channel_global_id_to_instance_map,
+ warehouse_global_id_to_instance_map,
+ variant_attributes,
+ [],
+ variant_attributes_ids,
+ duplicated_sku,
+ variant_index_error_map,
+ index,
+ None,
+ )
+ variants_to_create.append(cleaned_input)
+
+ for index, errors in variant_index_error_map.items():
+ for error in errors:
+ index_error_map[product_index].append(
+ ProductBulkCreateError(
+ path=f"variants.{index}.{error.field}"
+ if error.field
+ else f"variants.{index}",
+ message=error.message,
+ code=error.code,
+ attributes=error.attributes,
+ values=error.values,
+ warehouses=error.warehouses,
+ channels=error.channels,
+ )
+ )
+ return variants_to_create
+
+ @classmethod
+ def clean_product_input(
+ cls,
+ info,
+ data: dict,
+ channel_global_id_to_instance_map: dict,
+ warehouse_global_id_to_instance_map: dict,
+ duplicated_sku: set,
+ new_slugs: list,
+ product_index: int,
+ index_error_map: dict,
+ ):
+ used_channels_map: dict = {}
+ base_fields_errors_count = 0
+
+ try:
+ cleaned_input = ModelMutation.clean_input(
+ info, None, data, input_cls=ProductBulkCreateInput
+ )
+ except ValidationError as exc:
+ cls.add_indexes_to_errors(product_index, exc, index_error_map)
+ return None
+
+ base_fields_errors_count += cls.clean_base_fields(
+ cleaned_input,
+ new_slugs,
+ product_index,
+ index_error_map,
+ )
+
+ attributes_errors_count = cls.clean_attributes(
+ cleaned_input, product_index, index_error_map
+ )
+
+ if media_inputs := cleaned_input.get("media"):
+ cleaned_input["media"] = cls.clean_media(
+ media_inputs, product_index, index_error_map
+ )
+
+ if listings_inputs := cleaned_input.get("channel_listings"):
+ cleaned_input["channel_listings"] = cls.clean_product_channel_listings(
+ listings_inputs,
+ channel_global_id_to_instance_map,
+ product_index,
+ used_channels_map,
+ index_error_map,
+ )
+
+ if variant_inputs := cleaned_input.get("variants"):
+ cleaned_input["variants"] = cls.clean_variants(
+ info,
+ variant_inputs,
+ used_channels_map,
+ warehouse_global_id_to_instance_map,
+ duplicated_sku,
+ cleaned_input["product_type"],
+ product_index,
+ index_error_map,
+ )
+
+ if base_fields_errors_count > 0 or attributes_errors_count > 0:
+ return None
+
+ return cleaned_input if cleaned_input else None
+
+ @classmethod
+ def clean_products(cls, info, products_data, index_error_map):
+ cleaned_inputs_map: dict = {}
+ new_slugs: list = []
+
+ warehouse_global_id_to_instance_map = {
+ graphene.Node.to_global_id("Warehouse", warehouse.id): warehouse
+ for warehouse in Warehouse.objects.all()
+ }
+ channel_global_id_to_instance_map = {
+ graphene.Node.to_global_id("Channel", channel.id): channel
+ for channel in models.Channel.objects.all()
+ }
+
+ duplicated_sku = get_duplicated_values(
+ [
+ variant.sku
+ for product_data in products_data
+ if product_data.variants
+ for variant in product_data.variants
+ if variant.sku
+ ]
+ )
+
+ for product_index, product_data in enumerate(products_data):
+ cleaned_input = cls.clean_product_input(
+ info,
+ product_data,
+ channel_global_id_to_instance_map,
+ warehouse_global_id_to_instance_map,
+ duplicated_sku,
+ new_slugs,
+ product_index,
+ index_error_map,
+ )
+ cleaned_inputs_map[product_index] = cleaned_input
+ return cleaned_inputs_map
+
+ @classmethod
+ def create_products(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 = models.Product()
+ instance = cls.construct_instance(instance, cleaned_input)
+ cls.validate_and_update_metadata(
+ instance, metadata_list, private_metadata_list
+ )
+ cls.clean_instance(info, instance)
+ instance.search_index_dirty = True
+
+ instances_data_and_errors_list.append(
+ {
+ "instance": instance,
+ "errors": index_error_map[index],
+ "cleaned_input": cleaned_input,
+ }
+ )
+ # assign product instance to media data
+ if media := cleaned_input.get("media"):
+ for media_input in media:
+ media_input["product"] = instance
+
+ # assign product instance to variants data
+ if variants := cleaned_input.get("variants"):
+ variants = cls.create_variants(
+ info, instance, variants, index, index_error_map
+ )
+ cleaned_input["variants"] = variants
+
+ # assign product instance to channel listings data
+ if channel_listings := cleaned_input.get("channel_listings"):
+ for channel_listing in channel_listings:
+ channel_listing["product"] = instance
+
+ except ValidationError as exc:
+ for key, value in exc.error_dict.items():
+ for e in value:
+ index_error_map[index].append(
+ ProductBulkCreateError(
+ path=to_camel_case(key),
+ message=e.messages[0],
+ code=e.code,
+ )
+ )
+ instances_data_and_errors_list.append(
+ {"instance": None, "errors": index_error_map[index]}
+ )
+
+ return instances_data_and_errors_list
+
+ @classmethod
+ def create_variants(cls, info, product, variants_inputs, index, index_error_map):
+ variants_instances_data = []
+
+ for variant_index, variant_data in enumerate(variants_inputs):
+ if variant_data:
+ try:
+ metadata_list = variant_data.pop("metadata", None)
+ private_metadata_list = variant_data.pop("private_metadata", None)
+ variant = models.ProductVariant()
+ variant.product = product
+ variant = cls.construct_instance(variant, variant_data)
+ cls.validate_and_update_metadata(
+ variant, metadata_list, private_metadata_list
+ )
+ variant.full_clean(exclude=["product"])
+
+ # store variant related objects data to create related objects
+ # after variant instance will be created
+ variant_data = {
+ "instance": variant,
+ "cleaned_input": {
+ "attributes": variant_data.get("attributes"),
+ "channel_listings": variant_data.get("channel_listings"),
+ "stocks": variant_data.get("stocks"),
+ },
+ }
+ variants_instances_data.append(variant_data)
+ except ValidationError as exc:
+ cls.add_indexes_to_errors(index, exc, index_error_map)
+
+ return variants_instances_data
+
+ @classmethod
+ def save(cls, info, product_data_with_errors_list):
+ products_to_create: list = []
+ media_to_create: list = []
+ attributes_to_save: list = []
+ listings_to_create: list = []
+
+ variants: list = []
+ variants_input_data: list = []
+ updated_channels: set = set()
+
+ for product_data in product_data_with_errors_list:
+ product = product_data["instance"]
+
+ if not product:
+ continue
+
+ products_to_create.append(product)
+ cleaned_input = product_data["cleaned_input"]
+
+ if media_inputs := cleaned_input.get("media"):
+ cls.prepare_media(info, product, media_inputs, media_to_create)
+
+ if attributes := cleaned_input.get("attributes"):
+ attributes_to_save.append((product, attributes))
+
+ if listings_input := cleaned_input.get("channel_listings"):
+ cls.prepare_products_channel_listings(
+ product,
+ listings_input,
+ listings_to_create,
+ updated_channels,
+ )
+
+ if variants_data := cleaned_input.pop("variants", None):
+ variants_input_data.extend(variants_data)
+
+ models.Product.objects.bulk_create(products_to_create)
+ models.ProductMedia.objects.bulk_create(media_to_create)
+ models.ProductChannelListing.objects.bulk_create(listings_to_create)
+
+ for product, attributes in attributes_to_save:
+ AttributeAssignmentMixin.save(product, attributes)
+
+ if variants_input_data:
+ variants = cls.save_variants(variants_input_data)
+
+ return variants, updated_channels
+
+ @classmethod
+ def prepare_products_channel_listings(
+ cls, product, listings_input, listings_to_create, updated_channels
+ ):
+ listings_to_create += [
+ models.ProductChannelListing(
+ product=product,
+ channel=listing_data["channel"],
+ currency=listing_data["channel"].currency_code,
+ is_published=listing_data.get("is_published", False),
+ published_at=listing_data.get("published_at"),
+ visible_in_listings=listing_data.get("visible_in_listings", False),
+ available_for_purchase_at=listing_data.get("available_for_purchase_at"),
+ )
+ for listing_data in listings_input
+ ]
+ updated_channels.update(
+ {listing_data["channel"] for listing_data in listings_input}
+ )
+
+ @classmethod
+ def save_variants(cls, variants_input_data):
+ return ProductVariantBulkCreate.save_variants(variants_input_data, None)
+
+ @classmethod
+ def prepare_media(cls, info, product, media_inputs, media_to_create):
+ for media_input in media_inputs:
+ alt = media_input.get("alt", "")
+ media_url = media_input.get("media_url")
+ if img_data := media_input.get("image"):
+ media_input["image"] = info.context.FILES.get(img_data)
+ image_data = clean_image_file(
+ media_input, "image", ProductBulkCreateErrorCode
+ )
+ media_to_create.append(
+ models.ProductMedia(
+ image=image_data,
+ alt=alt,
+ product=product,
+ type=ProductMediaTypes.IMAGE,
+ )
+ )
+ if media_url:
+ if is_image_url(media_url):
+ validate_image_url(
+ media_url, "media_url", ProductBulkCreateErrorCode.INVALID.value
+ )
+ filename = get_filename_from_url(media_url)
+ image_data = requests.get(media_url, stream=True)
+ image_data = File(image_data.raw, filename)
+ media_to_create.append(
+ models.ProductMedia(
+ image=image_data,
+ alt=alt,
+ product=product,
+ type=ProductMediaTypes.IMAGE,
+ )
+ )
+ else:
+ oembed_data, media_type = get_oembed_data(media_url, "media_url")
+ media_to_create.append(
+ models.ProductMedia(
+ external_url=oembed_data["url"],
+ alt=oembed_data.get("title", alt),
+ product=product,
+ type=media_type,
+ oembed_data=oembed_data,
+ )
+ )
+
+ @classmethod
+ def post_save_actions(cls, info, products, variants, channels):
+ manager = get_plugin_manager_promise(info.context).get()
+ for product in products:
+ cls.call_event(manager.product_created, product)
+
+ for variant in variants:
+ cls.call_event(manager.product_variant_created, variant)
+
+ for channel in channels:
+ cls.call_event(manager.channel_updated, channel)
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, root, info, **data):
+ index_error_map: dict = defaultdict(list)
+ error_policy = data["error_policy"]
+
+ # clean and validate inputs
+ cleaned_inputs_map = cls.clean_products(info, data["products"], index_error_map)
+ instances_data_with_errors_list = cls.create_products(
+ info, cleaned_inputs_map, index_error_map
+ )
+
+ # check error policy
+ if any([True if error else False for error in index_error_map.values()]):
+ if error_policy == ErrorPolicyEnum.REJECT_EVERYTHING.value:
+ results = get_results(instances_data_with_errors_list, True)
+ return ProductBulkCreate(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
+
+ # save all objects
+ variants, updated_channels = cls.save(info, instances_data_with_errors_list)
+
+ # prepare and return data
+ results = get_results(instances_data_with_errors_list)
+ products = [result.product for result in results if result.product]
+
+ cls.post_save_actions(info, products, variants, updated_channels)
+
+ return ProductBulkCreate(count=len(products), results=results)
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
index abe1619d81..3ca1bda874 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
@@ -286,7 +286,10 @@ class ProductVariantBulkCreate(BaseMutation):
code = ProductVariantBulkErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.value
index_error_map[variant_index].append(
ProductVariantBulkError(
- field="attributes", message=message, code=code
+ field="attributes",
+ message=message,
+ code=code,
+ attributes=invalid_attributes,
)
)
if errors is not None:
@@ -335,6 +338,7 @@ class ProductVariantBulkCreate(BaseMutation):
field="attributes",
message=message,
code=ProductVariantBulkErrorCode.INVALID.value,
+ attributes=invalid_attributes,
)
)
if errors is not None:
@@ -834,7 +838,7 @@ class ProductVariantBulkCreate(BaseMutation):
variant, listings_input, listings_to_create
)
- if attributes := variant_data["cleaned_input"].get("attributes"):
+ if attributes := cleaned_input.get("attributes"):
attributes_to_save.append((variant, attributes))
if not variant.name:
@@ -848,10 +852,12 @@ class ProductVariantBulkCreate(BaseMutation):
warehouse_models.Stock.objects.bulk_create(stocks_to_create)
models.ProductVariantChannelListing.objects.bulk_create(listings_to_create)
- if not product.default_variant and variants_to_create:
+ if product and not product.default_variant and variants_to_create:
product.default_variant = variants_to_create[0]
product.save(update_fields=["default_variant", "updated_at"])
+ return variants_to_create
+
@classmethod
def prepare_stocks(cls, variant, stocks_input, stocks_to_create):
stocks_to_create += [
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 36cc645242..953346c8c8 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -33,6 +33,7 @@ from ..utils import get_user_or_app_from_context
from .bulk_mutations import (
CategoryBulkDelete,
CollectionBulkDelete,
+ ProductBulkCreate,
ProductBulkDelete,
ProductMediaBulkDelete,
ProductTypeBulkDelete,
@@ -556,6 +557,7 @@ class ProductMutations(graphene.ObjectType):
product_create = ProductCreate.Field()
product_delete = ProductDelete.Field()
+ product_bulk_create = ProductBulkCreate.Field()
product_bulk_delete = ProductBulkDelete.Field()
product_update = ProductUpdate.Field()
product_translate = ProductTranslate.Field()
diff --git a/saleor/graphql/product/tests/mutations/cassettes/test_product_bulk_create/test_product_bulk_create_with_media_with_media_url.yaml b/saleor/graphql/product/tests/mutations/cassettes/test_product_bulk_create/test_product_bulk_create_with_media_with_media_url.yaml
new file mode 100644
index 0000000000..12f29fb96e
--- /dev/null
+++ b/saleor/graphql/product/tests/mutations/cassettes/test_product_bulk_create/test_product_bulk_create_with_media_with_media_url.yaml
@@ -0,0 +1,102 @@
+interactions:
+- request:
+ body: null
+ headers:
+ Connection:
+ - close
+ Host:
+ - www.youtube.com
+ User-Agent:
+ - python-micawber
+ method: GET
+ uri: https://www.youtube.com/oembed?scheme=https&format=json&maxheight=1080&maxwidth=1920&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdQw4w9WgXcQ
+ response:
+ body:
+ string: '{"title":"Rick Astley - Never Gonna Give You Up (Official Music Video)","author_name":"Rick
+ Astley","author_url":"https://www.youtube.com/@RickAstleyYT","type":"video","height":1080,"width":1920,"version":"1.0","provider_name":"YouTube","provider_url":"https://www.youtube.com/","thumbnail_height":360,"thumbnail_width":480,"thumbnail_url":"https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg","html":"\u003ciframe
+ width=\u00221920\u0022 height=\u00221080\u0022 src=\u0022https://www.youtube.com/embed/dQw4w9WgXcQ?feature=oembed\u0022
+ frameborder=\u00220\u0022 allow=\u0022accelerometer; autoplay; clipboard-write;
+ encrypted-media; gyroscope; picture-in-picture\u0022 allowfullscreen title=\u0022Rick
+ Astley - Never Gonna Give You Up (Official Music Video)\u0022\u003e\u003c/iframe\u003e"}'
+ headers:
+ Accept-Ranges:
+ - none
+ Alt-Svc:
+ - h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443";
+ ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"
+ Cache-Control:
+ - private
+ Connection:
+ - close
+ Content-Type:
+ - application/json
+ Date:
+ - Wed, 30 Nov 2022 21:06:26 GMT
+ Server:
+ - scaffolding on HTTPServer2
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - X-Origin
+ - Referer
+ - Origin,Accept-Encoding
+ X-Content-Type-Options:
+ - nosniff
+ X-Frame-Options:
+ - SAMEORIGIN
+ X-XSS-Protection:
+ - '0'
+ status:
+ code: 200
+ message: OK
+- request:
+ body: null
+ headers:
+ Connection:
+ - close
+ Host:
+ - www.youtube.com
+ User-Agent:
+ - python-micawber
+ method: GET
+ uri: https://www.youtube.com/oembed?scheme=https&format=json&maxheight=1080&maxwidth=1920&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdQw4w9WgXcQ
+ response:
+ body:
+ string: '{"title":"Rick Astley - Never Gonna Give You Up (Official Music Video)","author_name":"Rick
+ Astley","author_url":"https://www.youtube.com/@RickAstleyYT","type":"video","height":1080,"width":1920,"version":"1.0","provider_name":"YouTube","provider_url":"https://www.youtube.com/","thumbnail_height":360,"thumbnail_width":480,"thumbnail_url":"https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg","html":"\u003ciframe
+ width=\u00221920\u0022 height=\u00221080\u0022 src=\u0022https://www.youtube.com/embed/dQw4w9WgXcQ?feature=oembed\u0022
+ frameborder=\u00220\u0022 allow=\u0022accelerometer; autoplay; clipboard-write;
+ encrypted-media; gyroscope; picture-in-picture\u0022 allowfullscreen title=\u0022Rick
+ Astley - Never Gonna Give You Up (Official Music Video)\u0022\u003e\u003c/iframe\u003e"}'
+ headers:
+ Accept-Ranges:
+ - none
+ Alt-Svc:
+ - h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443";
+ ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"
+ Cache-Control:
+ - private
+ Connection:
+ - close
+ Content-Type:
+ - application/json
+ Date:
+ - Wed, 30 Nov 2022 21:06:26 GMT
+ Server:
+ - scaffolding on HTTPServer2
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - X-Origin
+ - Referer
+ - Origin,Accept-Encoding
+ X-Content-Type-Options:
+ - nosniff
+ X-Frame-Options:
+ - SAMEORIGIN
+ X-XSS-Protection:
+ - '0'
+ status:
+ code: 200
+ message: OK
+version: 1
diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
new file mode 100644
index 0000000000..2fe0d4635e
--- /dev/null
+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
@@ -0,0 +1,1508 @@
+import datetime
+import json
+import os
+from unittest.mock import patch
+from uuid import uuid4
+
+import graphene
+import pytest
+import pytz
+
+from .....product.error_codes import ProductBulkCreateErrorCode
+from .....product.models import Product
+from .....product.tests.utils import create_image
+from ....tests.utils import (
+ get_graphql_content,
+ get_multipart_request_body_with_multiple_files,
+)
+
+PRODUCT_BULK_CREATE_MUTATION = """
+ mutation ProductBulkCreate(
+ $products: [ProductBulkCreateInput!]!
+ ) {
+ productBulkCreate(products: $products) {
+ results {
+ errors {
+ path
+ code
+ message
+ warehouses
+ channels
+ }
+ product{
+ id
+ name
+ slug
+ media{
+ url
+ alt
+ type
+ oembedData
+ }
+ category{
+ name
+ }
+ description
+ attributes{
+ attribute{
+ slug
+ }
+ values{
+ value
+ }
+ }
+ channelListings{
+ id
+ channel{
+ name
+ }
+ }
+ variants{
+ name
+ stocks{
+ warehouse{
+ slug
+ }
+ quantity
+ }
+ }
+ }
+ }
+ count
+ }
+ }
+"""
+
+
+def test_product_bulk_create_with_base_data(
+ staff_api_client,
+ product_type,
+ category,
+ description_json,
+ permission_manage_products,
+):
+ # given
+ description_json_string = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION,
+ {"products": products},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ products = Product.objects.all()
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert data["results"][0]["product"]["name"] == product_name_1
+ assert data["results"][0]["product"]["slug"] == "test-name-1"
+ assert data["results"][0]["product"]["description"] == description_json_string
+ assert data["results"][0]["product"]["category"]["name"] == category.name
+ assert data["results"][1]["product"]["name"] == product_name_2
+ assert data["results"][1]["product"]["description"] == description_json_string
+ assert data["results"][1]["product"]["category"]["name"] == category.name
+ assert len(products) == 2
+
+ for product in products:
+ assert product.description == description_json
+ assert product.category == category
+ assert product.product_type == product_type
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_created")
+def test_product_bulk_create_send_product_created_webhook(
+ created_webhook_mock,
+ staff_api_client,
+ product_type,
+ category,
+ description_json,
+ permission_manage_products,
+):
+ # given
+ description_json_string = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION,
+ {"products": products},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert created_webhook_mock.call_count == 2
+
+
+def test_product_bulk_create_with_same_name_and_no_slug(
+ staff_api_client,
+ product_type,
+ category,
+ description_json,
+ permission_manage_products,
+):
+ # given
+ description_json_string = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name = "test name"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION,
+ {"products": products},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert data["results"][0]["product"]["name"] == product_name
+ assert data["results"][0]["product"]["slug"] == "test-name"
+ assert data["results"][1]["product"]["name"] == product_name
+ assert data["results"][1]["product"]["slug"] == "test-name-2"
+
+
+def test_product_bulk_create_with_invalid_attributes(
+ staff_api_client,
+ product_type,
+ category,
+ description_json,
+ permission_manage_products,
+):
+ # given
+ description_json_string = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "attributes": [
+ {"id": "invalidID", "values": ["invalidValue"]},
+ ],
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION,
+ {"products": products},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ assert data["count"] == 0
+ assert data["results"][0]["errors"]
+ error = data["results"][0]["errors"][0]
+ assert error["path"] == "attributes"
+ assert error["message"] == "Couldn't resolve id: invalidID."
+
+
+def test_product_bulk_create_with_media(
+ staff_api_client,
+ product_type,
+ category,
+ description_json,
+ permission_manage_products,
+ media_root,
+):
+ # given
+ description_json_string = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ image_file_1, image_name_1 = create_image(image_name="prod1")
+ image_file_2, image_name_2 = create_image(image_name="prod2")
+ image_file_3, image_name_3 = create_image(image_name="prod3")
+
+ media_1 = {
+ "alt": "",
+ "image": image_name_1,
+ }
+
+ media_2 = {
+ "alt": "",
+ "image": image_name_2,
+ }
+
+ media_3 = {
+ "alt": "",
+ "image": image_name_3,
+ }
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "media": [media_1, media_2],
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "media": [media_3],
+ },
+ ]
+
+ files = [image_file_1, image_file_2, image_file_3]
+
+ map_dict = {
+ 0: ["variables.products.0.media.0.image"],
+ 1: ["variables.products.0.media.1.image"],
+ 2: ["variables.products.1.media.0.image"],
+ }
+
+ # when
+ body = get_multipart_request_body_with_multiple_files(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}, files, map_dict
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_multipart(body)
+
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+ products = Product.objects.all()
+
+ product_1_media = products[0].media.all()
+ product_2_media = products[1].media.all()
+
+ # then
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert len(product_1_media) == 2
+ assert len(product_2_media) == 1
+
+ assert data["results"][0]["product"]["media"][0]["type"] == "IMAGE"
+ assert data["results"][0]["product"]["media"][1]["type"] == "IMAGE"
+ assert data["results"][1]["product"]["media"][0]["type"] == "IMAGE"
+
+ assert product_1_media[0].image.file
+ img_1_name, format = os.path.splitext(image_file_1._name)
+ file_1_name = product_1_media[0].image.name
+ assert file_1_name != image_file_1._name
+ assert file_1_name.startswith(f"products/{img_1_name}")
+ assert file_1_name.endswith(format)
+
+ assert product_2_media[0].image.file
+ img_3_name, format = os.path.splitext(image_file_3._name)
+ file_3_name = product_2_media[0].image.name
+ assert file_3_name != image_file_3._name
+ assert file_3_name.startswith(f"products/{img_3_name}")
+ assert file_3_name.endswith(format)
+
+
+def test_product_bulk_create_with_media_with_media_url(
+ staff_api_client,
+ product_type,
+ category,
+ description_json,
+ permission_manage_products,
+ media_root,
+):
+ # given
+ description_json_string = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ alt = "Rick Astley - Never Gonna Give You Up (Official Music Video)"
+ url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
+
+ media_1 = {
+ "alt": "",
+ "mediaUrl": url,
+ }
+
+ media_2 = {
+ "alt": "",
+ "mediaUrl": url,
+ }
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "media": [media_1],
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "media": [media_2],
+ },
+ ]
+
+ # when
+ body = get_multipart_request_body_with_multiple_files(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}, [], {}
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_multipart(body)
+
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+ products = Product.objects.all()
+
+ product_1_media = products[0].media.all()
+ product_2_media = products[1].media.all()
+
+ # then
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert len(product_1_media) == 1
+ assert len(product_2_media) == 1
+ assert data["results"][0]["product"]["media"][0]["type"] == "VIDEO"
+ assert data["results"][0]["product"]["media"][0]["alt"] == alt
+ assert data["results"][0]["product"]["media"][0]["url"] == url
+ assert data["results"][1]["product"]["media"][0]["type"] == "VIDEO"
+ assert data["results"][1]["product"]["media"][0]["alt"] == alt
+ assert data["results"][1]["product"]["media"][0]["url"] == url
+
+ oembed_data = json.loads(data["results"][0]["product"]["media"][0]["oembedData"])
+ assert oembed_data["url"] == "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
+ assert oembed_data["type"] == "video"
+ assert oembed_data["html"] is not None
+ assert oembed_data["thumbnail_url"] == (
+ "https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg"
+ )
+
+
+def test_product_bulk_create_with_attributes(
+ staff_api_client,
+ product_type,
+ category,
+ size_attribute,
+ description_json,
+ permission_manage_products,
+ media_root,
+ channel_USD,
+):
+ # given
+ description_json = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ # Default attribute defined in product_type fixture
+ color_attr = product_type.product_attributes.get(name="Color")
+ color_value_name = color_attr.values.first().name
+ color_attr_id = graphene.Node.to_global_id("Attribute", color_attr.id)
+
+ # Add second attribute
+ product_type.product_attributes.add(size_attribute)
+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.id)
+ non_existent_attr_value = "The cake is a lie"
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "attributes": [
+ {"id": color_attr_id, "values": [color_value_name]},
+ {"id": size_attr_id, "values": [non_existent_attr_value]},
+ ],
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "attributes": [
+ {"id": color_attr_id, "values": [color_value_name]},
+ {"id": size_attr_id, "values": [non_existent_attr_value]},
+ ],
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ products = Product.objects.all()
+
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert (
+ data["results"][0]["product"]["attributes"][0]["attribute"]["slug"]
+ == color_attr.slug
+ )
+ assert (
+ data["results"][1]["product"]["attributes"][0]["attribute"]["slug"]
+ == color_attr.slug
+ )
+
+ for product in products:
+ first_attribute_assignment = product.attributes.first()
+ assert product.attributes.count() == 2
+ assert first_attribute_assignment.attribute == color_attr
+ assert first_attribute_assignment.values.count() == 1
+
+
+def test_product_bulk_create_with_meta_data(
+ staff_api_client,
+ product_type,
+ category,
+ size_attribute,
+ description_json,
+ permission_manage_products,
+):
+ # given
+
+ description_json = json.dumps(description_json)
+ metadata_key = "md key"
+ metadata_value = "md value"
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "metadata": [{"key": metadata_key, "value": metadata_value}],
+ "privateMetadata": [{"key": metadata_key, "value": metadata_value}],
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "metadata": [{"key": metadata_key, "value": metadata_value}],
+ "privateMetadata": [{"key": metadata_key, "value": metadata_value}],
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ products = Product.objects.all()
+
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert len(products) == 2
+
+ for product in products:
+ assert product.metadata == {metadata_key: metadata_value}
+ assert product.private_metadata == {metadata_key: metadata_value}
+
+
+def test_product_bulk_create_with_channel_listings(
+ staff_api_client,
+ product_type,
+ category,
+ description_json,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+
+ description_json = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ publication_at = datetime.datetime.now(pytz.utc)
+
+ channel_listings = [
+ {
+ "channelId": channel_id,
+ "isPublished": True,
+ "visibleInListings": True,
+ "isAvailableForPurchase": True,
+ "publishedAt": publication_at,
+ }
+ ]
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "channelListings": channel_listings,
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "channelListings": channel_listings,
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert (
+ data["results"][0]["product"]["channelListings"][0]["channel"]["name"]
+ == channel_USD.name
+ )
+ assert (
+ data["results"][1]["product"]["channelListings"][0]["channel"]["name"]
+ == channel_USD.name
+ )
+ assert Product.objects.count() == 2
+ assert channel_USD.product_listings.count() == 2
+
+
+def test_product_bulk_create_with_variants(
+ staff_api_client,
+ product_type,
+ category,
+ size_attribute,
+ description_json,
+ permission_manage_products,
+):
+ # given
+ description_json = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ product_type.product_attributes.add(size_attribute)
+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.id)
+ non_existent_attr_value = "The cake is a lie"
+
+ sku_1 = str(uuid4())[:12]
+ variant_1_name = "new-variant-1-name"
+
+ sku_2 = str(uuid4())[:12]
+ variant_2_name = "new-variant-2-name"
+
+ sku_3 = str(uuid4())[:12]
+ variant_3_name = "new-variant-3-name"
+
+ variants_prod_1 = [
+ {
+ "sku": sku_1,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_1_name,
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ },
+ {
+ "sku": sku_2,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_2_name,
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ },
+ ]
+
+ variants_prod_2 = [
+ {
+ "sku": sku_3,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_3_name,
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ }
+ ]
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "variants": variants_prod_1,
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "variants": variants_prod_2,
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ products = Product.objects.all()
+ product_1_variants = products[0].variants.all()
+ product_2_variants = products[1].variants.all()
+
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert data["results"][0]["product"]["variants"]
+ assert data["results"][1]["product"]["variants"]
+ assert len(products) == 2
+ assert len(product_1_variants) == 2
+ assert len(product_2_variants) == 1
+
+ for variant in product_1_variants:
+ assert variant.name in [variant_1_name, variant_2_name]
+ assert variant.sku in [sku_1, sku_2]
+ attribute_assignment = variant.attributes.first()
+ assert variant.attributes.count() == 1
+ assert attribute_assignment.attribute == size_attribute
+ assert attribute_assignment.values.count() == 1
+
+ for variant in product_2_variants:
+ assert variant.name == variant_3_name
+ assert variant.sku == sku_3
+ attribute_assignment = variant.attributes.first()
+ assert variant.attributes.count() == 1
+ assert attribute_assignment.attribute == size_attribute
+ assert attribute_assignment.values.count() == 1
+
+
+def test_product_bulk_create_with_variants_with_duplicated_sku(
+ staff_api_client,
+ product_type,
+ category,
+ size_attribute,
+ description_json,
+ permission_manage_products,
+):
+ # given
+ description_json = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ product_type.product_attributes.add(size_attribute)
+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.id)
+ non_existent_attr_value = "The cake is a lie"
+
+ sku = str(uuid4())[:12]
+ variant_1_name = "new-variant-1-name"
+ variant_2_name = "new-variant-2-name"
+
+ variants_prod_1 = [
+ {
+ "sku": sku,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_1_name,
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ }
+ ]
+ variants_prod_2 = [
+ {
+ "sku": sku,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_2_name,
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ }
+ ]
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "variants": variants_prod_1,
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "variants": variants_prod_2,
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ prod_1_errors = data["results"][0]["errors"]
+ prod_2_errors = data["results"][1]["errors"]
+ assert prod_1_errors
+ assert prod_2_errors
+ assert data["count"] == 0
+ assert prod_1_errors[0]["path"] == "variants.0.sku"
+ assert prod_2_errors[0]["path"] == "variants.0.sku"
+ assert prod_1_errors[0]["code"] == ProductBulkCreateErrorCode.UNIQUE.name
+ assert prod_2_errors[0]["code"] == ProductBulkCreateErrorCode.UNIQUE.name
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
+@patch("saleor.plugins.manager.PluginsManager.product_created")
+def test_product_bulk_create_with_variants_send_product_variant_created_event(
+ product_created_webhook_mock,
+ variant_created_webhook_mock,
+ staff_api_client,
+ product_type,
+ category,
+ size_attribute,
+ description_json,
+ permission_manage_products,
+):
+ # given
+ description_json = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ product_type.product_attributes.add(size_attribute)
+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.id)
+ non_existent_attr_value = "The cake is a lie"
+
+ sku_1 = str(uuid4())[:12]
+ variant_1_name = "new-variant-1-name"
+
+ sku_2 = str(uuid4())[:12]
+ variant_2_name = "new-variant-2-name"
+
+ sku_3 = str(uuid4())[:12]
+ variant_3_name = "new-variant-3-name"
+
+ variants_prod_1 = [
+ {
+ "sku": sku_1,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_1_name,
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ },
+ {
+ "sku": sku_2,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_2_name,
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ },
+ ]
+
+ variants_prod_2 = [
+ {
+ "sku": sku_3,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_3_name,
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ }
+ ]
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "variants": variants_prod_1,
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "variants": variants_prod_2,
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert product_created_webhook_mock.call_count == 2
+ assert variant_created_webhook_mock.call_count == 3
+
+
+def test_product_bulk_create_with_variants_and_stocks(
+ staff_api_client,
+ product_type,
+ size_attribute,
+ category,
+ description_json,
+ permission_manage_products,
+ warehouse,
+):
+ # given
+ description_json = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ product_type.product_attributes.add(size_attribute)
+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.id)
+ non_existent_attr_value = "The cake is a lie"
+
+ sku_1 = str(uuid4())[:12]
+ variant_1_name = "new-variant-1-name"
+
+ sku_2 = str(uuid4())[:12]
+ variant_2_name = "new-variant-2-name"
+
+ quantity = 20
+ stocks = [
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
+ "quantity": quantity,
+ }
+ ]
+
+ variants_prod_1 = [
+ {
+ "sku": sku_1,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_1_name,
+ "stocks": stocks,
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ }
+ ]
+
+ variants_prod_2 = [
+ {
+ "sku": sku_2,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_2_name,
+ "stocks": stocks,
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ }
+ ]
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "variants": variants_prod_1,
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "variants": variants_prod_2,
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ products = Product.objects.all()
+ product_1_variant = products[0].variants.last()
+ product_2_variant = products[1].variants.last()
+
+ variant_1_data = data["results"][0]["product"]["variants"][0]
+ variant_2_data = data["results"][1]["product"]["variants"][0]
+
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert variant_1_data["stocks"][0]["quantity"] == quantity
+ assert variant_1_data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
+ assert variant_2_data["stocks"][0]["quantity"] == quantity
+ assert variant_2_data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
+ assert len(products) == 2
+ assert product_1_variant.stocks.count() == 1
+ assert product_2_variant.stocks.count() == 1
+
+
+def test_product_bulk_create_with_variants_and_invalid_stock(
+ staff_api_client,
+ product_type,
+ size_attribute,
+ category,
+ description_json,
+ permission_manage_products,
+ warehouse,
+):
+ # given
+ description_json = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name = "test name 1"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ product_type.product_attributes.add(size_attribute)
+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.id)
+ non_existent_attr_value = "The cake is a lie"
+
+ sku_1 = str(uuid4())[:12]
+ variant_1_name = "new-variant-1-name"
+
+ sku_2 = str(uuid4())[:12]
+ variant_2_name = "new-variant-2-name"
+
+ quantity = 20
+ stocks = [
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
+ "quantity": quantity,
+ }
+ ]
+
+ variants_prod_1 = [
+ {
+ "sku": sku_1,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_1_name,
+ "stocks": stocks,
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ },
+ {
+ "sku": sku_2,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_2_name,
+ "stocks": [
+ {
+ "warehouse": "invalidId",
+ "quantity": quantity,
+ }
+ ],
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ },
+ ]
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "variants": variants_prod_1,
+ }
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ assert not data["results"][0]["product"]
+ errors = data["results"][0]["errors"]
+ assert errors
+ assert errors[0]["path"] == "variants.1.warehouses"
+ assert errors[0]["code"] == ProductBulkCreateErrorCode.NOT_FOUND.name
+ assert data["count"] == 0
+
+
+@patch("saleor.plugins.manager.PluginsManager.channel_updated")
+def test_product_bulk_create_with_variants_and_channel_listings(
+ channel_updated_webhook_mock,
+ staff_api_client,
+ product_type,
+ category,
+ size_attribute,
+ description_json,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ description_json = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ product_type.product_attributes.add(size_attribute)
+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.id)
+ non_existent_attr_value = "The cake is a lie"
+
+ sku_1 = str(uuid4())[:12]
+ variant_1_name = "new-variant-1-name"
+
+ sku_2 = str(uuid4())[:12]
+ variant_2_name = "new-variant-2-name"
+
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ publication_at = datetime.datetime.now(pytz.utc)
+
+ product_channel_listings = [
+ {
+ "channelId": channel_id,
+ "isPublished": True,
+ "visibleInListings": True,
+ "isAvailableForPurchase": True,
+ "publishedAt": publication_at,
+ }
+ ]
+
+ price = 10.0
+ cost_price = 11.0
+ variant_channel_listings = [
+ {
+ "price": price,
+ "costPrice": cost_price,
+ "channelId": channel_id,
+ }
+ ]
+
+ variants_prod_1 = [
+ {
+ "sku": sku_1,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_1_name,
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ "channelListings": variant_channel_listings,
+ },
+ ]
+
+ variants_prod_2 = [
+ {
+ "sku": sku_2,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_2_name,
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ "channelListings": variant_channel_listings,
+ }
+ ]
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "channelListings": product_channel_listings,
+ "variants": variants_prod_1,
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "channelListings": product_channel_listings,
+ "variants": variants_prod_2,
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ products = Product.objects.all()
+ product_1_variant = products[0].variants.last()
+ product_2_variant = products[1].variants.last()
+
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert data["results"][0]["product"]["variants"]
+ assert data["results"][1]["product"]["variants"]
+ assert len(products) == 2
+
+ assert product_1_variant.channel_listings.last().channel_id == channel_USD.id
+ assert product_2_variant.channel_listings.last().channel_id == channel_USD.id
+
+ # 2 product channel listing and 2 variant channel listing were created but
+ # all are using same channel so only one event should be sent
+ channel_updated_webhook_mock.assert_called_once_with(channel_USD)
+
+
+def test_product_bulk_create_with_variants_and_channel_listings_with_wrong_price(
+ staff_api_client,
+ product_type,
+ category,
+ size_attribute,
+ description_json,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ description_json = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ product_type.product_attributes.add(size_attribute)
+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.id)
+ non_existent_attr_value = "The cake is a lie"
+
+ sku_1 = str(uuid4())[:12]
+ variant_1_name = "new-variant-1-name"
+
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ publication_at = datetime.datetime.now(pytz.utc)
+
+ product_channel_listings = [
+ {
+ "channelId": channel_id,
+ "isPublished": True,
+ "visibleInListings": True,
+ "isAvailableForPurchase": True,
+ "publishedAt": publication_at,
+ }
+ ]
+
+ price = 10.000001
+ cost_price = 11.0000001
+
+ variant_channel_listings = [
+ {
+ "price": price,
+ "costPrice": cost_price,
+ "channelId": channel_id,
+ }
+ ]
+
+ variants_prod_1 = [
+ {
+ "sku": sku_1,
+ "weight": 2.5,
+ "trackInventory": True,
+ "name": variant_1_name,
+ "attributes": [{"id": size_attr_id, "values": [non_existent_attr_value]}],
+ "channelListings": variant_channel_listings,
+ },
+ ]
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "channelListings": product_channel_listings,
+ "variants": variants_prod_1,
+ }
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ assert data["count"] == 0
+ assert not data["results"][0]["product"]
+ errors = data["results"][0]["errors"]
+ assert len(errors) == 2
+ assert errors[0]["path"] == "variants.0.price"
+ assert errors[0]["code"] == ProductBulkCreateErrorCode.INVALID_PRICE.name
+ assert errors[0]["channels"] == [channel_id]
+ assert errors[1]["path"] == "variants.0.costPrice"
+ assert errors[1]["code"] == ProductBulkCreateErrorCode.INVALID_PRICE.name
+ assert errors[1]["channels"] == [channel_id]
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 9710848bfe..506a5869c7 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -13327,6 +13327,23 @@ type Mutation {
id: ID
): ProductDelete @doc(category: "Products")
+ """
+ Creates products.
+
+ Added in Saleor 3.13.
+
+ 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.
+ """
+ productBulkCreate(
+ """Policies of error handling."""
+ errorPolicy: ErrorPolicyEnum = reject_everything
+
+ """Input list of products to create."""
+ products: [ProductBulkCreateInput!]!
+ ): ProductBulkCreate @doc(category: "Products")
+
"""
Deletes products.
@@ -18792,29 +18809,76 @@ type ProductDelete @doc(category: "Products") {
}
"""
-Deletes products.
+Creates products.
+
+Added in Saleor 3.13.
+
+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 ProductBulkDelete @doc(category: "Products") {
- """Returns how many objects were affected."""
+type ProductBulkCreate @doc(category: "Products") {
+ """Returns how many objects were created."""
count: Int!
- productErrors: [ProductError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
- errors: [ProductError!]!
-}
-"""
-Updates an existing product.
+ """List of the created products."""
+ results: [ProductBulkResult!]!
+ errors: [ProductBulkCreateError!]!
+}
-Requires one of the following permissions: MANAGE_PRODUCTS.
-"""
-type ProductUpdate @doc(category: "Products") {
- productErrors: [ProductError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
- errors: [ProductError!]!
+type ProductBulkResult @doc(category: "Products") {
+ """Product data."""
product: Product
+
+ """List of errors occurred on create attempt."""
+ errors: [ProductBulkCreateError!]
}
-input ProductInput @doc(category: "Products") {
+type ProductBulkCreateError {
+ """
+ Path to field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.
+ """
+ path: String
+
+ """The error message."""
+ message: String
+
+ """The error code."""
+ code: ProductBulkCreateErrorCode!
+
+ """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 ProductBulkCreateErrorCode {
+ ATTRIBUTE_ALREADY_ASSIGNED
+ ATTRIBUTE_CANNOT_BE_ASSIGNED
+ ATTRIBUTE_VARIANTS_DISABLED
+ BLANK
+ MAX_LENGTH
+ DUPLICATED_INPUT_ITEM
+ GRAPHQL_ERROR
+ INVALID
+ INVALID_PRICE
+ PRODUCT_WITHOUT_CATEGORY
+ NOT_FOUND
+ REQUIRED
+ UNIQUE
+ PRODUCT_NOT_ASSIGNED_TO_CHANNEL
+ UNSUPPORTED_MEDIA_PROVIDER
+}
+
+input ProductBulkCreateInput @doc(category: "Products") {
"""List of attributes."""
attributes: [AttributeValueInput!]
@@ -18865,103 +18929,47 @@ input ProductInput @doc(category: "Products") {
"""Defines the product rating value."""
rating: Float
- """
- Fields required to update the product metadata.
-
- Added in Saleor 3.8.
- """
+ """Fields required to update the product metadata."""
metadata: [MetadataInput!]
- """
- Fields required to update the product private metadata.
-
- Added in Saleor 3.8.
- """
+ """Fields required to update the product private metadata."""
privateMetadata: [MetadataInput!]
- """
- External ID of this product.
-
- Added in Saleor 3.10.
- """
+ """External ID of this product."""
externalReference: String
-}
-"""
-Creates/updates translations for a product.
+ """ID of the type that product belongs to."""
+ productType: ID!
-Requires one of the following permissions: MANAGE_TRANSLATIONS.
-"""
-type ProductTranslate @doc(category: "Products") {
- translationErrors: [TranslationError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
- errors: [TranslationError!]!
- product: Product
-}
+ """List of media inputs associated with the product."""
+ media: [MediaInput!]
-"""
-Manage product's availability in channels.
+ """List of channels in which the product is available."""
+ channelListings: [ProductChannelListingCreateInput!]
-Requires one of the following permissions: MANAGE_PRODUCTS.
-"""
-type ProductChannelListingUpdate @doc(category: "Products") {
- """An updated product instance."""
- product: Product
- productChannelListingErrors: [ProductChannelListingError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
- errors: [ProductChannelListingError!]!
+ """Input list of product variants to create."""
+ variants: [ProductVariantBulkCreateInput!]
}
-type ProductChannelListingError {
- """
- 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: ProductErrorCode!
-
- """List of attributes IDs which causes the error."""
- attributes: [ID!]
-
- """List of attribute values IDs which causes the error."""
- values: [ID!]
-
- """List of channels IDs which causes the error."""
- channels: [ID!]
-
- """List of variants IDs which causes the error."""
- variants: [ID!]
-}
+input MediaInput {
+ """Alt text for a product media."""
+ alt: String
-input ProductChannelListingUpdateInput @doc(category: "Products") {
- """List of channels to which the product should be assigned or updated."""
- updateChannels: [ProductChannelListingAddInput!]
+ """Represents an image file in a multipart request."""
+ image: Upload
- """List of channels from which the product should be unassigned."""
- removeChannels: [ID!]
+ """Represents an URL to an external media."""
+ mediaUrl: String
}
-input ProductChannelListingAddInput @doc(category: "Products") {
+input ProductChannelListingCreateInput @doc(category: "Products") {
"""ID of a channel."""
channelId: ID!
"""Determines if object is visible to customers."""
isPublished: Boolean
- """
- Publication date. ISO 8601 standard.
-
- DEPRECATED: this field will be removed in Saleor 4.0. Use `publishedAt` field instead.
- """
- publicationDate: Date
-
- """
- Publication date time. ISO 8601 standard.
-
- Added in Saleor 3.3.
- """
+ """Publication date time. ISO 8601 standard."""
publishedAt: DateTime
"""
@@ -18972,76 +18980,455 @@ input ProductChannelListingAddInput @doc(category: "Products") {
"""Determine if product should be available for purchase."""
isAvailableForPurchase: Boolean
- """
- A start date from which a product will be available for purchase. When not set and isAvailable is set to True, the current day is assumed.
-
- DEPRECATED: this field will be removed in Saleor 4.0. Use `availableForPurchaseAt` field instead.
- """
- availableForPurchaseDate: Date
-
"""
A start date time from which a product will be available for purchase. When not set and `isAvailable` is set to True, the current day is assumed.
-
- Added in Saleor 3.3.
"""
availableForPurchaseAt: DateTime
-
- """List of variants to which the channel should be assigned."""
- addVariants: [ID!]
-
- """List of variants from which the channel should be unassigned."""
- removeVariants: [ID!]
}
-"""
-Create a media object (image or video URL) associated with product. For image, this mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec
-
-Requires one of the following permissions: MANAGE_PRODUCTS.
-"""
-type ProductMediaCreate @doc(category: "Products") {
- product: Product
- media: ProductMedia
- productErrors: [ProductError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
- errors: [ProductError!]!
-}
+input ProductVariantBulkCreateInput @doc(category: "Products") {
+ """List of attributes specific to this variant."""
+ attributes: [BulkAttributeValueInput!]!
-input ProductMediaCreateInput @doc(category: "Products") {
- """Alt text for a product media."""
- alt: String
+ """Stock keeping unit."""
+ sku: String
- """Represents an image file in a multipart request."""
- image: Upload
+ """Variant name."""
+ name: String
- """ID of an product."""
- product: ID!
+ """
+ Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item.
+ """
+ trackInventory: Boolean
- """Represents an URL to an external media."""
- mediaUrl: String
-}
+ """Weight of the Product Variant."""
+ weight: WeightScalar
-"""
-Reorder the variants of a product. Mutation updates updated_at on product and triggers PRODUCT_UPDATED webhook.
+ """
+ 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
-Requires one of the following permissions: MANAGE_PRODUCTS.
-"""
-type ProductVariantReorder @doc(category: "Products") {
- product: Product
- productErrors: [ProductError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
- errors: [ProductError!]!
-}
+ """
+ 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
-input ReorderInput {
- """The ID of the item to move."""
- id: ID!
+ """
+ Fields required to update the product variant metadata.
+
+ Added in Saleor 3.8.
+ """
+ metadata: [MetadataInput!]
"""
- The new relative sorting position of the item (from -inf to +inf). 1 moves the item one position forward, -1 moves the item one position backward, 0 leaves the item unchanged.
+ Fields required to update the product variant private metadata.
+
+ Added in Saleor 3.8.
"""
- sortOrder: Int
-}
+ privateMetadata: [MetadataInput!]
-"""
-Deletes a product media.
+ """
+ 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!]
+}
+
+input BulkAttributeValueInput @doc(category: "Products") {
+ """ID of the selected attribute."""
+ id: ID
+
+ """
+ The value or slug of an attribute to resolve. If the passed value is non-existent, it will be created.This field will be removed in Saleor 4.0.
+ """
+ values: [String!]
+
+ """
+ Attribute value ID.
+
+ Added in Saleor 3.12.
+ """
+ dropdown: AttributeValueSelectableTypeInput
+
+ """
+ Attribute value ID.
+
+ Added in Saleor 3.12.
+ """
+ swatch: AttributeValueSelectableTypeInput
+
+ """
+ List of attribute value IDs.
+
+ Added in Saleor 3.12.
+ """
+ multiselect: [AttributeValueSelectableTypeInput!]
+
+ """
+ Numeric value of an attribute.
+
+ Added in Saleor 3.12.
+ """
+ numeric: String
+
+ """
+ URL of the file attribute. Every time, a new value is created.
+
+ Added in Saleor 3.12.
+ """
+ file: String
+
+ """
+ File content type.
+
+ Added in Saleor 3.12.
+ """
+ contentType: String
+
+ """
+ List of entity IDs that will be used as references.
+
+ Added in Saleor 3.12.
+ """
+ references: [ID!]
+
+ """
+ Text content in JSON format.
+
+ Added in Saleor 3.12.
+ """
+ richText: JSONString
+
+ """
+ Plain text content.
+
+ Added in Saleor 3.12.
+ """
+ plainText: String
+
+ """
+ The boolean value of an attribute to resolve. If the passed value is non-existent, it will be created.
+ """
+ boolean: Boolean
+
+ """
+ Represents the date value of the attribute value.
+
+ Added in Saleor 3.12.
+ """
+ date: Date
+
+ """
+ Represents the date/time value of the attribute value.
+
+ Added in Saleor 3.12.
+ """
+ dateTime: DateTime
+}
+
+input PreorderSettingsInput @doc(category: "Products") {
+ """The global threshold for preorder variant."""
+ globalThreshold: Int
+
+ """The end date for preorder."""
+ endDate: DateTime
+}
+
+input StockInput @doc(category: "Products") {
+ """Warehouse in which stock is located."""
+ warehouse: ID!
+
+ """Quantity of items available for sell."""
+ quantity: Int!
+}
+
+input ProductVariantChannelListingAddInput @doc(category: "Products") {
+ """ID of a channel."""
+ channelId: ID!
+
+ """Price of the particular variant in channel."""
+ price: PositiveDecimal!
+
+ """Cost price of the variant in channel."""
+ costPrice: PositiveDecimal
+
+ """
+ The threshold for preorder variant in channel.
+
+ Added in Saleor 3.1.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ preorderThreshold: Int
+}
+
+"""
+Deletes products.
+
+Requires one of the following permissions: MANAGE_PRODUCTS.
+"""
+type ProductBulkDelete @doc(category: "Products") {
+ """Returns how many objects were affected."""
+ count: Int!
+ productErrors: [ProductError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
+ errors: [ProductError!]!
+}
+
+"""
+Updates an existing product.
+
+Requires one of the following permissions: MANAGE_PRODUCTS.
+"""
+type ProductUpdate @doc(category: "Products") {
+ productErrors: [ProductError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
+ errors: [ProductError!]!
+ product: Product
+}
+
+input ProductInput @doc(category: "Products") {
+ """List of attributes."""
+ attributes: [AttributeValueInput!]
+
+ """ID of the product's category."""
+ category: ID
+
+ """
+ Determine if taxes are being charged for the product.
+
+ DEPRECATED: this field will be removed in Saleor 4.0. Use `Channel.taxConfiguration` to configure whether tax collection is enabled.
+ """
+ chargeTaxes: Boolean
+
+ """List of IDs of collections that the product belongs to."""
+ collections: [ID!]
+
+ """
+ Product description.
+
+ Rich text format. For reference see https://editorjs.io/
+ """
+ description: JSONString
+
+ """Product name."""
+ name: String
+
+ """Product slug."""
+ slug: String
+
+ """
+ ID of a tax class to assign to this product. If not provided, product will use the tax class which is assigned to the product type.
+ """
+ taxClass: ID
+
+ """
+ Tax rate for enabled tax gateway.
+
+ DEPRECATED: this field will be removed in Saleor 4.0. Use tax classes to control the tax calculation for a product. If taxCode is provided, Saleor will try to find a tax class with given code (codes are stored in metadata) and assign it. If no tax class is found, it would be created and assigned.
+ """
+ taxCode: String
+
+ """Search engine optimization fields."""
+ seo: SeoInput
+
+ """Weight of the Product."""
+ weight: WeightScalar
+
+ """Defines the product rating value."""
+ rating: Float
+
+ """
+ Fields required to update the product metadata.
+
+ Added in Saleor 3.8.
+ """
+ metadata: [MetadataInput!]
+
+ """
+ Fields required to update the product private metadata.
+
+ Added in Saleor 3.8.
+ """
+ privateMetadata: [MetadataInput!]
+
+ """
+ External ID of this product.
+
+ Added in Saleor 3.10.
+ """
+ externalReference: String
+}
+
+"""
+Creates/updates translations for a product.
+
+Requires one of the following permissions: MANAGE_TRANSLATIONS.
+"""
+type ProductTranslate @doc(category: "Products") {
+ translationErrors: [TranslationError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
+ errors: [TranslationError!]!
+ product: Product
+}
+
+"""
+Manage product's availability in channels.
+
+Requires one of the following permissions: MANAGE_PRODUCTS.
+"""
+type ProductChannelListingUpdate @doc(category: "Products") {
+ """An updated product instance."""
+ product: Product
+ productChannelListingErrors: [ProductChannelListingError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
+ errors: [ProductChannelListingError!]!
+}
+
+type ProductChannelListingError {
+ """
+ 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: ProductErrorCode!
+
+ """List of attributes IDs which causes the error."""
+ attributes: [ID!]
+
+ """List of attribute values IDs which causes the error."""
+ values: [ID!]
+
+ """List of channels IDs which causes the error."""
+ channels: [ID!]
+
+ """List of variants IDs which causes the error."""
+ variants: [ID!]
+}
+
+input ProductChannelListingUpdateInput @doc(category: "Products") {
+ """List of channels to which the product should be assigned or updated."""
+ updateChannels: [ProductChannelListingAddInput!]
+
+ """List of channels from which the product should be unassigned."""
+ removeChannels: [ID!]
+}
+
+input ProductChannelListingAddInput @doc(category: "Products") {
+ """ID of a channel."""
+ channelId: ID!
+
+ """Determines if object is visible to customers."""
+ isPublished: Boolean
+
+ """
+ Publication date. ISO 8601 standard.
+
+ DEPRECATED: this field will be removed in Saleor 4.0. Use `publishedAt` field instead.
+ """
+ publicationDate: Date
+
+ """
+ Publication date time. ISO 8601 standard.
+
+ Added in Saleor 3.3.
+ """
+ publishedAt: DateTime
+
+ """
+ Determines if product is visible in product listings (doesn't apply to product collections).
+ """
+ visibleInListings: Boolean
+
+ """Determine if product should be available for purchase."""
+ isAvailableForPurchase: Boolean
+
+ """
+ A start date from which a product will be available for purchase. When not set and isAvailable is set to True, the current day is assumed.
+
+ DEPRECATED: this field will be removed in Saleor 4.0. Use `availableForPurchaseAt` field instead.
+ """
+ availableForPurchaseDate: Date
+
+ """
+ A start date time from which a product will be available for purchase. When not set and `isAvailable` is set to True, the current day is assumed.
+
+ Added in Saleor 3.3.
+ """
+ availableForPurchaseAt: DateTime
+
+ """List of variants to which the channel should be assigned."""
+ addVariants: [ID!]
+
+ """List of variants from which the channel should be unassigned."""
+ removeVariants: [ID!]
+}
+
+"""
+Create a media object (image or video URL) associated with product. For image, this mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec
+
+Requires one of the following permissions: MANAGE_PRODUCTS.
+"""
+type ProductMediaCreate @doc(category: "Products") {
+ product: Product
+ media: ProductMedia
+ productErrors: [ProductError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
+ errors: [ProductError!]!
+}
+
+input ProductMediaCreateInput @doc(category: "Products") {
+ """Alt text for a product media."""
+ alt: String
+
+ """Represents an image file in a multipart request."""
+ image: Upload
+
+ """ID of an product."""
+ product: ID!
+
+ """Represents an URL to an external media."""
+ mediaUrl: String
+}
+
+"""
+Reorder the variants of a product. Mutation updates updated_at on product and triggers PRODUCT_UPDATED webhook.
+
+Requires one of the following permissions: MANAGE_PRODUCTS.
+"""
+type ProductVariantReorder @doc(category: "Products") {
+ product: Product
+ productErrors: [ProductError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
+ errors: [ProductError!]!
+}
+
+input ReorderInput {
+ """The ID of the item to move."""
+ id: ID!
+
+ """
+ The new relative sorting position of the item (from -inf to +inf). 1 moves the item one position forward, -1 moves the item one position backward, 0 leaves the item unchanged.
+ """
+ sortOrder: Int
+}
+
+"""
+Deletes a product media.
Requires one of the following permissions: MANAGE_PRODUCTS.
"""
@@ -19400,22 +19787,6 @@ input ProductVariantCreateInput @doc(category: "Products") {
stocks: [StockInput!]
}
-input PreorderSettingsInput @doc(category: "Products") {
- """The global threshold for preorder variant."""
- globalThreshold: Int
-
- """The end date for preorder."""
- endDate: DateTime
-}
-
-input StockInput @doc(category: "Products") {
- """Warehouse in which stock is located."""
- warehouse: ID!
-
- """Quantity of items available for sell."""
- quantity: Int!
-}
-
"""
Deletes a product variant.
@@ -19540,182 +19911,6 @@ type BulkProductError {
channels: [ID!]
}
-input ProductVariantBulkCreateInput @doc(category: "Products") {
- """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!]
-}
-
-input BulkAttributeValueInput @doc(category: "Products") {
- """ID of the selected attribute."""
- id: ID
-
- """
- The value or slug of an attribute to resolve. If the passed value is non-existent, it will be created.This field will be removed in Saleor 4.0.
- """
- values: [String!]
-
- """
- Attribute value ID.
-
- Added in Saleor 3.12.
- """
- dropdown: AttributeValueSelectableTypeInput
-
- """
- Attribute value ID.
-
- Added in Saleor 3.12.
- """
- swatch: AttributeValueSelectableTypeInput
-
- """
- List of attribute value IDs.
-
- Added in Saleor 3.12.
- """
- multiselect: [AttributeValueSelectableTypeInput!]
-
- """
- Numeric value of an attribute.
-
- Added in Saleor 3.12.
- """
- numeric: String
-
- """
- URL of the file attribute. Every time, a new value is created.
-
- Added in Saleor 3.12.
- """
- file: String
-
- """
- File content type.
-
- Added in Saleor 3.12.
- """
- contentType: String
-
- """
- List of entity IDs that will be used as references.
-
- Added in Saleor 3.12.
- """
- references: [ID!]
-
- """
- Text content in JSON format.
-
- Added in Saleor 3.12.
- """
- richText: JSONString
-
- """
- Plain text content.
-
- Added in Saleor 3.12.
- """
- plainText: String
-
- """
- The boolean value of an attribute to resolve. If the passed value is non-existent, it will be created.
- """
- boolean: Boolean
-
- """
- Represents the date value of the attribute value.
-
- Added in Saleor 3.12.
- """
- date: Date
-
- """
- Represents the date/time value of the attribute value.
-
- Added in Saleor 3.12.
- """
- dateTime: DateTime
-}
-
-input ProductVariantChannelListingAddInput @doc(category: "Products") {
- """ID of a channel."""
- channelId: ID!
-
- """Price of the particular variant in channel."""
- price: PositiveDecimal!
-
- """Cost price of the variant in channel."""
- costPrice: PositiveDecimal
-
- """
- The threshold for preorder variant in channel.
-
- Added in Saleor 3.1.
-
- Note: this API is currently in Feature Preview and can be subject to changes at later point.
- """
- preorderThreshold: Int
-}
-
"""
Update multiple product variants.
diff --git a/saleor/product/error_codes.py b/saleor/product/error_codes.py
index f1914ffe04..d02a6f8b62 100644
--- a/saleor/product/error_codes.py
+++ b/saleor/product/error_codes.py
@@ -47,3 +47,21 @@ class ProductVariantBulkErrorCode(Enum):
REQUIRED = "required"
UNIQUE = "unique"
PRODUCT_NOT_ASSIGNED_TO_CHANNEL = "product_not_assigned_to_channel"
+
+
+class ProductBulkCreateErrorCode(Enum):
+ ATTRIBUTE_ALREADY_ASSIGNED = "attribute_already_assigned"
+ ATTRIBUTE_CANNOT_BE_ASSIGNED = "attribute_cannot_be_assigned"
+ ATTRIBUTE_VARIANTS_DISABLED = "attribute_variants_disabled"
+ BLANK = "blank"
+ MAX_LENGTH = "max_length"
+ DUPLICATED_INPUT_ITEM = "duplicated_input_item"
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
+ INVALID_PRICE = "invalid_price"
+ PRODUCT_WITHOUT_CATEGORY = "product_without_category"
+ NOT_FOUND = "not_found"
+ REQUIRED = "required"
+ UNIQUE = "unique"
+ PRODUCT_NOT_ASSIGNED_TO_CHANNEL = "product_not_assigned_to_channel"
+ UNSUPPORTED_MEDIA_PROVIDER = "unsupported_media_provider"