Skip to content

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

Add new inputs to ProductVariantBulkUpdate and allow to remove stocks and channel listings (#11904)

SzymJ7d9a566edeea
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6bcaa6ef17..b3e2c6fee5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,8 +5,38 @@ All notable, unreleased changes to this project will be documented in this file.
# 3.12.0 [Unreleased]
### Breaking changes
+- `stocks` and `channelListings` inputs for preview `ProductVariantBulkUpdate` mutation has been changed. Both inputs have been extended by:
+ - `create` input - list of items that should be created
+ - `update` input - list of items that should be updated
+ - `remove` input - list of objects ID's that should be removed
+
+ If your platform relies on this [Preview] feature, make sure you update your mutations stocks and channel listings inputs from:
+ ```
+ {
+ "stocks/channelListings": [
+ {
+ ...
+ }
+ ]
+ }
+ ```
+ to:
+ ```
+ {
+ "stocks/channelListings": {
+ "create": [
+ {
+ ...
+ }
+ ]
+ }
+ }
+ ```
+
+
### GraphQL API
+- Add possibility to remove `stocks` and `channel listings` in `ProductVariantBulkUpdate` mutation.
- Move `orderSettings` query to `Channel` type - #11417 by @kadewu:
- Mutation `Channel.channelCreate` and `Channel.channelUpdate` have new `orderSettings` input.
- Deprecate `Shop.orderSettings` query. Use `Channel.orderSettings` query instead.
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 2ac9eb3f68..c0f0a5831e 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -6,7 +6,12 @@ from django.core.files.storage import default_storage
from ....core.utils import build_absolute_uri
from ...account.enums import AddressTypeEnum
-from ..descriptions import ADDED_IN_36, DEPRECATED_IN_3X_FIELD, PREVIEW_FEATURE
+from ..descriptions import (
+ ADDED_IN_36,
+ ADDED_IN_312,
+ DEPRECATED_IN_3X_FIELD,
+ PREVIEW_FEATURE,
+)
from ..enums import (
AccountErrorCode,
AppErrorCode,
@@ -336,9 +341,19 @@ class ProductVariantBulkError(Error):
description="List of warehouse IDs which causes the error.",
required=False,
)
+ stocks = NonNullList(
+ graphene.ID,
+ description="List of stocks IDs which causes the error." + ADDED_IN_312,
+ required=False,
+ )
channels = NonNullList(
graphene.ID,
- description="List of channel IDs which causes the error.",
+ description="List of channel IDs which causes the error." + ADDED_IN_312,
+ required=False,
+ )
+ channel_listings = NonNullList(
+ graphene.ID,
+ description="List of channel listings IDs which causes the error.",
required=False,
)
diff --git a/saleor/graphql/core/validators/__init__.py b/saleor/graphql/core/validators/__init__.py
index 56bf0d7d55..b52d538ad8 100644
--- a/saleor/graphql/core/validators/__init__.py
+++ b/saleor/graphql/core/validators/__init__.py
@@ -40,7 +40,11 @@ def validate_one_of_args_is_in_query(*args):
raise GraphQLError(f"At least one of arguments is required: {required_args}.")
-def validate_price_precision(value: Optional["Decimal"], currency: str):
+def validate_price_precision(
+ value: Optional["Decimal"],
+ currency: str,
+ currency_fractions=None,
+):
"""Validate if price amount does not have too many decimal places.
Price amount can't have more decimal places than currency allow to.
@@ -50,7 +54,15 @@ def validate_price_precision(value: Optional["Decimal"], currency: str):
# check no needed when there is no value
if not value:
return
- currency_fraction = get_currency_fraction(currency)
+
+ if currency_fractions:
+ try:
+ currency_fraction = currency_fractions[currency][0]
+ except KeyError:
+ currency_fraction = currency_fractions["DEFAULT"][0]
+ else:
+ currency_fraction = get_currency_fraction(currency)
+
value = value.normalize()
if value.as_tuple().exponent < -currency_fraction:
raise ValidationError(
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 7ea269c97c..c7d746324d 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
@@ -2,19 +2,19 @@ from collections import defaultdict
from typing import cast
import graphene
+from babel.core import get_global
from django.core.exceptions import ValidationError
-from django.db import transaction
-from django.db.utils import IntegrityError
+from django.db.models import F
from graphene.types import InputObjectType
from graphene.utils.str_converters import to_camel_case
+from ....attribute import AttributeType
from ....core.tracing import traced_atomic_transaction
from ....permission.enums import ProductPermissions
from ....product import models
from ....product.error_codes import ProductVariantBulkErrorCode
from ....product.search import update_product_search_vector
from ....product.tasks import update_product_discounted_price_task
-from ....product.utils.variants import generate_and_set_variant_name
from ....warehouse import models as warehouse_models
from ...attribute.utils import AttributeAssignmentMixin
from ...channel import ChannelContext
@@ -38,6 +38,56 @@ from ..mutations.product_variant.product_variant_create import (
from ..types import ProductVariant
from ..utils import clean_variant_sku, get_used_variants_attribute_values
+CURRENCY_FRACTIONS = get_global("currency_fractions")
+
+
+def clean_price(
+ price,
+ field_name,
+ currency,
+ channel_id,
+ variant_index,
+ errors,
+ index_error_map,
+):
+ try:
+ validate_price_precision(price, currency, CURRENCY_FRACTIONS)
+ except ValidationError as error:
+ index_error_map[variant_index].append(
+ ProductVariantBulkError(
+ field=to_camel_case(field_name),
+ message=error.message,
+ code=ProductVariantBulkErrorCode.INVALID_PRICE.value,
+ channels=[channel_id],
+ )
+ )
+ if errors is not None:
+ error.code = ProductVariantBulkErrorCode.INVALID_PRICE.value
+ error.params = {
+ "channels": [channel_id],
+ "index": variant_index,
+ }
+ errors[field_name].append(error)
+
+
+def get_results(instances_data_with_errors_list, reject_everything=False):
+ if reject_everything:
+ return [
+ ProductVariantBulkResult(product_variant=None, errors=data.get("errors"))
+ for data in instances_data_with_errors_list
+ ]
+ return [
+ ProductVariantBulkResult(
+ product_variant=ChannelContext(
+ node=data.get("instance"), channel_slug=None
+ ),
+ errors=data.get("errors"),
+ )
+ if data.get("instance")
+ else ProductVariantBulkResult(product_variant=None, errors=data.get("errors"))
+ for data in instances_data_with_errors_list
+ ]
+
class ProductVariantBulkResult(graphene.ObjectType):
product_variant = graphene.Field(
@@ -141,6 +191,7 @@ class ProductVariantBulkCreate(BaseMutation):
cls,
cleaned_input,
product_type,
+ variant_attributes,
variant_attributes_ids,
used_attribute_values,
errors,
@@ -148,8 +199,8 @@ class ProductVariantBulkCreate(BaseMutation):
index_error_map,
):
attributes_errors_count = 0
- if attributes := cleaned_input.get("attributes"):
- attributes_ids = {attr["id"] for attr in attributes or []}
+ if attributes_input := cleaned_input.get("attributes"):
+ attributes_ids = {attr["id"] for attr in attributes_input or []}
invalid_attributes = attributes_ids - variant_attributes_ids
if len(invalid_attributes) > 0:
message = "Given attributes are not a variant attributes."
@@ -174,8 +225,8 @@ class ProductVariantBulkCreate(BaseMutation):
if product_type.has_variants:
try:
- cleaned_attributes = ProductVariantCreate.clean_attributes(
- attributes, product_type
+ cleaned_attributes = AttributeAssignmentMixin.clean_input(
+ attributes_input, variant_attributes
)
ProductVariantCreate.validate_duplicated_attribute_values(
cleaned_attributes, used_attribute_values, None
@@ -222,45 +273,44 @@ class ProductVariantBulkCreate(BaseMutation):
return attributes_errors_count
@classmethod
- def clean_price(
+ def clean_prices(
cls,
price,
- field_name,
- currency,
+ cost_price,
+ currency_code,
channel_id,
variant_index,
errors,
index_error_map,
):
- try:
- validate_price_precision(price, currency)
- except ValidationError as error:
- index_error_map[variant_index].append(
- ProductVariantBulkError(
- field=to_camel_case(field_name),
- message=error.message,
- code=ProductVariantBulkErrorCode.INVALID_PRICE.value,
- channels=[channel_id],
- )
- )
- if errors is not None:
- error.code = ProductVariantBulkErrorCode.INVALID_PRICE.value
- error.params = {
- "channels": [channel_id],
- "index": variant_index,
- }
- errors[field_name].append(error)
+ clean_price(
+ price,
+ "price",
+ currency_code,
+ channel_id,
+ variant_index,
+ errors,
+ index_error_map,
+ )
+ clean_price(
+ cost_price,
+ "cost_price",
+ currency_code,
+ channel_id,
+ variant_index,
+ errors,
+ index_error_map,
+ )
@classmethod
def clean_channel_listings(
cls,
- cleaned_input,
+ channel_listings,
product_channel_global_id_to_instance_map,
errors,
variant_index,
index_error_map,
):
- channel_listings = cleaned_input.get("channel_listings")
channel_ids = [
channel_listing["channel_id"] for channel_listing in channel_listings
]
@@ -330,18 +380,10 @@ class ProductVariantBulkCreate(BaseMutation):
currency_code = channel_listing["channel"].currency_code
errors_count_before_prices = len(index_error_map[variant_index])
- cls.clean_price(
+
+ cls.clean_prices(
price,
- "price",
- currency_code,
- channel_id,
- variant_index,
- errors,
- index_error_map,
- )
- cls.clean_price(
cost_price,
- "cost_price",
currency_code,
channel_id,
variant_index,
@@ -354,20 +396,19 @@ class ProductVariantBulkCreate(BaseMutation):
listings_to_create.append(channel_listing)
- cleaned_input["channel_listings"] = listings_to_create
+ return listings_to_create
@classmethod
def clean_stocks(
cls,
- cleaned_input,
+ stocks_data,
warehouse_global_id_to_instance_map,
errors,
variant_index,
index_error_map,
):
- stocks = cleaned_input.get("stocks")
stocks_to_create = []
- warehouse_ids = [stock["warehouse"] for stock in stocks]
+ warehouse_ids = [stock["warehouse"] for stock in stocks_data]
wrong_warehouse_ids = {
warehouse_id
@@ -410,7 +451,7 @@ class ProductVariantBulkCreate(BaseMutation):
params={"warehouses": duplicates, "index": variant_index},
)
- for stock_data in stocks:
+ for stock_data in stocks_data:
if (
stock_data["warehouse"] in duplicates
or stock_data["warehouse"] in wrong_warehouse_ids
@@ -422,7 +463,7 @@ class ProductVariantBulkCreate(BaseMutation):
]
stocks_to_create.append(stock_data)
- cleaned_input["stocks"] = stocks_to_create
+ return stocks_to_create
@classmethod
def add_indexes_to_errors(cls, index, error, error_dict, index_error_map):
@@ -442,16 +483,6 @@ class ProductVariantBulkCreate(BaseMutation):
)
error_dict[key].extend(value)
- @classmethod
- def save(cls, info, instance, cleaned_input):
- instance.save()
-
- attributes = cleaned_input.get("attributes")
- if attributes:
- AttributeAssignmentMixin.save(instance, attributes)
- if not instance.name:
- generate_and_set_variant_name(instance, cleaned_input.get("sku"))
-
@classmethod
def create_variants(
cls, info, cleaned_inputs_map, product, errors, index_error_map
@@ -547,16 +578,16 @@ class ProductVariantBulkCreate(BaseMutation):
variant_data,
product_channel_global_id_to_instance_map,
warehouse_global_id_to_instance_map,
+ variant_attributes,
used_attribute_values,
variant_attributes_ids,
duplicated_sku,
index_error_map,
index,
errors,
- input_class=ProductVariantBulkCreateInput,
):
cleaned_input = ModelMutation.clean_input(
- info, None, variant_data, input_cls=input_class
+ info, None, variant_data, input_cls=ProductVariantBulkCreateInput
)
sku = cleaned_input.get("sku")
@@ -578,6 +609,7 @@ class ProductVariantBulkCreate(BaseMutation):
attributes_errors_count = cls.clean_attributes(
cleaned_input,
variant_data["product_type"],
+ variant_attributes,
variant_attributes_ids,
used_attribute_values,
errors,
@@ -585,18 +617,18 @@ class ProductVariantBulkCreate(BaseMutation):
index_error_map,
)
- if cleaned_input.get("channel_listings"):
- cls.clean_channel_listings(
- cleaned_input,
+ if listings_data := cleaned_input.get("channel_listings"):
+ cleaned_input["channel_listings"] = cls.clean_channel_listings(
+ listings_data,
product_channel_global_id_to_instance_map,
errors,
index,
index_error_map,
)
- if cleaned_input.get("stocks"):
- cls.clean_stocks(
- cleaned_input,
+ if stocks_data := cleaned_input.get("stocks"):
+ cleaned_input["stocks"] = cls.clean_stocks(
+ stocks_data,
warehouse_global_id_to_instance_map,
errors,
index,
@@ -605,12 +637,14 @@ class ProductVariantBulkCreate(BaseMutation):
if base_fields_errors_count > 0 or attributes_errors_count > 0:
return None
- else:
- return cleaned_input if cleaned_input else None
+
+ return cleaned_input if cleaned_input else None
@classmethod
def clean_variants(cls, info, variants, product, errors, index_error_map):
cleaned_inputs_map = {}
+ product_type = product.product_type
+
warehouse_global_id_to_instance_map = {
graphene.Node.to_global_id("Warehouse", warehouse.id): warehouse
for warehouse in warehouse_models.Warehouse.objects.all()
@@ -621,21 +655,22 @@ class ProductVariantBulkCreate(BaseMutation):
"channel"
).filter(product=product.id)
}
- used_attribute_values = get_used_variants_attribute_values(product)
+
+ variant_attributes = product_type.variant_attributes.annotate(
+ variant_selection=F("attributevariant__variant_selection")
+ )
variant_attributes_ids = {
- graphene.Node.to_global_id("Attribute", attr_id)
- for attr_id in list(
- product.product_type.variant_attributes.all().values_list(
- "pk", flat=True
- )
- )
+ graphene.Node.to_global_id("Attribute", variant_attribute.id)
+ for variant_attribute in variant_attributes
}
+ used_attribute_values = get_used_variants_attribute_values(product)
+
duplicated_sku = get_duplicated_values(
[variant.sku for variant in variants if variant.sku]
)
for index, variant_data in enumerate(variants):
- variant_data["product_type"] = product.product_type
+ variant_data["product_type"] = product_type
variant_data["product"] = product
cleaned_input = cls.clean_variant(
@@ -643,6 +678,7 @@ class ProductVariantBulkCreate(BaseMutation):
variant_data,
product_channel_global_id_to_instance_map,
warehouse_global_id_to_instance_map,
+ variant_attributes,
used_attribute_values,
variant_attributes_ids,
duplicated_sku,
@@ -655,68 +691,104 @@ class ProductVariantBulkCreate(BaseMutation):
return cleaned_inputs_map
@classmethod
- def create_variant_channel_listings(cls, variant, cleaned_input):
- channel_listings_data = cleaned_input.get("channel_listings")
-
- if not channel_listings_data:
- return
-
- variant_channel_listings = []
- for channel_listing_data in channel_listings_data:
- channel = channel_listing_data["channel"]
- price = channel_listing_data["price"]
- cost_price = channel_listing_data.get("cost_price")
- preorder_quantity_threshold = channel_listing_data.get("preorder_threshold")
- variant_channel_listings.append(
- models.ProductVariantChannelListing(
- channel=channel,
- variant=variant,
- price_amount=price,
- cost_price_amount=cost_price,
- currency=channel.currency_code,
- preorder_quantity_threshold=preorder_quantity_threshold,
- )
+ def prepare_channel_listings(cls, variant, listings_input, listings_to_create):
+ listings_to_create += [
+ models.ProductVariantChannelListing(
+ channel=listing_data["channel"],
+ variant=variant,
+ price_amount=listing_data["price"],
+ cost_price_amount=listing_data.get("cost_price"),
+ currency=listing_data["channel"].currency_code,
+ preorder_quantity_threshold=listing_data.get("preorder_threshold"),
)
- models.ProductVariantChannelListing.objects.bulk_create(
- variant_channel_listings
- )
+ for listing_data in listings_input
+ ]
+
+ @classmethod
+ def set_variant_name(cls, variant, cleaned_input):
+ attributes_input = cleaned_input.get("attributes", [])
+ sku = cleaned_input.get("sku")
+ attributes_display: list = []
+
+ for attribute_data in attributes_input:
+ if (
+ attribute_data[0].type == AttributeType.PRODUCT_TYPE
+ and attribute_data[0].variant_selection
+ ):
+ attributes_display.append(
+ ", ".join([value for value in attribute_data[1].values])
+ )
+
+ name = " / ".join(sorted(attributes_display))
+ if not name:
+ name = sku or variant.get_global_id()
+
+ variant.name = name
@classmethod
@traced_atomic_transaction()
- def save_variants(cls, info, instances_data_with_errors_list, product):
- for instance_data in instances_data_with_errors_list:
- instance = instance_data["instance"]
- if instance:
- cleaned_input = instance_data.pop("cleaned_input")
- cls.save(info, instance_data["instance"], cleaned_input)
- cls.create_variant_stocks(instance, cleaned_input)
- cls.create_variant_channel_listings(instance, cleaned_input)
-
- if not product.default_variant:
- product.default_variant = instance
- product.save(update_fields=["default_variant", "updated_at"])
+ def save_variants(cls, variants_data_with_errors_list, product):
+ variants_to_create: list = []
+ stocks_to_create: list = []
+ listings_to_create: list = []
+ attributes_to_save: list = []
+
+ for variant_data in variants_data_with_errors_list:
+ variant = variant_data["instance"]
+
+ if not variant:
+ continue
+
+ variants_to_create.append(variant)
+ cleaned_input = variant_data["cleaned_input"]
+
+ if stocks_input := cleaned_input.get("stocks"):
+ cls.prepare_stocks(variant, stocks_input, stocks_to_create)
+
+ if listings_input := cleaned_input.get("channel_listings"):
+ cls.prepare_channel_listings(
+ variant, listings_input, listings_to_create
+ )
+
+ if attributes := variant_data["cleaned_input"].get("attributes"):
+ attributes_to_save.append((variant, attributes))
+
+ if not variant.name:
+ cls.set_variant_name(variant, cleaned_input)
+
+ models.ProductVariant.objects.bulk_create(variants_to_create)
+
+ for variant, attributes in attributes_to_save:
+ AttributeAssignmentMixin.save(variant, attributes)
+
+ 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:
+ product.default_variant = variants_to_create[0]
+ product.save(update_fields=["default_variant", "updated_at"])
@classmethod
- def create_variant_stocks(cls, variant, cleaned_input):
- stocks = cleaned_input.get("stocks")
-
- if not stocks:
- return
-
- try:
- warehouse_models.Stock.objects.bulk_create(
- [
- warehouse_models.Stock(
- product_variant=variant,
- warehouse=stock_data["warehouse"],
- quantity=stock_data["quantity"],
- )
- for stock_data in stocks
- ]
+ def prepare_stocks(cls, variant, stocks_input, stocks_to_create):
+ stocks_to_create += [
+ warehouse_models.Stock(
+ product_variant=variant,
+ warehouse=stock_data["warehouse"],
+ quantity=stock_data["quantity"],
)
- except IntegrityError:
- msg = "Stock for one of warehouses already exists for this product variant."
- raise ValidationError(msg)
+ for stock_data in stocks_input
+ ]
+
+ @classmethod
+ def post_save_actions(cls, info, instances, product):
+ manager = get_plugin_manager_promise(info.context).get()
+
+ # Recalculate the "discounted price" for the parent product
+ update_product_discounted_price_task.delay(product.pk)
+ update_product_search_vector(product)
+
+ for instance in instances:
+ cls.call_event(manager.product_variant_created, instance.node)
@classmethod
@traced_atomic_transaction()
@@ -738,12 +810,7 @@ class ProductVariantBulkCreate(BaseMutation):
if errors:
if error_policy == ErrorPolicyEnum.REJECT_EVERYTHING.value:
- results = [
- ProductVariantBulkResult(
- product_variant=None, errors=data.get("errors")
- )
- for data in instances_data_with_errors_list
- ]
+ results = get_results(instances_data_with_errors_list, True)
return ProductVariantBulkCreate(
count=0,
results=results,
@@ -757,38 +824,14 @@ class ProductVariantBulkCreate(BaseMutation):
if data["errors"] and data["instance"]:
data["instance"] = None
- cls.save_variants(info, instances_data_with_errors_list, product)
+ cls.save_variants(instances_data_with_errors_list, product)
+ # prepare and return data
+ results = get_results(instances_data_with_errors_list)
instances = [
- ChannelContext(node=instance_data["instance"], channel_slug=None)
- for instance_data in instances_data_with_errors_list
- if instance_data["instance"]
- ]
-
- # Recalculate the "discounted price" for the parent product
- update_product_discounted_price_task.delay(product.pk)
-
- update_product_search_vector(product)
- manager = get_plugin_manager_promise(info.context).get()
- transaction.on_commit(
- lambda: [
- manager.product_variant_created(instance.node) for instance in instances
- ]
- )
-
- results = [
- ProductVariantBulkResult(
- product_variant=ChannelContext(
- node=data.get("instance"), channel_slug=None
- ),
- errors=data.get("errors"),
- )
- if data.get("instance")
- else ProductVariantBulkResult(
- product_variant=None, errors=data.get("errors")
- )
- for data in instances_data_with_errors_list
+ result.product_variant for result in results if result.product_variant
]
+ cls.post_save_actions(info, instances, product)
return ProductVariantBulkCreate(
count=len(instances),
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
index 9ac1602da7..e46008254a 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
@@ -3,32 +3,82 @@ from typing import cast
import graphene
from django.core.exceptions import ValidationError
-from django.db import transaction
+from django.db.models import F
from graphene.utils.str_converters import to_camel_case
from ....core.tracing import traced_atomic_transaction
from ....permission.enums import ProductPermissions
from ....product import models
-from ....product.error_codes import ProductErrorCode
+from ....product.error_codes import ProductErrorCode, ProductVariantBulkErrorCode
from ....product.search import update_product_search_vector
from ....product.tasks import update_product_discounted_price_task
from ....warehouse import models as warehouse_models
-from ...channel import ChannelContext
-from ...core.descriptions import ADDED_IN_311, PREVIEW_FEATURE
+from ...attribute.utils import AttributeAssignmentMixin
+from ...core.descriptions import ADDED_IN_311, ADDED_IN_312, PREVIEW_FEATURE
from ...core.enums import ErrorPolicyEnum
-from ...core.mutations import BaseMutation
+from ...core.mutations import BaseMutation, ModelMutation
+from ...core.scalars import PositiveDecimal
from ...core.types import NonNullList, ProductVariantBulkError
from ...core.utils import get_duplicated_values
from ...plugins.dataloaders import get_plugin_manager_promise
-from ..utils import get_used_variants_attribute_values
+from ..mutations.channels import ProductVariantChannelListingAddInput
+from ..mutations.product.product_create import StockInput, StockUpdateInput
+from ..utils import clean_variant_sku, get_used_variants_attribute_values
from .product_variant_bulk_create import (
BulkAttributeValueInput,
ProductVariantBulkCreate,
ProductVariantBulkCreateInput,
ProductVariantBulkResult,
+ clean_price,
+ get_results,
)
+class ProductVariantStocksUpdateInput(graphene.InputObjectType):
+ create = NonNullList(
+ StockInput,
+ description="List of warehouses to create stocks.",
+ required=False,
+ )
+ update = NonNullList(
+ StockUpdateInput,
+ description="List of stocks to update.",
+ required=False,
+ )
+ remove = NonNullList(
+ graphene.ID,
+ description="List of stocks to remove.",
+ required=False,
+ )
+
+
+class ChannelListingUpdateInput(graphene.InputObjectType):
+ channel_listing = graphene.ID(required=True, description="ID of a channel listing.")
+ price = PositiveDecimal(description="Price of the particular variant in channel.")
+ cost_price = PositiveDecimal(description="Cost price of the variant in channel.")
+ preorder_threshold = graphene.Int(
+ description="The threshold for preorder variant in channel."
+ )
+
+
+class ProductVariantChannelListingUpdateInput(graphene.InputObjectType):
+ create = NonNullList(
+ ProductVariantChannelListingAddInput,
+ description="List of channels to create variant channel listings.",
+ required=False,
+ )
+ update = NonNullList(
+ ChannelListingUpdateInput,
+ description="List of channel listings to update.",
+ required=False,
+ )
+ remove = NonNullList(
+ graphene.ID,
+ description="List of channel listings to remove.",
+ required=False,
+ )
+
+
class ProductVariantBulkUpdateInput(ProductVariantBulkCreateInput):
id = graphene.ID(description="ID of the product variant to update.", required=True)
attributes = NonNullList(
@@ -36,6 +86,17 @@ class ProductVariantBulkUpdateInput(ProductVariantBulkCreateInput):
required=False,
description="List of attributes specific to this variant.",
)
+ stocks = graphene.Field(
+ ProductVariantStocksUpdateInput,
+ description="Stocks input." + ADDED_IN_312 + PREVIEW_FEATURE,
+ required=False,
+ )
+
+ channel_listings = graphene.Field(
+ ProductVariantChannelListingUpdateInput,
+ description="Channel listings input." + ADDED_IN_312 + PREVIEW_FEATURE,
+ required=False,
+ )
class Meta:
description = "Input fields to update product variants." + ADDED_IN_311
@@ -85,6 +146,239 @@ class ProductVariantBulkUpdate(BaseMutation):
def save(cls, info, instance, cleaned_input):
ProductVariantBulkCreate.save(info, instance, cleaned_input)
+ @classmethod
+ def validate_base_fields(
+ cls, cleaned_input, duplicated_sku, index_error_map, index
+ ):
+ return ProductVariantBulkCreate.validate_base_fields(
+ cleaned_input, duplicated_sku, None, index_error_map, index
+ )
+
+ @classmethod
+ def clean_prices(
+ cls,
+ price,
+ cost_price,
+ currency_code,
+ channel_id,
+ variant_index,
+ index_error_map,
+ ):
+ clean_price(
+ price,
+ "price",
+ currency_code,
+ channel_id,
+ variant_index,
+ None,
+ index_error_map,
+ )
+ clean_price(
+ cost_price,
+ "cost_price",
+ currency_code,
+ channel_id,
+ variant_index,
+ None,
+ index_error_map,
+ )
+
+ @classmethod
+ def clean_channel_listings(
+ cls,
+ cleaned_input,
+ product_channel_global_id_to_instance_map,
+ listings_global_id_to_instance_map,
+ variant_index,
+ index_error_map,
+ ):
+ wrong_listings_ids: list = []
+
+ if listings_data := cleaned_input["channel_listings"].get("create"):
+ cleaned_input["channel_listings"][
+ "create"
+ ] = ProductVariantBulkCreate.clean_channel_listings(
+ listings_data,
+ product_channel_global_id_to_instance_map,
+ None,
+ variant_index,
+ index_error_map,
+ )
+ if listings_data := cleaned_input["channel_listings"].get("update"):
+ listings_to_update = []
+ for listing_data in listings_data:
+ listing_id = listing_data["channel_listing"]
+
+ if listing_id not in listings_global_id_to_instance_map.keys():
+ wrong_listings_ids.append(listing_id)
+ continue
+
+ channel_listing = listings_global_id_to_instance_map[listing_id]
+ price = listing_data.get("price")
+ cost_price = listing_data.get("cost_price")
+ currency_code = channel_listing.currency
+ channel_id = channel_listing.channel_id
+ errors_count_before_prices = len(index_error_map[variant_index])
+
+ cls.clean_prices(
+ price,
+ cost_price,
+ currency_code,
+ channel_id,
+ variant_index,
+ index_error_map,
+ )
+
+ if len(index_error_map[variant_index]) > errors_count_before_prices:
+ continue
+
+ listing_data["channel_listings"] = channel_listing
+ listings_to_update.append(listing_data)
+ cleaned_input["channel_listings"]["update"] = listings_to_update
+
+ if listings_ids := cleaned_input["channel_listings"].get("remove"):
+ listings_to_remove = []
+ for listing_id in listings_ids:
+ if listing_id not in listings_global_id_to_instance_map.keys():
+ wrong_listings_ids.append(listing_id)
+ continue
+
+ listings_to_remove.append(graphene.Node.from_global_id(listing_id)[1])
+ cleaned_input["channel_listings"]["remove"] = listings_to_remove
+
+ if wrong_listings_ids:
+ index_error_map[variant_index].append(
+ ProductVariantBulkError(
+ field="channelListing",
+ message="Channel listing was not found.",
+ code=ProductVariantBulkErrorCode.NOT_FOUND.value,
+ channel_listings=[wrong_listings_ids],
+ )
+ )
+
+ @classmethod
+ def clean_stocks(
+ cls,
+ cleaned_input,
+ warehouse_global_id_to_instance_map,
+ stock_global_id_to_instance_map,
+ variant_index,
+ index_error_map,
+ ):
+ wrong_stocks_ids: list = []
+
+ if stocks_data := cleaned_input["stocks"].get("create"):
+ cleaned_input["stocks"]["create"] = ProductVariantBulkCreate.clean_stocks(
+ stocks_data,
+ warehouse_global_id_to_instance_map,
+ None,
+ variant_index,
+ index_error_map,
+ )
+
+ if stocks_data := cleaned_input["stocks"].get("update"):
+ stocks_to_update = []
+ for stock_data in stocks_data:
+ stock_id = stock_data["stock"]
+ if stock_id not in stock_global_id_to_instance_map.keys():
+ wrong_stocks_ids.append(stock_id)
+ continue
+
+ stock_data["stock"] = stock_global_id_to_instance_map[stock_id]
+ stock_data["stock"].quantity = stock_data["quantity"]
+ stocks_to_update.append(stock_data)
+
+ cleaned_input["stocks"]["update"] = stocks_to_update
+
+ if stocks_ids := cleaned_input["stocks"].get("remove"):
+ stocks_to_remove = []
+ for stock_id in stocks_ids:
+ if stock_id not in stock_global_id_to_instance_map.keys():
+ wrong_stocks_ids.append(stock_id)
+ continue
+ stocks_to_remove.append(graphene.Node.from_global_id(stock_id)[1])
+ cleaned_input["stocks"]["remove"] = stocks_to_remove
+
+ if wrong_stocks_ids:
+ index_error_map[variant_index].append(
+ ProductVariantBulkError(
+ field="stock",
+ message="Stock was not found.",
+ code=ProductVariantBulkErrorCode.NOT_FOUND.value,
+ stocks=[wrong_stocks_ids],
+ )
+ )
+
+ @classmethod
+ def clean_variant(
+ cls,
+ info,
+ variant_data,
+ product_channel_global_id_to_instance_map,
+ warehouse_global_id_to_instance_map,
+ stock_global_id_to_instance_map,
+ listings_global_id_to_instance_map,
+ variant_attributes,
+ used_attribute_values,
+ variant_attributes_ids,
+ duplicated_sku,
+ index_error_map,
+ index,
+ ):
+ cleaned_input = ModelMutation.clean_input(
+ info, None, variant_data, input_cls=ProductVariantBulkUpdateInput
+ )
+
+ sku = cleaned_input.get("sku")
+ if sku is not None:
+ cleaned_input["sku"] = clean_variant_sku(sku)
+
+ preorder_settings = cleaned_input.get("preorder")
+ if preorder_settings:
+ cleaned_input["is_preorder"] = True
+ cleaned_input["preorder_global_threshold"] = preorder_settings.get(
+ "global_threshold"
+ )
+ cleaned_input["preorder_end_date"] = preorder_settings.get("end_date")
+
+ base_fields_errors_count = cls.validate_base_fields(
+ cleaned_input, duplicated_sku, index_error_map, index
+ )
+
+ attributes_errors_count = ProductVariantBulkCreate.clean_attributes(
+ cleaned_input,
+ variant_data["product_type"],
+ variant_attributes,
+ variant_attributes_ids,
+ used_attribute_values,
+ None,
+ index,
+ index_error_map,
+ )
+
+ if cleaned_input.get("channel_listings"):
+ cls.clean_channel_listings(
+ cleaned_input,
+ product_channel_global_id_to_instance_map,
+ listings_global_id_to_instance_map,
+ index,
+ index_error_map,
+ )
+
+ if cleaned_input.get("stocks"):
+ cls.clean_stocks(
+ cleaned_input,
+ warehouse_global_id_to_instance_map,
+ stock_global_id_to_instance_map,
+ 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_variants(
cls,
@@ -95,10 +389,27 @@ class ProductVariantBulkUpdate(BaseMutation):
index_error_map,
):
cleaned_inputs_map = {}
+ product_type = product.product_type
+
+ # fetch existing data required to validate inputs
warehouse_global_id_to_instance_map = {
graphene.Node.to_global_id("Warehouse", warehouse.id): warehouse
for warehouse in warehouse_models.Warehouse.objects.all()
}
+ stock_global_id_to_instance_map = {
+ graphene.Node.to_global_id("Stock", stock.id): stock
+ for stock in warehouse_models.Stock.objects.filter(
+ product_variant__in=variants_global_id_to_instance_map.values()
+ )
+ }
+ listings_global_id_to_instance_map = {
+ graphene.Node.to_global_id(
+ "ProductVariantChannelListing", listing.id
+ ): listing
+ for listing in models.ProductVariantChannelListing.objects.filter(
+ variant__in=variants_global_id_to_instance_map.values()
+ )
+ }
product_channel_global_id_to_instance_map = {
graphene.Node.to_global_id("Channel", listing.channel_id): listing.channel
for listing in models.ProductChannelListing.objects.select_related(
@@ -106,21 +417,21 @@ class ProductVariantBulkUpdate(BaseMutation):
).filter(product=product.id)
}
used_attribute_values = get_used_variants_attribute_values(product)
+ variant_attributes = product_type.variant_attributes.annotate(
+ variant_selection=F("attributevariant__variant_selection")
+ )
variant_attributes_ids = {
- graphene.Node.to_global_id("Attribute", attr_id)
- for attr_id in list(
- product.product_type.variant_attributes.all().values_list(
- "pk", flat=True
- )
- )
+ graphene.Node.to_global_id("Attribute", variant_attribute.id)
+ for variant_attribute in variant_attributes
}
duplicated_sku = get_duplicated_values(
[variant.sku for variant in variants if variant.sku]
)
+ # clean variants inputs
for index, variant_data in enumerate(variants):
variant_id = variant_data["id"]
- variant_data["product_type"] = product.product_type
+ variant_data["product_type"] = product_type
variant_data["product"] = product
if variant_id not in variants_global_id_to_instance_map.keys():
@@ -132,18 +443,19 @@ class ProductVariantBulkUpdate(BaseMutation):
)
continue
- cleaned_input = ProductVariantBulkCreate.clean_variant(
+ cleaned_input = cls.clean_variant(
info,
variant_data,
product_channel_global_id_to_instance_map,
warehouse_global_id_to_instance_map,
+ stock_global_id_to_instance_map,
+ listings_global_id_to_instance_map,
+ variant_attributes,
used_attribute_values,
variant_attributes_ids,
duplicated_sku,
index_error_map,
index,
- errors=None,
- input_class=ProductVariantBulkUpdateInput,
)
cleaned_inputs_map[index] = cleaned_input
@@ -191,74 +503,129 @@ class ProductVariantBulkUpdate(BaseMutation):
return instances_data_and_errors_list
@classmethod
- @traced_atomic_transaction()
- def update_or_create_variant_stocks(cls, variant, cleaned_input, manager):
- stocks = []
- if stocks_data := cleaned_input.get("stocks"):
- for stock_data in stocks_data:
- stock, is_created = warehouse_models.Stock.objects.get_or_create(
- product_variant=variant, warehouse=stock_data["warehouse"]
+ def prepare_stocks(cls, variant, stocks_input, stocks_to_create, stocks_to_update):
+ if stocks_data := stocks_input.get("create"):
+ stocks_to_create += [
+ warehouse_models.Stock(
+ product_variant=variant,
+ warehouse=stock_data["warehouse"],
+ quantity=stock_data["quantity"],
)
+ for stock_data in stocks_data
+ ]
+ if stocks_data := stocks_input.get("update"):
+ stocks_to_update += [stock_data["stock"] for stock_data in stocks_data]
- if is_created or (stock.quantity <= 0 and stock_data["quantity"] > 0):
- transaction.on_commit(
- lambda: manager.product_variant_back_in_stock(stock)
- )
+ @classmethod
+ def prepare_channel_listings(
+ cls, variant, listings_input, listings_to_create, listings_to_update
+ ):
+ if listings_data := listings_input.get("create"):
+ listings_to_create += [
+ models.ProductVariantChannelListing(
+ channel=listing_data["channel"],
+ variant=variant,
+ price_amount=listing_data["price"],
+ cost_price_amount=listing_data.get("cost_price"),
+ currency=listing_data["channel"].currency_code,
+ preorder_quantity_threshold=listing_data.get("preorder_threshold"),
+ )
+ for listing_data in listings_data
+ ]
- if stock_data["quantity"] <= 0:
- transaction.on_commit(
- lambda: manager.product_variant_out_of_stock(stock)
- )
+ if listings_data := listings_input.get("update"):
+ for listing_data in listings_data:
+ listing = listing_data["channel_listings"]
+ if "preorder_threshold" in listing_data:
+ listing.preorder_quantity_threshold = listing_data[
+ "preorder_threshold"
+ ]
+ if "price" in listing_data:
+ listing.price_amount = listing_data["price"]
+ if "cost_price" in listing_data:
+ listing.cost_price_amount = listing_data["cost_price"]
+ listings_to_update.append(listing)
- stock.quantity = stock_data["quantity"]
- stocks.append(stock)
+ @classmethod
+ @traced_atomic_transaction()
+ def save_variants(cls, variants_data_with_errors_list):
+ variants_to_update: list = []
+ stocks_to_create: list = []
+ stocks_to_update: list = []
+ stocks_to_remove: list = []
+ listings_to_create: list = []
+ listings_to_update: list = []
+ listings_to_remove: list = []
+
+ # prepare instances
+ for variant_data in variants_data_with_errors_list:
+ variant = variant_data["instance"]
+
+ if not variant:
+ continue
- warehouse_models.Stock.objects.bulk_update(stocks, ["quantity"])
+ cleaned_input = variant_data.pop("cleaned_input")
+ variants_to_update.append(variant)
- @classmethod
- def update_or_create_variant_channel_listings(cls, variant, cleaned_input):
- channel_listings_data = cleaned_input.get("channel_listings")
- if not channel_listings_data:
- return
-
- for channel_listing_data in channel_listings_data:
- channel = channel_listing_data["channel"]
- price = channel_listing_data["price"]
- cost_price = channel_listing_data.get("cost_price")
- preorder_quantity_threshold = channel_listing_data.get("preorder_threshold")
-
- defaults = {
- "price_amount": price,
- "currency": channel.currency_code,
- }
-
- if "preorder_threshold" in channel_listing_data:
- defaults["preorder_quantity_threshold"] = preorder_quantity_threshold
-
- if "cost_price" in channel_listing_data:
- defaults["cost_price_amount"] = cost_price
-
- models.ProductVariantChannelListing.objects.update_or_create(
- variant=variant, channel=channel, defaults=defaults
- )
+ if stocks_input := cleaned_input.get("stocks"):
+ cls.prepare_stocks(
+ variant, stocks_input, stocks_to_create, stocks_to_update
+ )
+ if to_remove := stocks_input.get("remove"):
+ stocks_to_remove += to_remove
+
+ if listings_input := cleaned_input.get("channel_listings"):
+ cls.prepare_channel_listings(
+ variant, listings_input, listings_to_create, listings_to_update
+ )
+ if to_remove := listings_input.get("remove"):
+ listings_to_remove += to_remove
+
+ if attributes := cleaned_input.get("attributes"):
+ AttributeAssignmentMixin.save(variant, attributes)
+
+ # perform db queries
+ models.ProductVariant.objects.bulk_update(
+ variants_to_update,
+ [
+ "name",
+ "sku",
+ "track_inventory",
+ "weight",
+ "quantity_limit_per_customer",
+ "metadata",
+ "private_metadata",
+ "external_reference",
+ ],
+ )
+ warehouse_models.Stock.objects.bulk_create(stocks_to_create)
+ warehouse_models.Stock.objects.bulk_update(stocks_to_update, ["quantity"])
+ models.ProductVariantChannelListing.objects.bulk_create(listings_to_create)
+ models.ProductVariantChannelListing.objects.bulk_update(
+ listings_to_update,
+ fields=["price_amount", "cost_price_amount", "preorder_quantity_threshold"],
+ )
+ warehouse_models.Stock.objects.filter(id__in=stocks_to_remove).delete()
+ models.ProductVariantChannelListing.objects.filter(
+ id__in=listings_to_remove
+ ).delete()
@classmethod
- @traced_atomic_transaction()
- def save_variants(cls, info, manager, instances_data_with_errors_list):
- for instance_data in instances_data_with_errors_list:
- instance = instance_data["instance"]
- if instance:
- cleaned_input = instance_data.pop("cleaned_input")
- cls.save(info, instance, cleaned_input)
- cls.update_or_create_variant_stocks(instance, cleaned_input, manager)
- cls.update_or_create_variant_channel_listings(instance, cleaned_input)
+ def post_save_actions(cls, info, instances, product):
+ manager = get_plugin_manager_promise(info.context).get()
+
+ # Recalculate the "discounted price" for the parent product
+ update_product_discounted_price_task.delay(product.pk)
+ update_product_search_vector(product)
+
+ for instance in instances:
+ cls.call_event(manager.product_variant_updated, instance.node)
@classmethod
@traced_atomic_transaction()
def perform_mutation(cls, _root, info, **data):
index_error_map: dict = defaultdict(list)
error_policy = data["error_policy"]
-
product = cast(
models.Product,
cls.get_node_or_error(info, data["product_id"], only_type="Product"),
@@ -268,6 +635,7 @@ class ProductVariantBulkUpdate(BaseMutation):
for variant in product.variants.all()
}
+ # clean and validate inputs
cleaned_inputs_map = cls.clean_variants(
info,
data["variants"],
@@ -280,17 +648,10 @@ class ProductVariantBulkUpdate(BaseMutation):
info, cleaned_inputs_map, index_error_map
)
- has_errors = any(
- [True if error else False for error in index_error_map.values()]
- )
- if has_errors:
+ # 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 = [
- ProductVariantBulkResult(
- product_variant=None, errors=data.get("errors")
- )
- for data in instances_data_with_errors_list
- ]
+ results = get_results(instances_data_with_errors_list, True)
return ProductVariantBulkUpdate(count=0, results=results)
if error_policy == ErrorPolicyEnum.REJECT_FAILED_ROWS.value:
@@ -298,36 +659,14 @@ class ProductVariantBulkUpdate(BaseMutation):
if data["errors"] and data["instance"]:
data["instance"] = None
- manager = get_plugin_manager_promise(info.context).get()
- cls.save_variants(info, manager, instances_data_with_errors_list)
+ # save all objects
+ cls.save_variants(instances_data_with_errors_list)
+ # prepare and return data
+ results = get_results(instances_data_with_errors_list)
instances = [
- ChannelContext(node=instance_data["instance"], channel_slug=None)
- for instance_data in instances_data_with_errors_list
- if instance_data["instance"]
- ]
-
- # Recalculate the "discounted price" for the parent product
- update_product_discounted_price_task.delay(product.pk)
- update_product_search_vector(product)
- transaction.on_commit(
- lambda: [
- manager.product_variant_updated(instance.node) for instance in instances
- ]
- )
-
- results = [
- ProductVariantBulkResult(
- product_variant=ChannelContext(
- node=data.get("instance"), channel_slug=None
- ),
- errors=data.get("errors"),
- )
- if data.get("instance")
- else ProductVariantBulkResult(
- product_variant=None, errors=data.get("errors")
- )
- for data in instances_data_with_errors_list
+ result.product_variant for result in results if result.product_variant
]
+ cls.post_save_actions(info, instances, product)
return ProductVariantBulkCreate(count=len(instances), results=results)
diff --git a/saleor/graphql/product/mutations/product/product_create.py b/saleor/graphql/product/mutations/product/product_create.py
index 7e51ec8a61..0a29244c6d 100644
--- a/saleor/graphql/product/mutations/product/product_create.py
+++ b/saleor/graphql/product/mutations/product/product_create.py
@@ -90,6 +90,13 @@ class StockInput(graphene.InputObjectType):
)
+class StockUpdateInput(graphene.InputObjectType):
+ stock = graphene.ID(required=True, description="Stock.")
+ quantity = graphene.Int(
+ required=True, description="Quantity of items available for sell."
+ )
+
+
class ProductCreateInput(ProductInput):
product_type = graphene.ID(
description="ID of the type that product belongs to.",
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
index cf45cafc6c..ad78e60402 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
@@ -120,18 +120,24 @@ def test_product_variant_bulk_update_stocks(
variants = [
{
"id": variant_id,
- "stocks": [
- {
- "quantity": new_quantity,
- "warehouse": graphene.Node.to_global_id(
- "Warehouse", stock_to_update.warehouse.pk
- ),
- },
- {
- "quantity": new_stock_quantity,
- "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
- },
- ],
+ "stocks": {
+ "create": [
+ {
+ "quantity": new_stock_quantity,
+ "warehouse": graphene.Node.to_global_id(
+ "Warehouse", warehouse.pk
+ ),
+ },
+ ],
+ "update": [
+ {
+ "quantity": new_quantity,
+ "stock": graphene.Node.to_global_id(
+ "Stock", stock_to_update.pk
+ ),
+ },
+ ],
+ },
}
]
@@ -155,6 +161,87 @@ def test_product_variant_bulk_update_stocks(
assert variant.stocks.last().quantity == new_stock_quantity
+def test_product_variant_bulk_update_and_remove_stock(
+ staff_api_client,
+ variant_with_many_stocks,
+ warehouse,
+ size_attribute,
+ permission_manage_products,
+):
+ # given
+ variant = variant_with_many_stocks
+ product_id = graphene.Node.to_global_id("Product", variant.product_id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ stocks = variant.stocks.all()
+ assert len(stocks) == 2
+ stock_to_remove = stocks[0]
+
+ variants = [
+ {
+ "id": variant_id,
+ "stocks": {
+ "remove": [graphene.Node.to_global_id("Stock", stock_to_remove.pk)]
+ },
+ }
+ ]
+
+ variables = {"productId": product_id, "variants": variants}
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_UPDATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+ flush_post_commit_hooks()
+ data = content["data"]["productVariantBulkUpdate"]
+
+ # then
+ assert not data["results"][0]["errors"]
+ assert data["count"] == 1
+ assert variant.stocks.count() == 1
+
+
+def test_product_variant_bulk_update_and_remove_stock_when_stock_not_exists(
+ staff_api_client,
+ variant_with_many_stocks,
+ warehouse,
+ size_attribute,
+ permission_manage_products,
+):
+ # given
+ variant = variant_with_many_stocks
+ product_id = graphene.Node.to_global_id("Product", variant.product_id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ stocks = variant.stocks.all()
+ assert len(stocks) == 2
+
+ variants = [
+ {
+ "id": variant_id,
+ "stocks": {"remove": [graphene.Node.to_global_id("Stock", "randomID")]},
+ }
+ ]
+
+ variables = {"productId": product_id, "variants": variants}
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_UPDATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+ flush_post_commit_hooks()
+ data = content["data"]["productVariantBulkUpdate"]
+
+ # then
+ assert data["count"] == 0
+ assert data["results"][0]["errors"]
+ assert variant.stocks.count() == 2
+ error = data["results"][0]["errors"][0]
+ assert error["code"] == ProductVariantBulkErrorCode.NOT_FOUND.name
+
+
def test_product_variant_bulk_update_stocks_with_invalid_warehouse(
staff_api_client,
variant_with_many_stocks,
@@ -174,7 +261,9 @@ def test_product_variant_bulk_update_stocks_with_invalid_warehouse(
variants = [
{
"id": variant_id,
- "stocks": [{"quantity": 10, "warehouse": not_existing_warehouse_id}],
+ "stocks": {
+ "create": [{"quantity": 10, "warehouse": not_existing_warehouse_id}]
+ },
}
]
@@ -225,16 +314,24 @@ def test_product_variant_bulk_update_channel_listings_input(
variants = [
{
"id": variant_id,
- "channelListings": [
- {
- "price": new_price_for_existing_variant_listing,
- "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
- },
- {
- "price": not_existing_variant_listing_price,
- "channelId": graphene.Node.to_global_id("Channel", channel_PLN.pk),
- },
- ],
+ "channelListings": {
+ "update": [
+ {
+ "price": new_price_for_existing_variant_listing,
+ "channelListing": graphene.Node.to_global_id(
+ "ProductVariantChannelListing", existing_variant_listing.id
+ ),
+ }
+ ],
+ "create": [
+ {
+ "price": not_existing_variant_listing_price,
+ "channelId": graphene.Node.to_global_id(
+ "Channel", channel_PLN.pk
+ ),
+ }
+ ],
+ },
},
]
@@ -262,6 +359,53 @@ def test_product_variant_bulk_update_channel_listings_input(
)
+def test_product_variant_bulk_update_and_remove_channel_listings(
+ staff_api_client,
+ variant,
+ permission_manage_products,
+ warehouses,
+ size_attribute,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ product = variant.product
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ ProductChannelListing.objects.create(product=product, channel=channel_PLN)
+ existing_variant_listing = variant.channel_listings.last()
+
+ assert variant.channel_listings.count() == 1
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ variants = [
+ {
+ "id": variant_id,
+ "channelListings": {
+ "remove": [
+ graphene.Node.to_global_id(
+ "ProductVariantChannelListing", existing_variant_listing.id
+ )
+ ]
+ },
+ },
+ ]
+
+ # when
+ variables = {"productId": product_id, "variants": variants}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_UPDATE_MUTATION, variables
+ )
+ content = get_graphql_content(response, ignore_errors=True)
+ data = content["data"]["productVariantBulkUpdate"]
+
+ # then
+ assert not data["results"][0]["errors"]
+ assert data["count"] == 1
+ assert variant.channel_listings.count() == 0
+
+
def test_product_variant_bulk_update_channel_listings_with_invalid_price(
staff_api_client,
variant,
@@ -284,12 +428,16 @@ def test_product_variant_bulk_update_channel_listings_with_invalid_price(
{
"id": variant_id,
"name": "RandomName",
- "channelListings": [
- {
- "price": 0.99999,
- "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
- },
- ],
+ "channelListings": {
+ "update": [
+ {
+ "price": 0.99999,
+ "channelListing": graphene.Node.to_global_id(
+ "ProductVariantChannelListing", existing_variant_listing.pk
+ ),
+ },
+ ],
+ },
},
]
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 66f02cd1a3..d27e33ea45 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -18838,8 +18838,22 @@ type ProductVariantBulkError {
"""List of warehouse IDs which causes the error."""
warehouses: [ID!]
- """List of channel IDs which causes the error."""
+ """
+ List of stocks IDs which causes the error.
+
+ Added in Saleor 3.12.
+ """
+ stocks: [ID!]
+
+ """
+ List of channel IDs which causes the error.
+
+ Added in Saleor 3.12.
+ """
channels: [ID!]
+
+ """List of channel listings IDs which causes the error."""
+ channelListings: [ID!]
}
"""An enumeration."""
@@ -19078,16 +19092,72 @@ input ProductVariantBulkUpdateInput {
"""
externalReference: String
- """Stocks of a product available for sale."""
- stocks: [StockInput!]
+ """
+ Stocks input.
+
+ Added in Saleor 3.12.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ stocks: ProductVariantStocksUpdateInput
- """List of prices assigned to channels."""
- channelListings: [ProductVariantChannelListingAddInput!]
+ """
+ Channel listings input.
+
+ Added in Saleor 3.12.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ channelListings: ProductVariantChannelListingUpdateInput
"""ID of the product variant to update."""
id: ID!
}
+input ProductVariantStocksUpdateInput {
+ """List of warehouses to create stocks."""
+ create: [StockInput!]
+
+ """List of stocks to update."""
+ update: [StockUpdateInput!]
+
+ """List of stocks to remove."""
+ remove: [ID!]
+}
+
+input StockUpdateInput {
+ """Stock."""
+ stock: ID!
+
+ """Quantity of items available for sell."""
+ quantity: Int!
+}
+
+input ProductVariantChannelListingUpdateInput {
+ """List of channels to create variant channel listings."""
+ create: [ProductVariantChannelListingAddInput!]
+
+ """List of channel listings to update."""
+ update: [ChannelListingUpdateInput!]
+
+ """List of channel listings to remove."""
+ remove: [ID!]
+}
+
+input ChannelListingUpdateInput {
+ """ID of a channel listing."""
+ channelListing: 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."""
+ preorderThreshold: Int
+}
+
"""
Deletes product variants.
diff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.py
index 857b3d6fe8..278105a932 100644
--- a/saleor/product/utils/variants.py
+++ b/saleor/product/utils/variants.py
@@ -20,8 +20,7 @@ def generate_and_set_variant_name(
attribute_rel: AssignedVariantAttribute
for attribute_rel in variant_selection_attributes.iterator():
values_qs = attribute_rel.values.all()
- translated_values = [str(value.translated) for value in values_qs]
- attributes_display.append(", ".join(translated_values))
+ attributes_display.append(", ".join([str(value) for value in values_qs]))
name = " / ".join(sorted(attributes_display))
if not name: