Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add StocksBulkUpdate mutation (#12139)
SzymJea347ff6029b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 50419d0735..5852b9f23d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ All notable, unreleased changes to this project will be documented in this file.### Breaking changes### GraphQL API+- [Preview] Add `StockBulkUpdate` mutation - #12139 by @SzymJ### Other changesdiff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex d5eb157ce6..9d98280e9c 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -25,7 +25,12 @@ from .shipping.schema import ShippingMutations, ShippingQueriesfrom .shop.schema import ShopMutations, ShopQueriesfrom .tax.schema import TaxMutations, TaxQueriesfrom .translations.schema import TranslationQueries-from .warehouse.schema import StockQueries, WarehouseMutations, WarehouseQueries+from .warehouse.schema import (+ StockMutations,+ StockQueries,+ WarehouseMutations,+ WarehouseQueries,+)from .webhook.schema import WebhookMutations, WebhookQueriesfrom .webhook.subscription_types import WEBHOOK_TYPES_MAP, Subscription@@ -80,6 +85,7 @@ class Mutation(ProductMutations,ShippingMutations,ShopMutations,+ StockMutations,TaxMutations,WarehouseMutations,WebhookMutations,diff --git a/saleor/graphql/core/descriptions.py b/saleor/graphql/core/descriptions.pyindex c4928970a1..0ea6be3d25 100644--- a/saleor/graphql/core/descriptions.py+++ b/saleor/graphql/core/descriptions.py@@ -23,6 +23,7 @@ ADDED_IN_39 = "\n\nAdded in Saleor 3.9."ADDED_IN_310 = "\n\nAdded in Saleor 3.10."ADDED_IN_311 = "\n\nAdded in Saleor 3.11."ADDED_IN_312 = "\n\nAdded in Saleor 3.12."+ADDED_IN_313 = "\n\nAdded in Saleor 3.13."PREVIEW_FEATURE = (diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.pyindex 38de8c4fd2..63fc90d8cb 100644--- a/saleor/graphql/core/enums.py+++ b/saleor/graphql/core/enums.py@@ -176,6 +176,9 @@ CollectionErrorCode = graphene.Enum.from_enum(product_error_codes.CollectionErroShopErrorCode = graphene.Enum.from_enum(core_error_codes.ShopErrorCode)ShippingErrorCode = graphene.Enum.from_enum(shipping_error_codes.ShippingErrorCode)StockErrorCode = graphene.Enum.from_enum(warehouse_error_codes.StockErrorCode)+StockBulkUpdateErrorCode = graphene.Enum.from_enum(+ warehouse_error_codes.StockBulkUpdateErrorCode+)UploadErrorCode = graphene.Enum.from_enum(core_error_codes.UploadErrorCode)WarehouseErrorCode = graphene.Enum.from_enum(warehouse_error_codes.WarehouseErrorCode)WebhookErrorCode = graphene.Enum.from_enum(webhook_error_codes.WebhookErrorCode)diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.pyindex c06f27d7e9..a4609e8962 100644--- a/saleor/graphql/core/types/__init__.py+++ b/saleor/graphql/core/types/__init__.py@@ -46,6 +46,7 @@ from .common import (ShippingError,ShopError,StaffError,+ StockBulkUpdateError,StockError,TaxType,ThumbnailField,@@ -126,6 +127,7 @@ __all__ = ["ShopError","StaffError","StockError",+ "StockBulkUpdateError","TaxType","TaxedMoney","TaxedMoneyRange",diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.pyindex 144581f5da..146a81f291 100644--- a/saleor/graphql/core/types/common.py+++ b/saleor/graphql/core/types/common.py@@ -40,6 +40,7 @@ from ..enums import (ProductVariantBulkErrorCode,ShippingErrorCode,ShopErrorCode,+ StockBulkUpdateErrorCode,StockErrorCode,ThumbnailFormatEnum,TimePeriodTypeEnum,@@ -436,6 +437,10 @@ class BulkStockError(ProductError):)+class StockBulkUpdateError(Error):+ code = StockBulkUpdateErrorCode(description="The error code.", required=True)++class UploadError(Error):code = UploadErrorCode(description="The error code.", required=True)diff --git a/saleor/graphql/core/validators/__init__.py b/saleor/graphql/core/validators/__init__.pyindex b52d538ad8..ced850c155 100644--- a/saleor/graphql/core/validators/__init__.py+++ b/saleor/graphql/core/validators/__init__.py@@ -4,6 +4,7 @@ from uuid import UUIDimport graphenefrom django.core.exceptions import ValidationErrorfrom django_prices.utils.formatting import get_currency_fraction+from graphene.utils.str_converters import to_camel_casefrom graphql.error import GraphQLErrorfrom ....core.utils import generate_unique_slug@@ -15,28 +16,41 @@ if TYPE_CHECKING:from django.db.models import Model-def validate_one_of_args_is_in_mutation(*args):+def validate_one_of_args_is_in_mutation(*args, **kwargs):try:- validate_one_of_args_is_in_query(*args)+ validate_one_of_args_is_in_query(*args, **kwargs)except GraphQLError as e:raise ValidationError(str(e), code="graphql_error")-def validate_one_of_args_is_in_query(*args):+def validate_one_of_args_is_in_query(*args, **kwargs):# split args into a list with 2-element tuples:# [(arg1_name, arg1_value), (arg2_name, arg2_value), ...]splitted_args = [args[i : i + 2] for i in range(0, len(args), 2)] # noqa: E203# filter trueish values from each tuplefilter_args = list(filter(lambda item: bool(item[1]) is True, splitted_args))+ use_camel_case = kwargs.get("use_camel_case")if len(filter_args) > 1:- rest_args = ", ".join([f"'{item[0]}'" for item in filter_args[1:]])+ if use_camel_case:+ first_arg = to_camel_case(filter_args[0][0])+ rest_args = ", ".join(+ [f"'{to_camel_case(item[0])}'" for item in filter_args[1:]]+ )+ else:+ first_arg = filter_args[0][0]+ rest_args = ", ".join([f"'{item[0]}'" for item in filter_args[1:]])raise GraphQLError(- f"Argument '{filter_args[0][0]}' cannot be combined with {rest_args}"+ f"Argument '{first_arg}' cannot be combined with {rest_args}")if not filter_args:- required_args = ", ".join([f"'{item[0]}'" for item in splitted_args])+ if use_camel_case:+ required_args = ", ".join(+ [f"'{to_camel_case(item[0])}'" for item in splitted_args]+ )+ else:+ required_args = ", ".join([f"'{item[0]}'" for item in splitted_args])raise GraphQLError(f"At least one of arguments is required: {required_args}.")diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 182e67bbc3..bd4868f957 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -12407,6 +12407,23 @@ type Mutation {taxExemption: Boolean!): TaxExemptionManage+ """+ Updates stocks for a given variant and warehouse.++ 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.+ """+ stockBulkUpdate(+ """Policies of error handling. DEFAULT: REJECT_EVERYTHING"""+ errorPolicy: ErrorPolicyEnum = reject_everything++ """Input list of stocks to update."""+ stocks: [StockBulkUpdateInput!]!+ ): StockBulkUpdate+"""Creates a new staff notification recipient.@@ -16818,6 +16835,83 @@ enum TaxExemptionManageErrorCode {NOT_EDITABLE_ORDER}+"""+Updates stocks for a given variant and warehouse.++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 StockBulkUpdate {+ """Returns how many objects were updated."""+ count: Int!++ """List of the updated stocks."""+ results: [StockBulkResult!]!+ errors: [StockBulkUpdateError!]!+}++type StockBulkResult {+ """Stock data."""+ stock: Stock++ """List of errors occurred on create or update attempt."""+ errors: [StockBulkUpdateError!]+}++type StockBulkUpdateError {+ """+ 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: StockBulkUpdateErrorCode!+}++"""An enumeration."""+enum StockBulkUpdateErrorCode {+ GRAPHQL_ERROR+ INVALID+ NOT_FOUND+ REQUIRED+}++enum ErrorPolicyEnum {+ """+ Save what is possible within a single row. If there are errors in an input data row, try to save it partially and skip the invalid part.+ """+ IGNORE_FAILED++ """Reject all rows if there is at least one error in any of them."""+ REJECT_EVERYTHING++ """Reject rows with errors."""+ REJECT_FAILED_ROWS+}++input StockBulkUpdateInput {+ """Variant ID."""+ variantId: ID++ """Variant external reference."""+ variantExternalReference: String++ """Warehouse ID."""+ warehouseId: ID++ """Warehouse external reference."""+ warehouseExternalReference: String++ """Quantity of items available for sell."""+ quantity: Int!+}+"""Creates a new staff notification recipient.@@ -18930,19 +19024,6 @@ type BulkProductError {channels: [ID!]}-enum ErrorPolicyEnum {- """- Save what is possible within a single row. If there are errors in an input data row, try to save it partially and skip the invalid part.- """- IGNORE_FAILED-- """Reject all rows if there is at least one error in any of them."""- REJECT_EVERYTHING-- """Reject rows with errors."""- REJECT_FAILED_ROWS-}-input ProductVariantBulkCreateInput {"""List of attributes specific to this variant."""attributes: [BulkAttributeValueInput!]!diff --git a/saleor/graphql/warehouse/bulk_mutations/__init__.py b/saleor/graphql/warehouse/bulk_mutations/__init__.pynew file mode 100644index 0000000000..561380e461--- /dev/null+++ b/saleor/graphql/warehouse/bulk_mutations/__init__.py@@ -0,0 +1,3 @@+from .stock_bulk_update import StockBulkUpdate++__all__ = ["StockBulkUpdate"]diff --git a/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py b/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.pynew file mode 100644index 0000000000..7259f0c845--- /dev/null+++ b/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py@@ -0,0 +1,390 @@+from collections import defaultdict++import graphene+from django.core.exceptions import ValidationError+from django.db.models import F, Q++from ....core.tracing import traced_atomic_transaction+from ....permission.enums import ProductPermissions+from ....warehouse import models+from ....warehouse.error_codes import StockBulkUpdateErrorCode+from ...core.descriptions import ADDED_IN_313, PREVIEW_FEATURE+from ...core.enums import ErrorPolicyEnum+from ...core.mutations import BaseMutation+from ...core.types import NonNullList, StockBulkUpdateError+from ...core.validators import validate_one_of_args_is_in_mutation+from ...plugins.dataloaders import get_plugin_manager_promise+from ..types import Stock+++class StockBulkResult(graphene.ObjectType):+ stock = graphene.Field(Stock, required=False, description="Stock data.")+ errors = NonNullList(+ StockBulkUpdateError,+ required=False,+ description="List of errors occurred on create or update attempt.",+ )+++class StockBulkUpdateInput(graphene.InputObjectType):+ variant_id = graphene.ID(required=False, description="Variant ID.")+ variant_external_reference = graphene.String(+ required=False, description="Variant external reference."+ )+ warehouse_id = graphene.ID(required=False, description="Warehouse ID.")+ warehouse_external_reference = graphene.String(+ required=False, description="Warehouse external reference."+ )+ quantity = graphene.Int(+ required=True, description="Quantity of items available for sell."+ )+++class StockBulkUpdate(BaseMutation):+ count = graphene.Int(+ required=True,+ default_value=0,+ description="Returns how many objects were updated.",+ )+ results = NonNullList(+ StockBulkResult,+ required=True,+ default_value=[],+ description="List of the updated stocks.",+ )++ class Arguments:+ stocks = NonNullList(+ StockBulkUpdateInput,+ required=True,+ description="Input list of stocks to update.",+ )+ error_policy = ErrorPolicyEnum(+ required=False,+ default_value=ErrorPolicyEnum.REJECT_EVERYTHING.value,+ description=(+ "Policies of error handling. DEFAULT: "+ + ErrorPolicyEnum.REJECT_EVERYTHING.name+ ),+ )++ class Meta:+ description = (+ "Updates stocks for a given variant and warehouse."+ + ADDED_IN_313+ + PREVIEW_FEATURE+ )+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = StockBulkUpdateError++ @classmethod+ def validate_variant(+ cls, variant_id, external_ref, stock_input, index, index_error_map+ ):+ errors_count = 0+ try:+ validate_one_of_args_is_in_mutation(+ "variant_id",+ variant_id,+ "variant_external_reference",+ external_ref,+ use_camel_case=True,+ )+ except ValidationError as exc:+ index_error_map[index].append(+ StockBulkUpdateError(+ message=exc.message,+ code=StockBulkUpdateErrorCode.INVALID.value,+ )+ )+ errors_count += 1++ if variant_id:+ try:+ type, variant_db_id = graphene.Node.from_global_id(variant_id)+ if type != "ProductVariant":+ index_error_map[index].append(+ StockBulkUpdateError(+ field="variantId",+ message="Invalid variantId.",+ code=StockBulkUpdateErrorCode.INVALID.value,+ )+ )+ errors_count += 1+ else:+ stock_input["variant_id"] = variant_db_id+ except Exception:+ index_error_map[index].append(+ StockBulkUpdateError(+ field="variantId",+ message="Invalid variantId.",+ code=StockBulkUpdateErrorCode.INVALID.value,+ )+ )+ errors_count += 1+ return errors_count++ @classmethod+ def validate_warehouse(+ cls,+ warehouse_id,+ external_ref,+ stock_input,+ index,+ index_error_map,+ ):+ errors_count = 0+ try:+ validate_one_of_args_is_in_mutation(+ "warehouse_id",+ warehouse_id,+ "warehouse_external_reference",+ external_ref,+ use_camel_case=True,+ )+ except ValidationError as exc:+ index_error_map[index].append(+ StockBulkUpdateError(+ message=exc.message,+ code=StockBulkUpdateErrorCode.INVALID.value,+ )+ )+ errors_count += 1++ if warehouse_id:+ try:+ type, warehouse_db_id = graphene.Node.from_global_id(warehouse_id)+ if type != "Warehouse":+ index_error_map[index].append(+ StockBulkUpdateError(+ field="warehouseId",+ message="Invalid warehouseId.",+ code=StockBulkUpdateErrorCode.INVALID.value,+ )+ )+ errors_count += 1+ else:+ stock_input["warehouse_id"] = warehouse_db_id+ except Exception:+ index_error_map[index].append(+ StockBulkUpdateError(+ field="warehouseId",+ message="Invalid warehouseId.",+ code=StockBulkUpdateErrorCode.INVALID.value,+ )+ )+ errors_count += 1+ return errors_count++ @classmethod+ def clean_stocks(cls, stocks_input, index_error_map):+ cleaned_inputs_map: dict = {}++ for index, stock_input in enumerate(stocks_input):+ base_error_count = 0+ variant_id = stock_input.get("variant_id")+ variant_external_ref = stock_input.get("variant_external_reference")+ warehouse_id = stock_input.get("warehouse_id")+ warehouse_external_ref = stock_input.get("warehouse_external_reference")++ base_error_count += cls.validate_variant(+ variant_id, variant_external_ref, stock_input, index, index_error_map+ )+ base_error_count += cls.validate_warehouse(+ warehouse_id,+ warehouse_external_ref,+ stock_input,+ index,+ index_error_map,+ )++ if stock_input.get("quantity") < 0:+ index_error_map[index].append(+ StockBulkUpdateError(+ field="quantity",+ message="Quantity should not be less than 0.",+ code=StockBulkUpdateErrorCode.INVALID.value,+ )+ )+ base_error_count += 1++ if base_error_count > 0:+ cleaned_inputs_map[index] = None+ else:+ cleaned_inputs_map[index] = stock_input++ return cleaned_inputs_map++ @classmethod+ def _get_stock(+ cls, variant_id, variant_external_ref, warehouse_id, warehouse_external_ref+ ):+ if variant_id and warehouse_id:+ return (+ lambda stock: str(stock.warehouse_id) == warehouse_id+ and str(stock.product_variant_id) == variant_id+ )+ elif variant_external_ref and warehouse_id:+ return (+ lambda stock: str(stock.warehouse_id) == warehouse_id+ and stock.variant_external_reference == variant_external_ref+ )++ elif variant_external_ref and warehouse_external_ref:+ return (+ lambda stock: str(stock.warehouse_external_reference)+ == warehouse_external_ref+ and stock.variant_external_reference == variant_external_ref+ )+ else:+ return (+ lambda stock: stock.warehouse_external_reference+ == warehouse_external_ref+ and str(stock.product_variant_id) == variant_id+ )++ @classmethod+ def update_stocks(cls, cleaned_inputs_map, index_error_map):+ instances_data_and_errors_list: list = []+ stocks_list = cls.get_stocks(cleaned_inputs_map)++ 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++ variant_id = cleaned_input.get("variant_id")+ warehouse_id = cleaned_input.get("warehouse_id")+ variant_external_ref = cleaned_input.get("variant_external_reference")+ warehouse_external_ref = cleaned_input.get("warehouse_external_reference")++ filter_stock = list(+ filter(+ cls._get_stock(+ variant_id,+ variant_external_ref,+ warehouse_id,+ warehouse_external_ref,+ ),+ stocks_list,+ )+ )+ if filter_stock:+ filter_stock[0].quantity = cleaned_input["quantity"]+ instances_data_and_errors_list.append(+ {"instance": filter_stock[0], "errors": index_error_map[index]}+ )+ else:+ index_error_map[index].append(+ StockBulkUpdateError(+ message="Stock was not found.",+ code=StockBulkUpdateErrorCode.NOT_FOUND.value,+ )+ )+ instances_data_and_errors_list.append(+ {"instance": None, "errors": index_error_map[index]}+ )++ return instances_data_and_errors_list++ @classmethod+ def get_stocks(cls, cleaned_inputs_map: dict) -> list[models.Stock]:+ lookup = Q()+ for stocks_input in cleaned_inputs_map.values():+ if not stocks_input:+ continue++ single_stock_lookup = Q()++ if variant_id := stocks_input.get("variant_id"):+ single_stock_lookup |= Q(product_variant_id=variant_id)+ else:+ single_stock_lookup |= Q(+ product_variant__external_reference=stocks_input.get(+ "variant_external_reference"+ )+ )++ if warehouse_id := stocks_input.get("warehouse_id"):+ single_stock_lookup |= Q(warehouse_id=warehouse_id)+ else:+ single_stock_lookup |= Q(+ warehouse__external_reference=stocks_input.get(+ "variant_external_reference"+ )+ )++ lookup |= single_stock_lookup++ stocks = models.Stock.objects.filter(lookup).annotate(+ variant_external_reference=F("product_variant__external_reference"),+ warehouse_external_reference=F("warehouse__external_reference"),+ )++ return list(stocks)++ @classmethod+ def save_stocks(cls, instances_data_with_errors_list):+ stocks_to_update = []++ for stock_data in instances_data_with_errors_list:+ stock = stock_data["instance"]+ if not stock:+ continue+ stocks_to_update.append(stock)++ models.Stock.objects.bulk_update(stocks_to_update, fields=["quantity"])++ return stocks_to_update++ @classmethod+ def post_save_actions(cls, info, instances):+ manager = get_plugin_manager_promise(info.context).get()+ for instance in instances:+ cls.call_event(manager.product_variant_stock_updated, instance)++ @classmethod+ def get_results(cls, instances_data_with_errors_list, reject_everything=False):+ if reject_everything:+ return [+ StockBulkResult(stock=None, errors=data.get("errors"))+ for data in instances_data_with_errors_list+ ]+ return [+ StockBulkResult(stock=data.get("instance"), errors=data.get("errors"))+ if data.get("instance")+ else StockBulkResult(stock=None, errors=data.get("errors"))+ for data in instances_data_with_errors_list+ ]++ @classmethod+ @traced_atomic_transaction()+ def perform_mutation(cls, _root, info, **data):+ error_policy = data["error_policy"]+ index_error_map: dict = defaultdict(list)+ cleaned_inputs_map = cls.clean_stocks(data["stocks"], index_error_map)++ instances_data_with_errors_list = cls.update_stocks(+ cleaned_inputs_map, index_error_map+ )++ if any([True if error else False for error in index_error_map.values()]):+ if error_policy == ErrorPolicyEnum.REJECT_EVERYTHING.value:+ results = cls.get_results(instances_data_with_errors_list, True)+ return StockBulkUpdate(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++ updated_stocks = cls.save_stocks(instances_data_with_errors_list)++ # prepare and return data+ results = cls.get_results(instances_data_with_errors_list)++ cls.post_save_actions(info, updated_stocks)++ return StockBulkUpdate(count=len(updated_stocks), results=results)diff --git a/saleor/graphql/warehouse/schema.py b/saleor/graphql/warehouse/schema.pyindex f35d89b789..b27b0be1bb 100644--- a/saleor/graphql/warehouse/schema.py+++ b/saleor/graphql/warehouse/schema.py@@ -12,6 +12,7 @@ from ..core.descriptions import ADDED_IN_310from ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.utils import from_global_id_or_errorfrom ..core.utils.resolvers import resolve_by_global_id_or_ext_ref+from .bulk_mutations import StockBulkUpdatefrom .filters import StockFilterInput, WarehouseFilterInputfrom .mutations import (WarehouseCreate,@@ -101,3 +102,7 @@ class StockQueries(graphene.ObjectType):qs = resolve_stocks()qs = filter_connection_queryset(qs, kwargs)return create_connection_slice(qs, info, kwargs, StockCountableConnection)+++class StockMutations(graphene.ObjectType):+ stock_bulk_update = StockBulkUpdate.Field()diff --git a/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.py b/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.pynew file mode 100644index 0000000000..afd62462ea--- /dev/null+++ b/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.py@@ -0,0 +1,105 @@+import graphene+import pytest++from .....warehouse.models import Stock+from ....tests.utils import get_graphql_content++STOCKS_BULK_UPDATE_MUTATION = """+ mutation StockBulkUpdate($stocks: [StockBulkUpdateInput!]!){+ stockBulkUpdate(stocks: $stocks){+ results{+ errors {+ field+ message+ code+ }+ stock{+ id+ quantity+ }+ }+ count+ }+ }+"""++[email protected]_queries(autouse=False)+def test_stocks_bulk_update_queries_count(+ staff_api_client,+ variant,+ variant_with_many_stocks,+ warehouse_no_shipping_zone,+ warehouse_with_external_ref,+ permission_manage_products,+ django_assert_num_queries,+ count_queries,+):+ # given+ variant_1 = variant_with_many_stocks+ variant_2 = variant++ stock_3 = Stock.objects.create(+ warehouse=warehouse_with_external_ref, product_variant=variant, quantity=4+ )+ stock_4 = Stock.objects.create(+ warehouse=warehouse_no_shipping_zone, product_variant=variant, quantity=4+ )++ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.pk)++ stocks = variant.stocks.all()+ stock_1 = stocks[0]+ stock_2 = stocks[1]++ new_quantity = 999++ warehouse_1_id = graphene.Node.to_global_id("Warehouse", stock_1.warehouse_id)+ warehouse_4_id = graphene.Node.to_global_id("Warehouse", stock_4.warehouse_id)++ stocks_input = [+ {+ "variantId": variant_1_id,+ "warehouseId": warehouse_1_id,+ "quantity": new_quantity,+ }+ ]++ # test number of queries when single object is updated+ with django_assert_num_queries(9):+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ STOCKS_BULK_UPDATE_MUTATION, {"stocks": stocks_input}+ )+ content = get_graphql_content(response)+ data = content["data"]["stockBulkUpdate"]+ assert data["count"] == 1++ stocks_input += [+ {+ "variantId": variant_1_id,+ "warehouseExternalReference": stock_2.warehouse.external_reference,+ "quantity": new_quantity,+ },+ {+ "variantExternalReference": variant_2.external_reference,+ "warehouseExternalReference": stock_3.warehouse.external_reference,+ "quantity": new_quantity,+ },+ {+ "variantExternalReference": variant_2.external_reference,+ "warehouseId": warehouse_4_id,+ "quantity": new_quantity,+ },+ ]++ # Test number of queries when multiple objects are updated+ with django_assert_num_queries(9):+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ STOCKS_BULK_UPDATE_MUTATION, {"stocks": stocks_input}+ )+ content = get_graphql_content(response)+ data = content["data"]["stockBulkUpdate"]+ assert data["count"] == 4diff --git a/saleor/graphql/warehouse/tests/test_stock_bulk_update.py b/saleor/graphql/warehouse/tests/test_stock_bulk_update.pynew file mode 100644index 0000000000..c2616c0044--- /dev/null+++ b/saleor/graphql/warehouse/tests/test_stock_bulk_update.py@@ -0,0 +1,418 @@+from unittest.mock import patch++import graphene++from ....warehouse.error_codes import StockBulkUpdateErrorCode+from ...tests.utils import get_graphql_content++STOCKS_BULK_UPDATE_MUTATION = """+ mutation StockBulkUpdate($stocks: [StockBulkUpdateInput!]!){+ stockBulkUpdate(stocks: $stocks){+ results{+ errors {+ field+ message+ code+ }+ stock{+ id+ quantity+ }+ }+ count+ }+ }+"""+++def test_stocks_bulk_update_using_ids(+ staff_api_client,+ variant_with_many_stocks,+ permission_manage_products,+):+ # given+ variant = variant_with_many_stocks+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ stocks = variant.stocks.all()+ stock_1 = stocks[0]+ stock_2 = stocks[1]+ new_quantity_1 = 999+ new_quantity_2 = 12++ assert stock_1.quantity != new_quantity_1+ assert stock_2.quantity != new_quantity_2++ warehouse_1_id = graphene.Node.to_global_id("Warehouse", stock_1.warehouse_id)+ warehouse_2_id = graphene.Node.to_global_id("Warehouse", stock_2.warehouse_id)++ stocks_input = [+ {+ "variantId": variant_id,+ "warehouseId": warehouse_1_id,+ "quantity": new_quantity_1,+ },+ {+ "variantId": variant_id,+ "warehouseId": warehouse_2_id,+ "quantity": new_quantity_2,+ },+ ]++ variables = {"stocks": stocks_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(STOCKS_BULK_UPDATE_MUTATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["stockBulkUpdate"]++ # then+ stock_1.refresh_from_db()+ stock_2.refresh_from_db()+ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]+ assert data["count"] == 2+ assert stock_1.quantity == new_quantity_1+ assert stock_2.quantity == new_quantity_2+++@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")+def test_stocks_bulk_update_send_stock_updated_event(+ product_variant_stock_update_webhook,+ staff_api_client,+ variant_with_many_stocks,+ permission_manage_products,+):+ # given+ variant = variant_with_many_stocks+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ stocks = variant.stocks.all()+ stock = stocks[0]+ new_quantity = 999++ assert stock.quantity != new_quantity++ warehouse_id = graphene.Node.to_global_id("Warehouse", stock.warehouse_id)++ stocks_input = [+ {"variantId": variant_id, "warehouseId": warehouse_id, "quantity": new_quantity}+ ]++ variables = {"stocks": stocks_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(STOCKS_BULK_UPDATE_MUTATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["stockBulkUpdate"]++ # then+ assert not data["results"][0]["errors"]+ assert data["count"] == 1+ assert product_variant_stock_update_webhook.call_count == 1+++def test_stocks_bulk_update_using_external_refs(+ staff_api_client,+ variant_with_many_stocks,+ permission_manage_products,+):+ # given+ variant = variant_with_many_stocks+ variant_external_reference = variant.external_reference+ stocks = variant.stocks.all()+ stock_1 = stocks[0]+ stock_2 = stocks[1]+ new_quantity_1 = 999+ new_quantity_2 = 12++ assert stock_1.quantity != new_quantity_1+ assert stock_2.quantity != new_quantity_2++ warehouse_1_external_reference = stock_1.warehouse.external_reference+ warehouse_2_external_reference = stock_2.warehouse.external_reference++ stocks_input = [+ {+ "variantExternalReference": variant_external_reference,+ "warehouseExternalReference": warehouse_1_external_reference,+ "quantity": new_quantity_1,+ },+ {+ "variantExternalReference": variant_external_reference,+ "warehouseExternalReference": warehouse_2_external_reference,+ "quantity": new_quantity_2,+ },+ ]++ variables = {"stocks": stocks_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(STOCKS_BULK_UPDATE_MUTATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["stockBulkUpdate"]++ # then+ stock_1.refresh_from_db()+ stock_2.refresh_from_db()+ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]+ assert data["count"] == 2+ assert stock_1.quantity == new_quantity_1+ assert stock_2.quantity == new_quantity_2+++def test_stocks_bulk_update_using_variant_id_and_warehouse_external_ref(+ staff_api_client,+ variant_with_many_stocks,+ permission_manage_products,+):+ # given+ variant = variant_with_many_stocks+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ stocks = variant.stocks.all()+ stock_1 = stocks[0]+ stock_2 = stocks[1]+ new_quantity_1 = 999+ new_quantity_2 = 12++ assert stock_1.quantity != new_quantity_1+ assert stock_2.quantity != new_quantity_2++ warehouse_1_external_reference = stock_1.warehouse.external_reference+ warehouse_2_external_reference = stock_2.warehouse.external_reference++ stocks_input = [+ {+ "variantId": variant_id,+ "warehouseExternalReference": warehouse_1_external_reference,+ "quantity": new_quantity_1,+ },+ {+ "variantId": variant_id,+ "warehouseExternalReference": warehouse_2_external_reference,+ "quantity": new_quantity_2,+ },+ ]++ variables = {"stocks": stocks_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(STOCKS_BULK_UPDATE_MUTATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["stockBulkUpdate"]++ # then+ stock_1.refresh_from_db()+ stock_2.refresh_from_db()+ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]+ assert data["count"] == 2+ assert stock_1.quantity == new_quantity_1+ assert stock_2.quantity == new_quantity_2+++def test_stocks_bulk_update_using_variant_external_ref_and_warehouse_id(+ staff_api_client,+ variant_with_many_stocks,+ permission_manage_products,+):+ # given+ variant = variant_with_many_stocks+ variant_external_reference = variant.external_reference++ stocks = variant.stocks.all()+ stock_1 = stocks[0]+ stock_2 = stocks[1]+ new_quantity_1 = 999+ new_quantity_2 = 12++ assert stock_1.quantity != new_quantity_1+ assert stock_2.quantity != new_quantity_2++ warehouse_1_id = graphene.Node.to_global_id("Warehouse", stock_1.warehouse_id)+ warehouse_2_id = graphene.Node.to_global_id("Warehouse", stock_2.warehouse_id)++ stocks_input = [+ {+ "variantExternalReference": variant_external_reference,+ "warehouseId": warehouse_1_id,+ "quantity": new_quantity_1,+ },+ {+ "variantExternalReference": variant_external_reference,+ "warehouseId": warehouse_2_id,+ "quantity": new_quantity_2,+ },+ ]++ variables = {"stocks": stocks_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(STOCKS_BULK_UPDATE_MUTATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["stockBulkUpdate"]++ # then+ stock_1.refresh_from_db()+ stock_2.refresh_from_db()+ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]+ assert data["count"] == 2+ assert stock_1.quantity == new_quantity_1+ assert stock_2.quantity == new_quantity_2+++def test_stocks_bulk_update_when_no_variant_args_provided(+ staff_api_client,+ variant_with_many_stocks,+ permission_manage_products,+):+ # given+ variant = variant_with_many_stocks+ stock = variant.stocks.first()++ warehouse_id = graphene.Node.to_global_id("Warehouse", stock.warehouse_id)++ stocks_input = [+ {"warehouseId": warehouse_id, "quantity": 10},+ ]++ variables = {"stocks": stocks_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(STOCKS_BULK_UPDATE_MUTATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["stockBulkUpdate"]++ # then+ assert data["count"] == 0+ assert data["results"][0]["errors"]+ error = data["results"][0]["errors"][0]+ assert error["message"] == (+ "At least one of arguments is required: 'variantId', "+ "'variantExternalReference'."+ )+++def test_stocks_bulk_update_when_invalid_variant_id_provided(+ staff_api_client,+ variant_with_many_stocks,+ permission_manage_products,+):+ # given+ variant = variant_with_many_stocks+ stock = variant.stocks.first()++ warehouse_id = graphene.Node.to_global_id("Warehouse", stock.warehouse_id)++ stocks_input = [+ {"variantId": "abcd", "warehouseId": warehouse_id, "quantity": 10},+ ]++ variables = {"stocks": stocks_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(STOCKS_BULK_UPDATE_MUTATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["stockBulkUpdate"]++ # then+ assert data["count"] == 0+ assert data["results"][0]["errors"]+ error = data["results"][0]["errors"][0]+ assert error["message"] == "Invalid variantId."+++def test_stocks_bulk_update_when_no_warehouse_args_provided(+ staff_api_client,+ variant_with_many_stocks,+ permission_manage_products,+):+ # given+ variant = variant_with_many_stocks+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ stocks_input = [+ {"variantId": variant_id, "quantity": 10},+ ]++ variables = {"stocks": stocks_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(STOCKS_BULK_UPDATE_MUTATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["stockBulkUpdate"]++ # then+ assert data["count"] == 0+ assert data["results"][0]["errors"]+ error = data["results"][0]["errors"][0]+ assert error["message"] == (+ "At least one of arguments is required: 'warehouseId', "+ "'warehouseExternalReference'."+ )+++def test_stocks_bulk_update_when_invalid_warehouse_id_provided(+ staff_api_client,+ variant_with_many_stocks,+ permission_manage_products,+):+ # given+ variant = variant_with_many_stocks+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)++ stocks_input = [+ {"variantId": variant_id, "warehouseId": "abcd", "quantity": 10},+ ]++ variables = {"stocks": stocks_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(STOCKS_BULK_UPDATE_MUTATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["stockBulkUpdate"]++ # then+ assert data["count"] == 0+ assert data["results"][0]["errors"]+ error = data["results"][0]["errors"][0]+ assert error["message"] == "Invalid warehouseId."+++def test_stocks_bulk_update_when_stock_not_exists(+ staff_api_client, variant_with_many_stocks, permission_manage_products, warehouse+):+ # given+ variant = variant_with_many_stocks+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ assert not variant.stocks.filter(warehouse=warehouse).exists()++ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)++ stocks_input = [+ {"variantId": variant_id, "warehouseId": warehouse_id, "quantity": 10},+ ]++ variables = {"stocks": stocks_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(STOCKS_BULK_UPDATE_MUTATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["stockBulkUpdate"]++ # then+ assert data["count"] == 0+ assert data["results"][0]["errors"]+ error = data["results"][0]["errors"][0]+ assert error["code"] == StockBulkUpdateErrorCode.NOT_FOUND.name+ assert error["message"] == "Stock was not found."diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 1f45c268cd..170f6f4546 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -2733,7 +2733,9 @@ def variant_without_inventory_tracking(@pytest.fixturedef variant(product, channel_USD) -> ProductVariant:- product_variant = ProductVariant.objects.create(product=product, sku="SKU_A")+ product_variant = ProductVariant.objects.create(+ product=product, sku="SKU_A", external_reference="SKU_A"+ )ProductVariantChannelListing.objects.create(variant=product_variant,channel=channel_USD,@@ -5930,6 +5932,21 @@ def warehouse(address, shipping_zone, channel_USD):return warehouse+def warehouse_with_external_ref(address, shipping_zone, channel_USD):+ warehouse = Warehouse.objects.create(+ address=address,+ name="Example Warehouse With Ref",+ slug="example-warehouse-with-ref",+ email="[email protected]",+ external_reference="example-warehouse-with-ref",+ )+ warehouse.shipping_zones.add(shipping_zone)+ warehouse.channels.add(channel_USD)+ warehouse.save()+ return warehouse++@pytest.fixturedef warehouse_JPY(address, shipping_zone_JPY, channel_JPY):warehouse = Warehouse.objects.create(@@ -5953,12 +5970,14 @@ def warehouses(address, address_usa, channel_USD):name="Warehouse PL",slug="warehouse1",email="[email protected]",+ external_reference="warehouse1",),Warehouse(address=address_usa.get_copy(),name="Warehouse USA",slug="warehouse2",email="[email protected]",+ external_reference="warehouse2",),])diff --git a/saleor/warehouse/error_codes.py b/saleor/warehouse/error_codes.pyindex 7ee54853aa..27d616488d 100644--- a/saleor/warehouse/error_codes.py+++ b/saleor/warehouse/error_codes.py@@ -17,3 +17,10 @@ class StockErrorCode(str, Enum):NOT_FOUND = "not_found"REQUIRED = "required"UNIQUE = "unique"+++class StockBulkUpdateErrorCode(str, Enum):+ GRAPHQL_ERROR = "graphql_error"+ INVALID = "invalid"+ NOT_FOUND = "not_found"+ REQUIRED = "required"