Skip to content

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

Add support for unhandled field trackInventoryByDefault . (#13497)

Smit Parmar7e07139ccb27
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f8be1b74fe..ac906eaf9d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -84,7 +84,7 @@ Shipping methods can be removed by the user after it has been assigned to a chec
- `accountUpdate`, `accountAddressCreate`, `accountAddressUpdate`, `addressCreate`, `AccountAddressUpdate`,
- `checkoutShippingAddressUpdate`, `checkoutBillingAddressUpdate`, `shopAddressUpdate`, `warehouseUpdate`
- Add `metadata` to `AddressInput` field
-
+- Add support for unhandled field `Shop.trackInventoryByDefault` for `productVariantCreate` and `productVariantBulkCreate` - #13492 by @Smit-Parmar
### Saleor Apps
- Introduce `Saleor-Schema-Version` HTTP header in app manifest fetching and app installation handshake requests. - #13075 by @przlada
diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
index 77f6a068af..f208a5ea8c 100644
--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
@@ -750,7 +750,7 @@ class ProductBulkCreate(BaseMutation):
AttributeAssignmentMixin.save(product, attributes)
if variants_input_data:
- variants = cls.save_variants(variants_input_data)
+ variants = cls.save_variants(info, variants_input_data)
return variants, updated_channels
@@ -775,8 +775,8 @@ class ProductBulkCreate(BaseMutation):
)
@classmethod
- def save_variants(cls, variants_input_data):
- return ProductVariantBulkCreate.save_variants(variants_input_data, None)
+ def save_variants(cls, info, variants_input_data):
+ return ProductVariantBulkCreate.save_variants(info, variants_input_data, None)
@classmethod
def prepare_media(cls, info, product, media_inputs, media_to_create):
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 e8d7a05f6d..0626c6403c 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
@@ -47,6 +47,7 @@ from ...core.types import (
from ...core.utils import get_duplicated_values
from ...core.validators import validate_price_precision
from ...plugins.dataloaders import get_plugin_manager_promise
+from ...shop.utils import get_track_inventory_by_default
from ..mutations.channels import ProductVariantChannelListingAddInput
from ..mutations.product.product_create import StockInput
from ..mutations.product_variant.product_variant_create import ProductVariantInput
@@ -853,7 +854,7 @@ class ProductVariantBulkCreate(BaseMutation):
@classmethod
@traced_atomic_transaction()
- def save_variants(cls, variants_data_with_errors_list, product):
+ def save_variants(cls, info, variants_data_with_errors_list, product):
variants_to_create: list = []
stocks_to_create: list = []
listings_to_create: list = []
@@ -864,7 +865,14 @@ class ProductVariantBulkCreate(BaseMutation):
if not variant:
continue
-
+ track_inventory_by_default = get_track_inventory_by_default(info)
+ track_inventory = variant_data["cleaned_input"].get("track_inventory")
+ if track_inventory_by_default is not None:
+ variant.track_inventory = (
+ track_inventory_by_default
+ if track_inventory is None
+ else track_inventory
+ )
variants_to_create.append(variant)
cleaned_input = variant_data["cleaned_input"]
@@ -881,7 +889,6 @@ class ProductVariantBulkCreate(BaseMutation):
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:
@@ -952,7 +959,7 @@ class ProductVariantBulkCreate(BaseMutation):
if data["errors"] and data["instance"]:
data["instance"] = None
- cls.save_variants(instances_data_with_errors_list, product)
+ cls.save_variants(info, instances_data_with_errors_list, product)
# prepare and return data
results = get_results(instances_data_with_errors_list)
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_create.py b/saleor/graphql/product/mutations/product_variant/product_variant_create.py
index 689fabbfe0..f5b71cb794 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_create.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_create.py
@@ -26,6 +26,7 @@ from ....core.types import BaseInputObjectType, NonNullList, ProductError
from ....core.utils import get_duplicated_values
from ....meta.inputs import MetadataInput
from ....plugins.dataloaders import get_plugin_manager_promise
+from ....shop.utils import get_track_inventory_by_default
from ....warehouse.types import Warehouse
from ...types import ProductVariant
from ...utils import (
@@ -59,7 +60,8 @@ class ProductVariantInput(BaseInputObjectType):
track_inventory = graphene.Boolean(
description=(
"Determines if the inventory of this variant should be tracked. If false, "
- "the quantity won't change when customers buy this item."
+ "the quantity won't change when customers buy this item. "
+ "If the field is not provided, `Shop.trackInventoryByDefault` will be used."
)
)
weight = WeightScalar(description="Weight of the Product Variant.", required=False)
@@ -294,9 +296,21 @@ class ProductVariantCreate(ModelMutation):
}
)
+ @classmethod
+ def set_track_inventory(cls, _info, instance, cleaned_input):
+ track_inventory_by_default = get_track_inventory_by_default(_info)
+ track_inventory = cleaned_input.get("track_inventory")
+ if track_inventory_by_default is not None:
+ instance.track_inventory = (
+ track_inventory_by_default
+ if track_inventory is None
+ else track_inventory
+ )
+
@classmethod
def save(cls, info: ResolveInfo, instance, cleaned_input):
new_variant = instance.pk is None
+ cls.set_track_inventory(info, instance, cleaned_input)
with traced_atomic_transaction():
instance.save()
if not instance.product.default_variant:
@@ -307,7 +321,6 @@ class ProductVariantCreate(ModelMutation):
stocks = cleaned_input.get("stocks")
if stocks:
cls.create_variant_stocks(instance, stocks)
-
attributes = cleaned_input.get("attributes")
if attributes:
AttributeAssignmentMixin.save(instance, attributes)
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_update.py b/saleor/graphql/product/mutations/product_variant/product_variant_update.py
index e97bfb0ffe..135d6f4561 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_update.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_update.py
@@ -127,6 +127,12 @@ class ProductVariantUpdate(ProductVariantCreate, ModelWithExtRefMutation):
)
return instance
+ @classmethod
+ def set_track_inventory(cls, _info, instance, cleaned_input):
+ track_inventory = cleaned_input.get("track_inventory")
+ if track_inventory is not None:
+ instance.track_inventory = track_inventory
+
@classmethod
def perform_mutation( # type: ignore[override]
cls,
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
index 887c034932..6ecc7f450c 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
@@ -37,6 +37,7 @@ PRODUCT_VARIANT_BULK_CREATE_MUTATION = """
id
name
sku
+ trackInventory
attributes{
attribute {
slug
@@ -2235,3 +2236,31 @@ def test_product_variant_bulk_create_two_variants_duplicated_one_attribute_value
assert not data["results"][0]["errors"]
assert data["count"] == 1
assert product_variant_count + 1 == ProductVariant.objects.count()
+
+
+def test_product_variant_bulk_create_with_default_track_inventory(
+ staff_api_client,
+ product_with_variant_with_two_attributes,
+ permission_manage_products,
+ site_settings,
+):
+ # given
+ product = product_with_variant_with_two_attributes
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variants = [{"sku": str(uuid4())[:12], "attributes": []}]
+ 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_CREATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkCreate"]
+ # then
+ assert not data["results"][0]["errors"]
+ assert data["count"] == 1
+ assert (
+ data["results"][0]["productVariant"]["trackInventory"]
+ == site_settings.track_inventory_by_default
+ )
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
index 7000410995..e8aaca8379 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
@@ -1775,6 +1775,7 @@ VARIANT_CREATE_MUTATION = """
{
productVariant {
id
+ trackInventory
}
errors {
field,
@@ -1887,3 +1888,26 @@ def test_create_product_variant_with_non_unique_external_reference(
error["message"]
== "Product variant with this External reference already exists."
)
+
+
+def test_variant_create_product_with_default_track_inventory(
+ product_with_product_attributes,
+ staff_api_client,
+ permission_manage_products,
+ site_settings,
+):
+ product = product_with_product_attributes
+
+ prod_id = graphene.Node.to_global_id("Product", product.pk)
+ input = {"sku": "my-sku", "product": prod_id, "attributes": []}
+ response = staff_api_client.post_graphql(
+ VARIANT_CREATE_MUTATION,
+ variables={"input": input},
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantCreate"]
+ assert (
+ data["productVariant"]["trackInventory"]
+ == site_settings.track_inventory_by_default
+ )
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index b2adfe225d..95b9cc1cc2 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -276,7 +276,12 @@ class ProductVariant(ChannelContextTypeWithMetadata[models.ProductVariant]):
description="The product to which the variant belongs.",
)
track_inventory = graphene.Boolean(
- required=True, description="Whether the inventory of the variant is tracked."
+ required=True,
+ description=(
+ "Determines if the inventory of this variant should be tracked. If false, "
+ "the quantity won't change when customers buy this item. "
+ "If the field is not provided, `Shop.trackInventoryByDefault` will be used."
+ ),
)
quantity_limit_per_customer = graphene.Int(
description="The maximum quantity of this variant that a customer can purchase."
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 102328ff59..7afb5353b3 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -7130,7 +7130,9 @@ type ProductVariant implements Node & ObjectWithMetadata @doc(category: "Product
"""The product to which the variant belongs."""
product: Product!
- """Whether the inventory of the variant is tracked."""
+ """
+ Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item. If the field is not provided, `Shop.trackInventoryByDefault` will be used.
+ """
trackInventory: Boolean!
"""The maximum quantity of this variant that a customer can purchase."""
@@ -9581,7 +9583,9 @@ type Shop implements ObjectWithMetadata {
"""
fulfillmentAllowUnpaid: Boolean!
- """Enable inventory tracking."""
+ """
+ This field is used as a default value for `ProductVariant.trackInventory`.
+ """
trackInventoryByDefault: Boolean
"""Default weight unit."""
@@ -19413,7 +19417,9 @@ input ShopSettingsInput {
"""SEO description."""
description: String
- """Enable inventory tracking."""
+ """
+ This field is used as a default value for `ProductVariant.trackInventory`.
+ """
trackInventoryByDefault: Boolean
"""Default weight unit."""
@@ -20896,7 +20902,7 @@ input ProductVariantBulkCreateInput @doc(category: "Products") {
name: String
"""
- Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item.
+ Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item. If the field is not provided, `Shop.trackInventoryByDefault` will be used.
"""
trackInventory: Boolean
@@ -21701,7 +21707,7 @@ input ProductVariantCreateInput @doc(category: "Products") {
name: String
"""
- Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item.
+ Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item. If the field is not provided, `Shop.trackInventoryByDefault` will be used.
"""
trackInventory: Boolean
@@ -21915,7 +21921,7 @@ input ProductVariantBulkUpdateInput @doc(category: "Products") {
name: String
"""
- Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item.
+ Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item. If the field is not provided, `Shop.trackInventoryByDefault` will be used.
"""
trackInventory: Boolean
@@ -22138,7 +22144,7 @@ input ProductVariantInput @doc(category: "Products") {
name: String
"""
- Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item.
+ Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item. If the field is not provided, `Shop.trackInventoryByDefault` will be used.
"""
trackInventory: Boolean
diff --git a/saleor/graphql/shop/mutations/shop_settings_update.py b/saleor/graphql/shop/mutations/shop_settings_update.py
index 77f29ab11d..4ece24e518 100644
--- a/saleor/graphql/shop/mutations/shop_settings_update.py
+++ b/saleor/graphql/shop/mutations/shop_settings_update.py
@@ -29,7 +29,10 @@ class ShopSettingsInput(graphene.InputObjectType):
header_text = graphene.String(description="Header text.")
description = graphene.String(description="SEO description.")
track_inventory_by_default = graphene.Boolean(
- description="Enable inventory tracking."
+ description=(
+ "This field is used as a default value for "
+ "`ProductVariant.trackInventory`."
+ )
)
default_weight_unit = WeightUnitsEnum(description="Default weight unit.")
automatic_fulfillment_digital_products = graphene.Boolean(
diff --git a/saleor/graphql/shop/tests/test_shop_utils.py b/saleor/graphql/shop/tests/test_shop_utils.py
index 4070107cdf..109a2d2990 100644
--- a/saleor/graphql/shop/tests/test_shop_utils.py
+++ b/saleor/graphql/shop/tests/test_shop_utils.py
@@ -1,6 +1,6 @@
from django_countries import countries
-from ..utils import get_countries_codes_list
+from ..utils import get_countries_codes_list, get_track_inventory_by_default
def test_get_countries_codes_list(shipping_zones):
@@ -36,3 +36,8 @@ def test_get_countries_codes_list_false(shipping_zones):
assert not any(
country in countries_list_false for country in fixture_countries_code_set
)
+
+
+def test_get_track_inventory_by_default(dummy_info):
+ result = get_track_inventory_by_default(dummy_info)
+ assert result is True or result is None
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index 8a128c725b..e405e6d166 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -248,7 +248,10 @@ class Shop(graphene.ObjectType):
required=True,
)
track_inventory_by_default = graphene.Boolean(
- description="Enable inventory tracking."
+ description=(
+ "This field is used as a default value for "
+ "`ProductVariant.trackInventory`."
+ )
)
default_weight_unit = WeightUnitsEnum(description="Default weight unit.")
translation = TranslationField(ShopTranslation, type_name="shop", resolver=None)
diff --git a/saleor/graphql/shop/utils.py b/saleor/graphql/shop/utils.py
index 6af450912b..08de323ad3 100644
--- a/saleor/graphql/shop/utils.py
+++ b/saleor/graphql/shop/utils.py
@@ -3,6 +3,7 @@ from typing import Optional
from django_countries import countries
from ...shipping.models import ShippingZone
+from ..site.dataloaders import get_site_promise
def get_countries_codes_list(attached_to_shipping_zones: Optional[bool] = None):
@@ -26,3 +27,10 @@ def get_countries_codes_list(attached_to_shipping_zones: Optional[bool] = None):
return all_countries_codes - covered_countries_codes
return all_countries_codes
+
+
+def get_track_inventory_by_default(info):
+ site = get_site_promise(info.context).get()
+ if site is not None and site.settings is not None:
+ return site.settings.track_inventory_by_default
+ return None
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 6598329946..883cbfdc85 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -7386,3 +7386,13 @@ def transaction_session_response():
"externalUrl": "http://127.0.0.1:9090/external-reference",
"message": "Message related to the payment",
}
+
+
+class Info:
+ def __init__(self, request):
+ self.context = request
+
+
+def dummy_info(request):
+ return Info(request)