Skip to content

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

Allow to update/delete product variant by providing SKU (#10861)

SzymJ0b46c89dfd9e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 63cdfd3647..3c1d4cf933 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Use `AttributeValue.name` instead of `AttributeValue.slug` to determine uniqueness of a value instance for dropdown and multiselect attributes. - #10881 by @jakubkuc
- Allow sorting products by `CREATED_AT` field. #10900 by @zedzior
- Add ability to pass metadata directly in create/update mutations for product app models - #10689 by @SzymJ
+- Add ability to use SKU argument in `productVariantUpdate`, `productVariantDelete`, `productVariantBulkDelete`, `productVariantStocksUpdate`, `productVariantStocksDelete`, `productVariantChannelListingUpdate` mutations - #10861 by @SzymJ
### Other changes
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index d5533c6af3..b0f2d9dca2 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -31,6 +31,7 @@ from ....warehouse.error_codes import StockErrorCode
from ...app.dataloaders import load_app
from ...channel import ChannelContext
from ...channel.types import Channel
+from ...core.descriptions import ADDED_IN_38
from ...core.mutations import BaseMutation, ModelBulkDeleteMutation, ModelMutation
from ...core.types import (
BulkProductError,
@@ -41,7 +42,10 @@ from ...core.types import (
StockError,
)
from ...core.utils import get_duplicated_values
-from ...core.validators import validate_price_precision
+from ...core.validators import (
+ validate_one_of_args_is_in_mutation,
+ validate_price_precision,
+)
from ...plugins.dataloaders import load_plugin_manager
from ...warehouse.dataloaders import (
StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader,
@@ -580,9 +584,14 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
class Arguments:
ids = NonNullList(
graphene.ID,
- required=True,
+ required=False,
description="List of product variant IDs to delete.",
)
+ skus = NonNullList(
+ graphene.String,
+ required=False,
+ description="List of product variant SKUs to delete." + ADDED_IN_38,
+ )
class Meta:
description = "Deletes product variants."
@@ -594,11 +603,19 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
@classmethod
@traced_atomic_transaction()
- def perform_mutation(cls, _root, info, ids, **data):
- try:
- pks = cls.get_global_ids_or_error(ids, ProductVariant)
- except ValidationError as error:
- return 0, error
+ def perform_mutation(cls, _root, info, ids=None, skus=None, **data):
+ validate_one_of_args_is_in_mutation(ProductErrorCode, "skus", skus, "ids", ids)
+
+ if ids:
+ try:
+ pks = cls.get_global_ids_or_error(ids, ProductVariant)
+ except ValidationError as error:
+ return 0, error
+ if skus:
+ pks = models.ProductVariant.objects.filter(sku__in=skus).values_list(
+ "pk", flat=True
+ )
+ ids = [graphene.Node.to_global_id("ProductVariant", pk) for pk in pks]
draft_order_lines_data = get_draft_order_lines_data_for_variants(pks)
@@ -799,13 +816,45 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):
error_type_class = BulkStockError
error_type_field = "bulk_stock_errors"
+ class Arguments:
+ variant_id = graphene.ID(
+ required=False,
+ description="ID of a product variant for which stocks will be updated.",
+ )
+ sku = graphene.String(
+ required=False,
+ description="SKU of product variant for which stocks will be updated.",
+ )
+ stocks = NonNullList(
+ StockInput,
+ required=True,
+ description="Input list of stocks to create or update.",
+ )
+
@classmethod
def perform_mutation(cls, _root, info, **data):
errors = defaultdict(list)
stocks = data["stocks"]
- variant = cls.get_node_or_error(
- info, data["variant_id"], only_type=ProductVariant
- )
+ sku = data.get("sku")
+ variant_id = data.get("variant_id")
+
+ validate_one_of_args_is_in_mutation(
+ ProductErrorCode, "sku", sku, "variant_id", variant_id
+ )
+
+ if variant_id:
+ variant = cls.get_node_or_error(info, variant_id, only_type=ProductVariant)
+ if sku:
+ variant = models.ProductVariant.objects.filter(sku=sku).first()
+ if not variant:
+ raise ValidationError(
+ {
+ "sku": ValidationError(
+ "Couldn't resolve to a node: %s" % sku, code="not_found"
+ )
+ }
+ )
+
if stocks:
warehouse_ids = [stock["warehouse"] for stock in stocks]
cls.check_for_duplicates(warehouse_ids, errors)
@@ -858,10 +907,16 @@ class ProductVariantStocksDelete(BaseMutation):
class Arguments:
variant_id = graphene.ID(
- required=True,
+ required=False,
description="ID of product variant for which stocks will be deleted.",
)
- warehouse_ids = NonNullList(graphene.ID)
+ sku = graphene.String(
+ required=False,
+ description="SKU of product variant for which stocks will be deleted.",
+ )
+ warehouse_ids = NonNullList(
+ graphene.ID, description="Input list of warehouse IDs."
+ )
class Meta:
description = "Delete stocks from product variant."
@@ -872,10 +927,27 @@ class ProductVariantStocksDelete(BaseMutation):
@classmethod
@traced_atomic_transaction()
def perform_mutation(cls, _root, info, **data):
- manager = load_plugin_manager(info.context)
- variant = cls.get_node_or_error(
- info, data["variant_id"], only_type=ProductVariant
+ sku = data.get("sku")
+ variant_id = data.get("variant_id")
+ validate_one_of_args_is_in_mutation(
+ ProductErrorCode, "sku", sku, "variant_id", variant_id
)
+
+ manager = load_plugin_manager(info.context)
+
+ if variant_id:
+ variant = cls.get_node_or_error(info, variant_id, only_type=ProductVariant)
+ if sku:
+ variant = models.ProductVariant.objects.filter(sku=sku).first()
+ if not variant:
+ raise ValidationError(
+ {
+ "sku": ValidationError(
+ "Couldn't resolve to a node: %s" % sku, code="not_found"
+ )
+ }
+ )
+
warehouses_pks = cls.get_global_ids_or_error(
data["warehouse_ids"], Warehouse, field="warehouse_ids"
)
diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.py
index bb933a8bbb..4ab490024b 100644
--- a/saleor/graphql/product/mutations/channels.py
+++ b/saleor/graphql/product/mutations/channels.py
@@ -24,6 +24,7 @@ from ...channel.types import Channel
from ...core.descriptions import (
ADDED_IN_31,
ADDED_IN_33,
+ ADDED_IN_38,
DEPRECATED_IN_3X_INPUT,
PREVIEW_FEATURE,
)
@@ -35,7 +36,10 @@ from ...core.types import (
ProductChannelListingError,
)
from ...core.utils import get_duplicated_values
-from ...core.validators import validate_price_precision
+from ...core.validators import (
+ validate_one_of_args_is_in_mutation,
+ validate_price_precision,
+)
from ...plugins.dataloaders import load_plugin_manager
from ...utils.validators import check_for_duplicates
from ..types.products import Collection, Product, ProductVariant
@@ -386,7 +390,11 @@ class ProductVariantChannelListingUpdate(BaseMutation):
class Arguments:
id = graphene.ID(
- required=True, description="ID of a product variant to update."
+ required=False, description="ID of a product variant to update."
+ )
+ sku = graphene.String(
+ required=False,
+ description="SKU of a product variant to update." + ADDED_IN_38,
)
input = NonNullList(
ProductVariantChannelListingAddInput,
@@ -511,11 +519,25 @@ class ProductVariantChannelListingUpdate(BaseMutation):
cls.call_event(manager.product_variant_updated, variant)
@classmethod
- def perform_mutation(cls, _root, info, id, input):
+ def perform_mutation(cls, _root, info, input, id=None, sku=None):
+ validate_one_of_args_is_in_mutation(ProductErrorCode, "sku", sku, "id", id)
+
qs = ProductVariantModel.objects.prefetched_for_webhook()
- variant: "ProductVariantModel" = cls.get_node_or_error( # type: ignore
- info, id, only_type=ProductVariant, field="id", qs=qs
- )
+ if id:
+ variant: "ProductVariantModel" = cls.get_node_or_error( # type: ignore
+ info, id, only_type=ProductVariant, field="id", qs=qs
+ )
+ else:
+ variant = qs.filter(sku=sku).first()
+ if not variant:
+ raise ValidationError(
+ {
+ "sku": ValidationError(
+ "Couldn't resolve to a node: %s" % sku, code="not_found"
+ )
+ }
+ )
+
errors = defaultdict(list)
cleaned_input = cls.clean_channels(info, input, errors)
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index b9bfcb055d..82c8235995 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -59,6 +59,7 @@ from ...core.utils import (
validate_slug_and_generate_if_needed,
)
from ...core.utils.reordering import perform_reordering
+from ...core.validators import validate_one_of_args_is_in_mutation
from ...meta.mutations import MetadataInput
from ...plugins.dataloaders import load_plugin_manager
from ...warehouse.types import Warehouse
@@ -1099,18 +1100,38 @@ class ProductVariantCreate(ModelMutation):
"""
object_id = data.get("id")
- if object_id and data.get("attributes"):
+ object_sku = data.get("sku")
+ attributes = data.get("attributes")
+
+ if attributes:
# Prefetches needed by AttributeAssignmentMixin and
# associate_attribute_values_to_instance
qs = cls.Meta.model.objects.prefetch_related(
"product__product_type__variant_attributes__values",
"product__product_type__attributevariant",
)
+ else:
+ # Use the default queryset.
+ qs = models.ProductVariant.objects.all()
+
+ if object_id:
return cls.get_node_or_error(
info, object_id, only_type="ProductVariant", qs=qs
)
-
- return super().get_instance(info, **data)
+ elif object_sku:
+ instance = qs.filter(sku=object_sku).first()
+ if not instance:
+ raise ValidationError(
+ {
+ "sku": ValidationError(
+ "Couldn't resolve to a node: %s" % object_sku,
+ code="not_found",
+ )
+ }
+ )
+ return instance
+ else:
+ return cls._meta.model()
@classmethod
def save(cls, info, instance, cleaned_input):
@@ -1159,7 +1180,11 @@ class ProductVariantCreate(ModelMutation):
class ProductVariantUpdate(ProductVariantCreate):
class Arguments:
id = graphene.ID(
- required=True, description="ID of a product variant to update."
+ required=False, description="ID of a product variant to update."
+ )
+ sku = graphene.String(
+ required=False,
+ description="SKU of a product variant to update." + ADDED_IN_38,
)
input = ProductVariantInput(
required=True, description="Fields required to update a product variant."
@@ -1212,11 +1237,22 @@ class ProductVariantUpdate(ProductVariantCreate):
attributes_data, used_attribute_values
)
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ validate_one_of_args_is_in_mutation(
+ ProductErrorCode, "sku", data.get("sku"), "id", data.get("id")
+ )
+ return super().perform_mutation(_root, info, **data)
+
class ProductVariantDelete(ModelDeleteMutation):
class Arguments:
id = graphene.ID(
- required=True, description="ID of a product variant to delete."
+ required=False, description="ID of a product variant to delete."
+ )
+ sku = graphene.String(
+ required=False,
+ description="SKU of a product variant to delete." + ADDED_IN_38,
)
class Meta:
@@ -1242,8 +1278,24 @@ class ProductVariantDelete(ModelDeleteMutation):
@classmethod
def perform_mutation(cls, _root, info, **data):
- node_id = data.get("id")
- instance = cls.get_node_or_error(info, node_id, only_type=ProductVariant)
+ validate_one_of_args_is_in_mutation(
+ ProductErrorCode, "sku", data.get("sku"), "id", data.get("id")
+ )
+ if node_id := data.get("id"):
+ instance = cls.get_node_or_error(info, node_id, only_type=ProductVariant)
+
+ if node_sku := data.get("sku"):
+ instance = models.ProductVariant.objects.filter(sku=node_sku).first()
+ if not instance:
+ raise ValidationError(
+ {
+ "sku": ValidationError(
+ "Couldn't resolve to a node: %s" % node_sku,
+ code="not_found",
+ )
+ }
+ )
+ data["id"] = graphene.Node.to_global_id("ProductVariant", instance.id)
draft_order_lines_data = get_draft_order_lines_data_for_variants([instance.pk])
diff --git a/saleor/graphql/product/tests/benchmark/test_variant_stocks.py b/saleor/graphql/product/tests/benchmark/test_variant_stocks.py
index f52641dc3d..9953a04a62 100644
--- a/saleor/graphql/product/tests/benchmark/test_variant_stocks.py
+++ b/saleor/graphql/product/tests/benchmark/test_variant_stocks.py
@@ -140,33 +140,36 @@ def test_product_variants_stocks_create_with_single_webhook_called(
product_variant_back_in_stock_webhook_mock.assert_called_with(Stock.objects.last())
[email protected]_queries(autouse=False)
-def test_product_variants_stocks_update(
- staff_api_client, variant, warehouse, permission_manage_products, count_queries
-):
- query = """
- mutation ProductVariantStocksUpdate($variantId: ID!, $stocks: [StockInput!]!){
- productVariantStocksUpdate(variantId: $variantId, stocks: $stocks){
- productVariant{
- stocks{
- quantity
- quantityAllocated
- id
- warehouse{
- slug
- }
+PRODUCT_VARIANT_STOCKS_UPDATE_MUTATION = """
+mutation ProductVariantStocksUpdate(
+ $variantId: ID, $sku: String, $stocks: [StockInput!]!){
+ productVariantStocksUpdate(variantId: $variantId, sku: $sku, stocks: $stocks){
+ productVariant{
+ stocks{
+ quantity
+ quantityAllocated
+ id
+ warehouse{
+ slug
}
}
- errors{
- code
- field
- message
- index
- }
+ }
+ errors{
+ code
+ field
+ message
+ index
}
}
- """
+ }
+"""
+
+
[email protected]_queries(autouse=False)
+def test_product_variants_stocks_update_byid(
+ staff_api_client, variant, warehouse, permission_manage_products, count_queries
+):
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
second_warehouse = Warehouse.objects.get(pk=warehouse.pk)
second_warehouse.slug = "second warehouse"
@@ -189,7 +192,7 @@ def test_product_variants_stocks_update(
]
variables = {"variantId": variant_id, "stocks": stocks}
response = staff_api_client.post_graphql(
- query,
+ PRODUCT_VARIANT_STOCKS_UPDATE_MUTATION,
variables,
permissions=[permission_manage_products],
)
@@ -203,19 +206,47 @@ def test_product_variants_stocks_update(
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
-def test_product_variants_stocks_delete(
- product_variant_out_of_stock_webhook_mock,
- staff_api_client,
- variant,
- warehouse,
- permission_manage_products,
- count_queries,
+def test_product_variants_stocks_update_by_sku(
+ staff_api_client, variant, warehouse, permission_manage_products, count_queries
):
- query = """
- mutation ProductVariantStocksDelete($variantId: ID!, $warehouseIds: [ID!]!){
+ second_warehouse = Warehouse.objects.get(pk=warehouse.pk)
+ second_warehouse.slug = "second warehouse"
+ second_warehouse.pk = None
+ second_warehouse.save()
+
+ Stock.objects.create(product_variant=variant, warehouse=warehouse, quantity=10)
+
+ stocks_count = variant.stocks.count()
+
+ stocks = [
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.id),
+ "quantity": 20,
+ },
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", second_warehouse.id),
+ "quantity": 100,
+ },
+ ]
+ variables = {"sku": variant.sku, "stocks": stocks}
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_STOCKS_UPDATE_MUTATION,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantStocksUpdate"]
+
+ assert not data["errors"]
+ assert len(data["productVariant"]["stocks"]) == len(stocks)
+ assert variant.stocks.count() == stocks_count + 1
+
+
+PRODUCT_VARIANT_STOCKS_DELETE_MUTATION = """
+ mutation ProductVariantStocksDelete(
+ $variantId: ID, $sku: String, $warehouseIds: [ID!]!){
productVariantStocksDelete(
- variantId: $variantId, warehouseIds: $warehouseIds
+ variantId: $variantId, sku: $sku, warehouseIds: $warehouseIds
){
productVariant{
stocks{
@@ -234,6 +265,19 @@ def test_product_variants_stocks_delete(
}
}
"""
+
+
[email protected]_queries(autouse=False)
+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
+def test_product_variants_stocks_delete_by_id(
+ product_variant_out_of_stock_webhook_mock,
+ staff_api_client,
+ variant,
+ warehouse,
+ permission_manage_products,
+ count_queries,
+):
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
second_warehouse = Warehouse.objects.get(pk=warehouse.pk)
second_warehouse.slug = "second warehouse"
@@ -253,7 +297,53 @@ def test_product_variants_stocks_delete(
variables = {"variantId": variant_id, "warehouseIds": warehouse_ids}
response = staff_api_client.post_graphql(
- query,
+ PRODUCT_VARIANT_STOCKS_DELETE_MUTATION,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantStocksDelete"]
+
+ assert not data["stockErrors"]
+ assert (
+ len(data["productVariant"]["stocks"])
+ == variant.stocks.count()
+ == stocks_count - 1
+ )
+ assert stock_to_delete not in Stock.objects.all()
+ product_variant_out_of_stock_webhook_mock.assert_called_once_with(stock_to_delete)
+
+
[email protected]_queries(autouse=False)
+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
+def test_product_variants_stocks_delete_by_sku(
+ product_variant_out_of_stock_webhook_mock,
+ staff_api_client,
+ variant,
+ warehouse,
+ permission_manage_products,
+ count_queries,
+):
+ second_warehouse = Warehouse.objects.get(pk=warehouse.pk)
+ second_warehouse.slug = "second warehouse"
+ second_warehouse.pk = None
+ second_warehouse.save()
+
+ Stock.objects.bulk_create(
+ [
+ Stock(product_variant=variant, warehouse=warehouse, quantity=10),
+ Stock(product_variant=variant, warehouse=second_warehouse, quantity=140),
+ ]
+ )
+ stock_to_delete = Stock.objects.last()
+ stocks_count = variant.stocks.count()
+
+ warehouse_ids = [graphene.Node.to_global_id("Warehouse", second_warehouse.id)]
+
+ variables = {"sku": variant.sku, "warehouseIds": warehouse_ids}
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_STOCKS_DELETE_MUTATION,
variables,
permissions=[permission_manage_products],
)
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 4b011c68d8..1342934cb2 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -873,6 +873,62 @@ def test_delete_product_types_with_file_attributes(
value.refresh_from_db()
+PRODUCT_VARIANT_BULK_DELETE_BY_SKU_MUTATION = """
+mutation productVariantBulkDelete($skus: [String!]!) {
+ productVariantBulkDelete(skus: $skus) {
+ count
+ errors {
+ code
+ field
+ }
+ }
+}
+"""
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
+def test_delete_product_variants_by_sku(
+ mocked_recalculate_orders_task,
+ product_variant_deleted_webhook_mock,
+ staff_api_client,
+ product_variant_list,
+ permission_manage_products,
+):
+ # given
+ product = product_variant_list[0].product
+
+ variant = product.variants.get(sku="123")
+ variant.sku = "abcd"
+ variant.save(update_fields=["sku"])
+
+ assert ProductVariantChannelListing.objects.filter(
+ variant_id__in=[variant.id for variant in product_variant_list]
+ ).exists()
+
+ variables = {"skus": [variant.sku for variant in product_variant_list]}
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_DELETE_BY_SKU_MUTATION,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+ flush_post_commit_hooks()
+
+ # then
+ assert content["data"]["productVariantBulkDelete"]["count"] == 4
+ assert not ProductVariant.objects.filter(
+ id__in=[variant.id for variant in product_variant_list]
+ ).exists()
+ assert (
+ product_variant_deleted_webhook_mock.call_count
+ == content["data"]["productVariantBulkDelete"]["count"]
+ )
+ mocked_recalculate_orders_task.assert_not_called()
+
+
PRODUCT_VARIANT_BULK_DELETE_MUTATION = """
mutation productVariantBulkDelete($ids: [ID!]!) {
productVariantBulkDelete(ids: $ids) {
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index afbdf76030..4ce7e8b1af 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -2353,7 +2353,7 @@ def test_product_variant_update_with_new_attributes(
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
-def test_update_product_variant(
+def test_update_product_variant_by_id(
product_variant_updated_webhook_mock,
product_variant_created_webhook_mock,
staff_api_client,
@@ -2388,7 +2388,6 @@ def test_update_product_variant(
}
}
}
-
"""
variant = product.variants.first()
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
@@ -2422,6 +2421,122 @@ def test_update_product_variant(
product_variant_created_webhook_mock.assert_not_called()
+UPDATE_VARIANT_BY_SKU = """
+ mutation updateVariant (
+ $sku: String!,
+ $newSku: String!,
+ $quantityLimitPerCustomer: Int!
+ $trackInventory: Boolean!,
+ $attributes: [AttributeValueInput!]) {
+ productVariantUpdate(
+ sku: $sku,
+ input: {
+ sku: $newSku,
+ trackInventory: $trackInventory,
+ attributes: $attributes,
+ quantityLimitPerCustomer: $quantityLimitPerCustomer,
+ }) {
+ productVariant {
+ name
+ sku
+ quantityLimitPerCustomer
+ channelListings {
+ channel {
+ slug
+ }
+ }
+ }
+ errors {
+ field
+ message
+ attributes
+ code
+ }
+ }
+ }
+
+"""
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
+def test_update_product_variant_by_sku(
+ product_variant_updated_webhook_mock,
+ product_variant_created_webhook_mock,
+ staff_api_client,
+ product,
+ size_attribute,
+ permission_manage_products,
+):
+ # given
+ variant = product.variants.first()
+ attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+ sku = "test sku"
+ quantity_limit_per_customer = 5
+ attr_value = "S"
+
+ variables = {
+ "sku": variant.sku,
+ "newSku": sku,
+ "trackInventory": True,
+ "quantityLimitPerCustomer": quantity_limit_per_customer,
+ "attributes": [{"id": attribute_id, "values": [attr_value]}],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ UPDATE_VARIANT_BY_SKU, variables, permissions=[permission_manage_products]
+ )
+ variant.refresh_from_db()
+ content = get_graphql_content(response)
+ flush_post_commit_hooks()
+ data = content["data"]["productVariantUpdate"]["productVariant"]
+
+ # then
+ assert data["name"] == variant.name
+ assert data["sku"] == sku
+ assert data["quantityLimitPerCustomer"] == quantity_limit_per_customer
+ product_variant_updated_webhook_mock.assert_called_once_with(
+ product.variants.last()
+ )
+ product_variant_created_webhook_mock.assert_not_called()
+
+
+def test_update_product_variant_by_sku_return_error_when_sku_dont_exists(
+ staff_api_client,
+ product,
+ size_attribute,
+ permission_manage_products,
+):
+ # given
+ variant = product.variants.first()
+ attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+ sku = "test sku"
+ quantity_limit_per_customer = 5
+ attr_value = "S"
+
+ variables = {
+ "sku": "randomSku",
+ "newSku": sku,
+ "trackInventory": True,
+ "quantityLimitPerCustomer": quantity_limit_per_customer,
+ "attributes": [{"id": attribute_id, "values": [attr_value]}],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ UPDATE_VARIANT_BY_SKU, variables, permissions=[permission_manage_products]
+ )
+ variant.refresh_from_db()
+ content = get_graphql_content(response)
+ flush_post_commit_hooks()
+ data = content["data"]["productVariantUpdate"]
+
+ # then
+ assert data["errors"][0]["field"] == "sku"
+ assert data["errors"][0]["code"] == "NOT_FOUND"
+
+
def test_update_product_variant_with_negative_weight(
staff_api_client, product, permission_manage_products
):
@@ -3975,6 +4090,50 @@ def test_update_product_variant_can_not_turn_off_preorder(
assert data["preorder"]["endDate"] is None
+DELETE_VARIANT_BY_SKU_MUTATION = """
+ mutation variantDelete($sku: String) {
+ productVariantDelete(sku: $sku) {
+ productVariant {
+ sku
+ id
+ }
+ }
+ }
+"""
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
+def test_delete_variant_by_sku(
+ mocked_recalculate_orders_task,
+ product_variant_deleted_webhook_mock,
+ staff_api_client,
+ product,
+ permission_manage_products,
+):
+ # given
+ variant = product.variants.first()
+ variant_sku = variant.sku
+ variables = {"sku": variant_sku}
+
+ # when
+ response = staff_api_client.post_graphql(
+ DELETE_VARIANT_BY_SKU_MUTATION,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+ flush_post_commit_hooks()
+ data = content["data"]["productVariantDelete"]
+
+ # then
+ product_variant_deleted_webhook_mock.assert_called_once_with(variant)
+ assert data["productVariant"]["sku"] == variant_sku
+ with pytest.raises(variant._meta.model.DoesNotExist):
+ variant.refresh_from_db()
+ mocked_recalculate_orders_task.assert_not_called()
+
+
DELETE_VARIANT_MUTATION = """
mutation variantDelete($id: ID!) {
productVariantDelete(id: $id) {
diff --git a/saleor/graphql/product/tests/test_variant_channel_listing_update.py b/saleor/graphql/product/tests/test_variant_channel_listing_update.py
index 6640b78651..e293d11d4c 100644
--- a/saleor/graphql/product/tests/test_variant_channel_listing_update.py
+++ b/saleor/graphql/product/tests/test_variant_channel_listing_update.py
@@ -13,10 +13,11 @@ from ...tests.utils import (
PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION = """
mutation UpdateProductVariantChannelListing(
- $id: ID!,
+ $id: ID,
+ $sku: String,
$input: [ProductVariantChannelListingAddInput!]!
) {
- productVariantChannelListingUpdate(id: $id, input: $input) {
+ productVariantChannelListingUpdate(id: $id, sku: $sku, input: $input) {
errors {
field
message
@@ -241,6 +242,66 @@ def test_variant_channel_listing_update_as_staff_user(
assert channel_pln_data["channel"]["slug"] == channel_PLN.slug
+def test_variant_channel_listing_update_by_sku(
+ staff_api_client, product, permission_manage_products, channel_USD, channel_PLN
+):
+ # given
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_PLN,
+ is_published=True,
+ )
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_usd_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ price = 1
+ second_price = 20
+ variables = {
+ "sku": variant.sku,
+ "input": [
+ {"channelId": channel_usd_id, "price": price, "costPrice": price},
+ {
+ "channelId": channel_pln_id,
+ "price": second_price,
+ "costPrice": second_price,
+ },
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productVariantChannelListingUpdate"]
+ variant_data = data["variant"]
+ assert not data["errors"]
+ assert variant_data["id"] == variant_id
+ channel_usd_data = next(
+ channel_data
+ for channel_data in variant_data["channelListings"]
+ if channel_data["channel"]["id"] == channel_usd_id
+ )
+ channel_pln_data = next(
+ channel_data
+ for channel_data in variant_data["channelListings"]
+ if channel_data["channel"]["id"] == channel_pln_id
+ )
+ assert channel_usd_data["price"]["currency"] == "USD"
+ assert channel_usd_data["price"]["amount"] == price
+ assert channel_usd_data["costPrice"]["amount"] == price
+ assert channel_usd_data["channel"]["slug"] == channel_USD.slug
+ assert channel_pln_data["price"]["currency"] == "PLN"
+ assert channel_pln_data["price"]["amount"] == second_price
+ assert channel_pln_data["costPrice"]["amount"] == second_price
+ assert channel_pln_data["channel"]["slug"] == channel_PLN.slug
+
+
@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
def test_variant_channel_listing_update_trigger_webhook_product_variant_updated(
mock_product_variant_updated,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 0795d9b39f..d747ba0d00 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -11766,7 +11766,14 @@ type Mutation {
"""
productVariantDelete(
"""ID of a product variant to delete."""
- id: ID!
+ id: ID
+
+ """
+ SKU of a product variant to delete.
+
+ Added in Saleor 3.8.
+ """
+ sku: String
): ProductVariantDelete
"""
@@ -11789,7 +11796,14 @@ type Mutation {
"""
productVariantBulkDelete(
"""List of product variant IDs to delete."""
- ids: [ID!]!
+ ids: [ID!]
+
+ """
+ List of product variant SKUs to delete.
+
+ Added in Saleor 3.8.
+ """
+ skus: [String!]
): ProductVariantBulkDelete
"""
@@ -11811,8 +11825,13 @@ type Mutation {
Requires one of the following permissions: MANAGE_PRODUCTS.
"""
productVariantStocksDelete(
+ """SKU of product variant for which stocks will be deleted."""
+ sku: String
+
"""ID of product variant for which stocks will be deleted."""
- variantId: ID!
+ variantId: ID
+
+ """Input list of warehouse IDs."""
warehouseIds: [ID!]
): ProductVariantStocksDelete
@@ -11822,11 +11841,14 @@ type Mutation {
Requires one of the following permissions: MANAGE_PRODUCTS.
"""
productVariantStocksUpdate(
- """Input list of stocks to create."""
+ """SKU of product variant for which stocks will be updated."""
+ sku: String
+
+ """Input list of stocks to create or update."""
stocks: [StockInput!]!
- """ID of a product variant for which stocks will be created."""
- variantId: ID!
+ """ID of a product variant for which stocks will be updated."""
+ variantId: ID
): ProductVariantStocksUpdate
"""
@@ -11836,10 +11858,17 @@ type Mutation {
"""
productVariantUpdate(
"""ID of a product variant to update."""
- id: ID!
+ id: ID
"""Fields required to update a product variant."""
input: ProductVariantInput!
+
+ """
+ SKU of a product variant to update.
+
+ Added in Saleor 3.8.
+ """
+ sku: String
): ProductVariantUpdate
"""
@@ -11876,12 +11905,19 @@ type Mutation {
"""
productVariantChannelListingUpdate(
"""ID of a product variant to update."""
- id: ID!
+ id: ID
"""
List of fields required to create or upgrade product variant channel listings.
"""
input: [ProductVariantChannelListingAddInput!]!
+
+ """
+ SKU of a product variant to update.
+
+ Added in Saleor 3.8.
+ """
+ sku: String
): ProductVariantChannelListingUpdate
"""