Skip to content

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

Add stocks input to ProductVariantBulkCreate

IKarbowiakdbf81bd29056
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index eb1b6a67f1..9b3133b198 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -137,6 +137,11 @@ class BulkProductError(ProductError):
index = graphene.Int(
description="Index of an input list item that caused the error."
)
+ warehouses = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of warehouse IDs which causes the error.",
+ required=False,
+ )
class ShopError(Error):
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index fb1e2bf6af..d524047975 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -24,6 +24,7 @@ from ...core.types.common import (
ProductError,
StockError,
)
+from ...core.utils import get_duplicated_values
from ...utils import resolve_global_ids_to_primary_keys
from ...warehouse.types import Warehouse
from ..mutations.products import (
@@ -113,6 +114,11 @@ class ProductVariantBulkCreateInput(ProductVariantInput):
required=True,
description="List of attributes specific to this variant.",
)
+ stocks = graphene.List(
+ graphene.NonNull(StockInput),
+ description=("Stocks of a product available for sale."),
+ required=False,
+ )
sku = graphene.String(required=True, description="Stock keeping unit.")
@@ -148,7 +154,14 @@ class ProductVariantBulkCreate(BaseMutation):
error_type_field = "bulk_product_errors"
@classmethod
- def clean_input(cls, info, instance: models.ProductVariant, data: dict):
+ def clean_variant_input(
+ cls,
+ info,
+ instance: models.ProductVariant,
+ data: dict,
+ errors: dict,
+ variant_index: int,
+ ):
cleaned_input = ModelMutation.clean_input(
info, instance, data, input_cls=ProductVariantBulkCreateInput
)
@@ -156,26 +169,20 @@ class ProductVariantBulkCreate(BaseMutation):
cost_price_amount = cleaned_input.pop("cost_price", None)
if cost_price_amount is not None:
if cost_price_amount < 0:
- raise ValidationError(
- {
- "costPrice": ValidationError(
- "Product price cannot be lower than 0.",
- code=ProductErrorCode.INVALID.value,
- )
- }
+ errors["costPrice"] = ValidationError(
+ "Product price cannot be lower than 0.",
+ code=ProductErrorCode.INVALID.value,
+ params={"index": variant_index},
)
cleaned_input["cost_price_amount"] = cost_price_amount
price_override_amount = cleaned_input.pop("price_override", None)
if price_override_amount is not None:
if price_override_amount < 0:
- raise ValidationError(
- {
- "priceOverride": ValidationError(
- "Product price cannot be lower than 0.",
- code=ProductErrorCode.INVALID.value,
- )
- }
+ errors["priceOverride"] = ValidationError(
+ "Product price cannot be lower than 0.",
+ code=ProductErrorCode.INVALID.value,
+ params={"index": variant_index},
)
cleaned_input["price_override_amount"] = price_override_amount
@@ -186,10 +193,26 @@ class ProductVariantBulkCreate(BaseMutation):
attributes, data["product_type"]
)
except ValidationError as exc:
- raise ValidationError({"attributes": exc})
+ exc.params = {"index": variant_index}
+ errors["attributes"] = exc
+
+ stocks = cleaned_input.get("stocks")
+ if stocks:
+ cls.clean_stocks(stocks, errors, variant_index)
return cleaned_input
+ @classmethod
+ def clean_stocks(cls, stocks_data, errors, variant_index):
+ warehouse_ids = [stock["warehouse"] for stock in stocks_data]
+ duplicates = get_duplicated_values(warehouse_ids)
+ if duplicates:
+ errors["stocks"] = ValidationError(
+ "Duplicated warehouse ID.",
+ code=ProductErrorCode.DUPLICATED,
+ params={"warehouses": duplicates, "index": variant_index},
+ )
+
@classmethod
def add_indexes_to_errors(cls, index, error, error_dict):
"""Append errors with index in params to mutation error dict."""
@@ -253,11 +276,11 @@ class ProductVariantBulkCreate(BaseMutation):
)
cleaned_input = None
- try:
- variant_data["product_type"] = product.product_type
- cleaned_input = cls.clean_input(info, None, variant_data)
- except ValidationError as exc:
- cls.add_indexes_to_errors(index, exc, errors)
+ variant_data["product_type"] = product.product_type
+ cleaned_input = cls.clean_variant_input(
+ info, None, variant_data, errors, index
+ )
+
cleaned_inputs.append(cleaned_input if cleaned_input else None)
if not variant_data.sku:
@@ -273,6 +296,18 @@ class ProductVariantBulkCreate(BaseMutation):
), "There should be the same number of instances and cleaned inputs."
for instance, cleaned_input in zip(instances, cleaned_inputs):
cls.save(info, instance, cleaned_input)
+ cls.create_variant_stocks(instance, cleaned_input)
+
+ @classmethod
+ def create_variant_stocks(cls, variant, cleaned_input):
+ stocks = cleaned_input.get("stocks")
+ if not stocks:
+ return
+ warehouse_ids = [stock["warehouse"] for stock in stocks]
+ warehouses = cls.get_nodes_or_error(
+ warehouse_ids, "warehouse", only_type=Warehouse
+ )
+ create_stocks(variant, stocks, warehouses)
@classmethod
def perform_mutation(cls, root, info, **data):
@@ -408,17 +443,20 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):
warehouses = cls.get_nodes_or_error(
warehouse_ids, "warehouse", only_type=Warehouse
)
- cls.create_variant_stocks(variant, stocks, warehouses)
+ cls.update_or_create_variant_stocks(variant, stocks, warehouses)
return cls(product_variant=variant)
@classmethod
- def create_variant_stocks(cls, variant, stocks, warehouses):
- for stock_data, warehouse in zip(stocks, warehouses):
+ @transaction.atomic
+ def update_or_create_variant_stocks(cls, variant, stocks_data, warehouses):
+ stocks = []
+ for stock_data, warehouse in zip(stocks_data, warehouses):
stock, _ = warehouse_models.Stock.objects.get_or_create(
product_variant=variant, warehouse=warehouse
)
stock.quantity = stock_data["quantity"]
- stock.save(update_fields=["quantity"])
+ stocks.append(stock)
+ warehouse_models.Stock.objects.bulk_update(stocks, ["quantity"])
class ProductVariantStocksDelete(BaseMutation):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 2a8b4abb63..4c072ecb7b 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -496,6 +496,7 @@ type BulkProductError {
message: String
code: ProductErrorCode!
index: Int
+ warehouses: [ID!]
}
type BulkStockError {
@@ -3622,6 +3623,7 @@ input ProductVariantBulkCreateInput {
sku: String!
trackInventory: Boolean
weight: WeightScalar
+ stocks: [StockInput!]
}
type ProductVariantBulkDelete {
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index 7e7a067197..f55ec459e2 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -13,6 +13,7 @@ from prices import Money
from saleor.core.taxes import TaxType
from saleor.graphql.core.enums import ReportingPeriod
+from saleor.graphql.product.bulk_mutations.products import ProductVariantStocksUpdate
from saleor.graphql.product.utils import create_stocks
from saleor.plugins.manager import PluginsManager
from saleor.product import AttributeInputType
@@ -3923,3 +3924,44 @@ def test_create_stocks(variant, warehouse):
assert {stock.quantity for stock in variant.stocks.all()} == {
data["quantity"] for data in stocks_data
}
+
+
+def test_update_or_create_variant_stocks(variant, warehouses):
+ Stock.objects.create(
+ product_variant=variant,
+ warehouse=warehouses[0],
+ quantity=5,
+ )
+ stocks_data = [
+ {"quantity": 10, "warehouse": "123"},
+ {"quantity": 10, "warehouse": "321"},
+ ]
+
+ ProductVariantStocksUpdate.update_or_create_variant_stocks(
+ variant, stocks_data, warehouses
+ )
+
+ variant.refresh_from_db()
+ assert variant.stocks.count() == 2
+ assert {stock.warehouse.pk for stock in variant.stocks.all()} == {
+ warehouse.pk for warehouse in warehouses
+ }
+ assert {stock.quantity for stock in variant.stocks.all()} == {
+ data["quantity"] for data in stocks_data
+ }
+
+
+def test_update_or_create_variant_stocks_empty_stocks_data(variant, warehouses):
+ Stock.objects.create(
+ product_variant=variant,
+ warehouse=warehouses[0],
+ quantity=5,
+ )
+
+ ProductVariantStocksUpdate.update_or_create_variant_stocks(variant, [], warehouses)
+
+ variant.refresh_from_db()
+ assert variant.stocks.count() == 1
+ stock = variant.stocks.first()
+ assert stock.warehouse == warehouses[0]
+ assert stock.quantity == 5
diff --git a/tests/api/test_variant.py b/tests/api/test_variant.py
index 3b95a50ddd..c34abdcf77 100644
--- a/tests/api/test_variant.py
+++ b/tests/api/test_variant.py
@@ -837,10 +837,17 @@ PRODUCT_VARIANT_BULK_CREATE_MUTATION = """
message
code
index
+ warehouses
}
productVariants{
id
sku
+ stocks {
+ warehouse {
+ slug
+ }
+ quantity
+ }
}
count
}
@@ -964,6 +971,136 @@ def test_product_variant_bulk_create_with_new_attribute_value(
assert attribute_value_count + 1 == size_attribute.values.count()
+def test_product_variant_bulk_create_stocks_input(
+ staff_api_client, product, permission_manage_products, warehouses, size_attribute
+):
+ product_variant_count = ProductVariant.objects.count()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ attribute_value_count = size_attribute.values.count()
+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+ attribute_value = size_attribute.values.last()
+ variants = [
+ {
+ "sku": str(uuid4())[:12],
+ "stocks": [
+ {
+ "quantity": 10,
+ "warehouse": graphene.Node.to_global_id(
+ "Warehouse", warehouses[0].pk
+ ),
+ }
+ ],
+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],
+ },
+ {
+ "sku": str(uuid4())[:12],
+ "attributes": [{"id": size_attribute_id, "values": ["Test-attribute"]}],
+ "stocks": [
+ {
+ "quantity": 15,
+ "warehouse": graphene.Node.to_global_id(
+ "Warehouse", warehouses[0].pk
+ ),
+ },
+ {
+ "quantity": 15,
+ "warehouse": graphene.Node.to_global_id(
+ "Warehouse", warehouses[1].pk
+ ),
+ },
+ ],
+ },
+ ]
+
+ variables = {"productId": product_id, "variants": variants}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkCreate"]
+ assert not data["bulkProductErrors"]
+ assert data["count"] == 2
+ assert product_variant_count + 2 == ProductVariant.objects.count()
+ assert attribute_value_count + 1 == size_attribute.values.count()
+
+ expected_result = [
+ {
+ "sku": variants[0]["sku"],
+ "stocks": [
+ {
+ "warehouse": {"slug": warehouses[0].slug},
+ "quantity": variants[0]["stocks"][0]["quantity"],
+ }
+ ],
+ },
+ {
+ "sku": variants[1]["sku"],
+ "stocks": [
+ {
+ "warehouse": {"slug": warehouses[0].slug},
+ "quantity": variants[1]["stocks"][0]["quantity"],
+ },
+ {
+ "warehouse": {"slug": warehouses[1].slug},
+ "quantity": variants[1]["stocks"][1]["quantity"],
+ },
+ ],
+ },
+ ]
+ for variant_data in data["productVariants"]:
+ variant_data.pop("id")
+ assert variant_data in expected_result
+
+
+def test_product_variant_bulk_create_duplicated_warehouses(
+ staff_api_client, product, permission_manage_products, warehouses, size_attribute
+):
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+ attribute_value = size_attribute.values.last()
+ warehouse1_id = graphene.Node.to_global_id("Warehouse", warehouses[0].pk)
+ variants = [
+ {
+ "sku": str(uuid4())[:12],
+ "stocks": [
+ {
+ "quantity": 10,
+ "warehouse": graphene.Node.to_global_id(
+ "Warehouse", warehouses[1].pk
+ ),
+ }
+ ],
+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],
+ },
+ {
+ "sku": str(uuid4())[:12],
+ "attributes": [{"id": size_attribute_id, "values": ["Test-attribute"]}],
+ "stocks": [
+ {"quantity": 15, "warehouse": warehouse1_id},
+ {"quantity": 15, "warehouse": warehouse1_id},
+ ],
+ },
+ ]
+
+ variables = {"productId": product_id, "variants": variants}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkCreate"]
+ errors = data["bulkProductErrors"]
+
+ assert not data["productVariants"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "stocks"
+ assert error["index"] == 1
+ assert error["code"] == ProductErrorCode.DUPLICATED.name
+ assert error["warehouses"] == [warehouse1_id]
+
+
def test_product_variant_bulk_create_duplicated_sku(
staff_api_client,
product,
@@ -1082,12 +1219,14 @@ def test_product_variant_bulk_create_many_errors(
"index": 2,
"code": ProductErrorCode.UNIQUE.name,
"message": ANY,
+ "warehouses": None,
},
{
"field": "attributes",
"index": 3,
"code": ProductErrorCode.NOT_FOUND.name,
"message": ANY,
+ "warehouses": None,
},
]
for expected_error in expected_errors: