Skip to content

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

Quantity should be created with stock

Mira Szewczyk3bf6c713314e
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index e1b03334ba..578494499f 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -28,6 +28,7 @@ from ....product.utils.attributes import (
associate_attribute_values_to_instance,
generate_name_for_variant,
)
+from ....warehouse.management import set_stock_quantity
from ...core.mutations import (
BaseMutation,
ClearMetaBaseMutation,
@@ -888,9 +889,12 @@ class ProductCreate(ModelMutation):
"track_inventory", site_settings.track_inventory_by_default
)
sku = cleaned_input.get("sku")
- models.ProductVariant.objects.create(
+ variant = models.ProductVariant.objects.create(
product=instance, track_inventory=track_inventory, sku=sku
)
+ quantity = cleaned_input.get("quantity")
+ if quantity is not None:
+ set_stock_quantity(variant, info.context.country, quantity)
attributes = cleaned_input.get("attributes")
if attributes:
@@ -945,8 +949,8 @@ class ProductUpdate(ProductCreate):
variant.track_inventory = cleaned_input["track_inventory"]
update_fields.append("track_inventory")
if "quantity" in cleaned_input:
- variant.quantity = cleaned_input["quantity"]
- update_fields.append("quantity")
+ quantity = cleaned_input.get("quantity")
+ set_stock_quantity(variant, info.context.country, quantity)
if "sku" in cleaned_input:
variant.sku = cleaned_input["sku"]
update_fields.append("sku")
@@ -1156,6 +1160,9 @@ class ProductVariantCreate(ModelMutation):
instance.save()
# Recalculate the "minimal variant price" for the parent product
update_product_minimal_variant_price_task.delay(instance.product_id)
+ quantity = cleaned_input.get("quantity")
+ if quantity is not None:
+ set_stock_quantity(instance, info.context.country, quantity)
attributes = cleaned_input.get("attributes")
if attributes:
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 3b3affbc80..ef38609608 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -24,6 +24,7 @@ from ....warehouse import models as stock_models
from ....warehouse.availability import (
get_available_quantity,
get_available_quantity_for_customer,
+ get_quantity_allocated,
is_product_in_stock,
is_variant_in_stock,
)
@@ -373,8 +374,7 @@ class ProductVariant(CountableDjangoObjectType, MetadataObjectType):
@permission_required(ProductPermissions.MANAGE_PRODUCTS)
def resolve_quantity_allocated(root: models.ProductVariant, info):
country = info.context.country
- stock = stock_models.Stock.objects.get_variant_stock_for_country(country, root)
- return stock.quantity_allocated
+ return get_quantity_allocated(root, country)
@staticmethod
@permission_required(ProductPermissions.MANAGE_PRODUCTS)
diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.py
index 9fcd3eade4..f6b4eba9c0 100644
--- a/saleor/warehouse/availability.py
+++ b/saleor/warehouse/availability.py
@@ -34,6 +34,14 @@ def get_available_quantity(variant: "ProductVariant", country_code: str) -> int:
return stock.quantity_available
+def get_quantity_allocated(variant: "ProductVariant", country_code: str) -> int:
+ try:
+ stock = Stock.objects.get_variant_stock_for_country(country_code, variant)
+ except Stock.DoesNotExist:
+ return 0
+ return stock.quantity_allocated
+
+
def is_variant_in_stock(variant: "ProductVariant", country_code: str) -> bool:
"""Check if variant is available in given country."""
stock = Stock.objects.get_variant_stock_for_country(country_code, variant)
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index 22d4098427..fae512b7c9 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -38,7 +38,7 @@ def increase_stock(
allocate: bool = False,
commit: bool = True,
) -> Stock:
- stock = Stock.objects.select_for_update(of=("self",)).get_variant_stock_for_country(
+ stock = Stock.objects.select_for_update(of=("self",)).get_or_create_for_country(
country_code, variant
)
stock.increase_stock(quantity, allocate=allocate, commit=commit)
@@ -54,3 +54,16 @@ def decrease_stock(
)
stock.decrease_stock(quantity, commit=commit)
return stock
+
+
+def set_stock_quantity(
+ variant: "ProductVariant", country_code: str, quantity: int, commit: bool = True
+) -> Stock:
+ stock = Stock.objects.select_for_update(of=("self",)).get_or_create_for_country(
+ country_code, variant
+ )
+ stock.quantity = quantity
+ if commit:
+ stock.save(update_fields=["quantity"])
+ return stock
diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.py
index 79a9af59c7..a516c23ad9 100644
--- a/saleor/warehouse/models.py
+++ b/saleor/warehouse/models.py
@@ -1,17 +1,15 @@
import itertools
import uuid
-from typing import Optional, Set
+from typing import Set
-from django.contrib.sites.models import Site
-from django.db import models, transaction
-from django.db.models import F, QuerySet
+from django.db import models
+from django.db.models import F
from django.utils.translation import pgettext_lazy
from ..account.models import Address
from ..core.exceptions import InsufficientStock
from ..product.models import ProductVariant
from ..shipping.models import ShippingZone
-from ..site.models import SiteSettings
class WarehouseQueryset(models.QuerySet):
@@ -19,23 +17,7 @@ class WarehouseQueryset(models.QuerySet):
return self.select_related("address").prefetch_related("shipping_zones")
def for_country(self, country: str):
- return self.filter(shipping_zone__countries__contains=country)
-
- @transaction.atomic
- def create_for_shipping_zones(
- self,
- address: Optional[Address] = None,
- shipping_zones: Optional[QuerySet] = None,
- ):
- if shipping_zones is None:
- shipping_zones = ShippingZone.objects.all()
- current_settings = SiteSettings.objects.get(site=Site.objects.get_current())
- address = address or current_settings.company_address
- if address is None:
- address = Address.objects.create()
- warehouse = self.create(address=address)
- warehouse.shipping_zones.add(*shipping_zones.values_list("pk", flat=True))
- return warehouse
+ return self.prefetch_data().get(shipping_zones__countries__contains=country)
class Warehouse(models.Model):
@@ -96,6 +78,15 @@ class StockQuerySet(models.QuerySet):
):
return self.for_country(country_code).get(product_variant=product_variant)
+ def get_or_create_for_country(
+ self, country_code: str, product_variant: ProductVariant
+ ):
+ try:
+ return self.get_variant_stock_for_country(country_code, product_variant)
+ except Stock.DoesNotExist:
+ warehouse = Warehouse.objects.for_country(country_code)
+ return self.create(product_variant=product_variant, warehouse=warehouse)
+
class Stock(models.Model):
warehouse = models.ForeignKey(Warehouse, null=False, on_delete=models.PROTECT)
diff --git a/tests/api/test_core.py b/tests/api/test_core.py
index de9cf71686..082995824b 100644
--- a/tests/api/test_core.py
+++ b/tests/api/test_core.py
@@ -154,7 +154,9 @@ def test_total_count_query(api_client, product):
assert content["data"]["products"]["totalCount"] == Product.objects.count()
-def test_mutation_decimal_input(staff_api_client, variant, permission_manage_products):
+def test_mutation_decimal_input(
+ staff_api_client, variant, stock, permission_manage_products
+):
query = """
mutation decimalInput($id: ID!, $cost: Decimal) {
productVariantUpdate(id: $id,
@@ -174,6 +176,7 @@ def test_mutation_decimal_input(staff_api_client, variant, permission_manage_pro
variables = {
"id": graphene.Node.to_global_id("ProductVariant", variant.id),
"cost": 12.12,
+ "quantity": 17,
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index 63edbbf357..6a14553901 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -27,6 +27,7 @@ from saleor.product.models import (
)
from saleor.product.tasks import update_variants_names
from saleor.product.utils.attributes import associate_attribute_values_to_instance
+from saleor.warehouse.models import Stock
from tests.api.utils import get_graphql_content
from tests.utils import create_image, create_pdf_file_with_image_ext
@@ -2997,3 +2998,160 @@ def test_product_filter_by_attribute_values(
}
}
]
+
+
+MUTATION_CREATE_PRODUCT_QUANTITY = """
+mutation createProduct(
+ $productType: ID!,
+ $category: ID!
+ $name: String!,
+ $sku: String,
+ $quantity: Int,
+ $basePrice: Decimal!
+ $trackInventory: Boolean)
+ {
+ productCreate(
+ input: {
+ category: $category,
+ productType: $productType,
+ name: $name,
+ sku: $sku,
+ trackInventory: $trackInventory,
+ quantity: $quantity,
+ basePrice: $basePrice,
+ })
+ {
+ product {
+ id
+ name
+ variants{
+ id
+ sku
+ trackInventory
+ quantity
+ }
+ }
+ errors {
+ message
+ field
+ }
+ }
+ }
+ """
+
+
+def test_create_product_without_variant_creates_stock(
+ staff_api_client,
+ category,
+ permission_manage_products,
+ product_type_without_variant,
+ warehouse,
+):
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ product_type_id = graphene.Node.to_global_id(
+ "ProductType", product_type_without_variant.pk
+ )
+ variables = {
+ "category": category_id,
+ "productType": product_type_id,
+ "name": "Test",
+ "quantity": 8,
+ "sku": "23434",
+ "trackInventory": True,
+ "basePrice": Decimal("19"),
+ }
+ response = staff_api_client.post_graphql(
+ MUTATION_CREATE_PRODUCT_QUANTITY,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+ quantity = content["data"]["productCreate"]["product"]["variants"][0]["quantity"]
+ assert quantity == 8
+
+
+def test_create_product_with_variants_does_not_create_stock(
+ staff_api_client, category, product_type, permission_manage_products
+):
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ variables = {
+ "category": category_id,
+ "productType": product_type_id,
+ "name": "Test",
+ "quantity": 8,
+ "sku": "23434",
+ "trackInventory": True,
+ "basePrice": Decimal("19"),
+ }
+ response = staff_api_client.post_graphql(
+ MUTATION_CREATE_PRODUCT_QUANTITY,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+ variants = content["data"]["productCreate"]["product"]["variants"]
+ assert len(variants) == 0
+ assert not Stock.objects.exists()
+
+
+def test_create_without_variants_failes_without_warehouses(
+ staff_api_client, category, product_type_without_variant, permission_manage_products
+):
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ product_type_id = graphene.Node.to_global_id(
+ "ProductType", product_type_without_variant.pk
+ )
+ variables = {
+ "category": category_id,
+ "productType": product_type_id,
+ "name": "Test",
+ "quantity": 8,
+ "sku": "23434",
+ "trackInventory": True,
+ "basePrice": Decimal("19"),
+ }
+ response = staff_api_client.post_graphql(
+ MUTATION_CREATE_PRODUCT_QUANTITY,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response, ignore_errors=True)
+ errors = content["errors"]
+ assert len(errors) == 1
+ assert errors[0]["message"] == "Warehouse matching query does not exist."
+
+
+MUTATION_UPDATE_PRODUCT_QUANTITY = """
+mutation updateProduct(
+ $productId: ID!,
+
+ $quantity: Int,
+ ) {
+ productUpdate(
+ id: $productId,
+ input: {
+ quantity: $quantity
+ }) {
+ product {
+ variants {
+ quantity
+ }
+ }
+}}
+"""
+
+
+def test_update_product_without_variants_updates_stock(
+ staff_api_client, product_with_default_variant, permission_manage_products
+):
+ product_id = graphene.Node.to_global_id("Product", product_with_default_variant.pk)
+ stock = product_with_default_variant.variants.first().stock.first()
+ variables = {"productId": product_id, "quantity": 17}
+ staff_api_client.post_graphql(
+ MUTATION_UPDATE_PRODUCT_QUANTITY,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ stock.refresh_from_db()
+ assert stock.quantity == 17
diff --git a/tests/api/test_variant.py b/tests/api/test_variant.py
index 92be9b7a6f..3f107490ef 100644
--- a/tests/api/test_variant.py
+++ b/tests/api/test_variant.py
@@ -8,6 +8,7 @@ from graphene.utils.str_converters import to_camel_case
from saleor.product.error_codes import ProductErrorCode
from saleor.product.models import ProductVariant
from saleor.product.utils.attributes import associate_attribute_values_to_instance
+from saleor.warehouse.models import Stock, Warehouse
from tests.api.utils import get_graphql_content
@@ -1153,3 +1154,84 @@ def test_product_variant_bulk_create_two_variants_duplicated_one_attribute_value
assert not data["bulkProductErrors"]
assert data["count"] == 1
assert product_variant_count + 1 == ProductVariant.objects.count()
+
+
+MUTATION_UPDATE_VARIANT_QUANTITY = """
+ mutation updateVariant(
+ $id: ID!,
+ $quantity: Int
+ ) {
+ productVariantUpdate(id: $id, input: {quantity: $quantity}) {
+ productVariant {
+ id
+ quantity
+ }
+ }
+ }
+"""
+
+
+def test_update_variant_and_set_quantity_creates_stock(
+ staff_api_client, variant, permission_manage_products, warehouse
+):
+ assert variant.stock.count() == 0
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "quantity": 70}
+ staff_api_client.post_graphql(
+ MUTATION_UPDATE_VARIANT_QUANTITY,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ assert variant.stock.count() == 1
+
+
+def test_update_variant_fails_when_there_is_no_warehouse_available(
+ staff_api_client, variant, permission_manage_products
+):
+ Stock.objects.all().delete()
+ Warehouse.objects.all().delete()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "quantity": 70}
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_VARIANT_QUANTITY,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response, ignore_errors=True)
+ errors = content["errors"]
+ assert len(errors) == 1
+ assert variant.stock.count() == 0
+
+
+def test_update_variant_sets_quantity_in_stock(
+ staff_api_client, variant, stock, permission_manage_products
+):
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {
+ "id": variant_id,
+ "quantity": 8,
+ }
+ staff_api_client.post_graphql(
+ MUTATION_UPDATE_VARIANT_QUANTITY,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ stock.refresh_from_db()
+ assert stock.quantity == 8
+
+
+def test_update_variant_changes_stock_only_when_quantity_is_passed(
+ staff_api_client, variant, stock, permission_manage_products, monkeypatch
+):
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ stock_quantity = stock.quantity
+ variables = {
+ "id": variant_id,
+ }
+ staff_api_client.post_graphql(
+ MUTATION_UPDATE_VARIANT_QUANTITY,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ stock.refresh_from_db()
+ assert stock.quantity == stock_quantity