Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Move allocations to relation betwen order linie and sock
fowczrekbcb293d2a023
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 07b02a2755..0a10eba738 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -741,7 +741,7 @@ def create_order(for line in order_lines: # type: OrderLinevariant = line.variantif variant and variant.track_inventory:- allocate_stock(variant, checkout.get_country(), line.quantity)+ allocate_stock(line, checkout.get_country(), line.quantity)# Add gift cards to the orderfor gift_card in checkout.gift_cards.select_for_update():diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 37e7d6fbd2..db1052c140 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -67,7 +67,7 @@ from ...product.thumbnails import (create_product_thumbnails,)from ...shipping.models import ShippingMethod, ShippingMethodType, ShippingZone-from ...warehouse.management import increase_stock+from ...warehouse.management import deallocate_stock, increase_stockfrom ...warehouse.models import Stock, Warehousefake = Factory.create()@@ -456,15 +456,10 @@ def create_order_lines(order, discounts, how_many=10):)variants_iter = itertools.cycle(variants)lines = []- stocks = []- country = order.shipping_method.shipping_zone.countries[0]for dummy in range(how_many):variant = next(variants_iter)product = variant.productquantity = random.randrange(1, 5)- stocks.append(- increase_stock(variant, country, quantity, allocate=True, commit=False)- )unit_price = variant.get_price(discounts)unit_price = TaxedMoney(net=unit_price, gross=unit_price)lines.append(@@ -480,13 +475,14 @@ def create_order_lines(order, discounts, how_many=10):tax_rate=0,))- Stock.objects.bulk_update(stocks, ["quantity", "quantity_allocated"])lines = OrderLine.objects.bulk_create(lines)manager = get_plugins_manager()+ country = order.shipping_method.shipping_zone.countries[0]for line in lines:unit_price = manager.calculate_order_line_unit(line)line.unit_price = unit_priceline.tax_rate = unit_price.tax / unit_price.net+ increase_stock(line, country, line.quantity, allocate=True)OrderLine.objects.bulk_update(lines,["unit_price_net_amount", "unit_price_gross_amount", "currency", "tax_rate"],@@ -504,9 +500,7 @@ def create_fulfillments(order):line.quantity_fulfilled = quantityline.save(update_fields=["quantity_fulfilled"])- Stock.objects.get_or_create_for_country(- country, line.variant- ).deallocate_stock(quantity)+ deallocate_stock(line, country, quantity)update_order_status(order)diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex eb9c95ef1b..d2edfa803e 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -274,10 +274,10 @@ class DraftOrderComplete(BaseMutation):for line in order:try:check_stock_quantity(line.variant, country, line.quantity)- allocate_stock(line.variant, country, line.quantity)+ allocate_stock(line, country, line.quantity)except InsufficientStock:available_stock = get_available_quantity(line.variant, country)- allocate_stock(line.variant, country, available_stock)+ allocate_stock(line, country, available_stock)oversold_items.append(str(line))order_created(order, user=info.context.user, from_draft=True)diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.pyindex 23a5d61e58..013dc04294 100644--- a/saleor/graphql/product/filters.py+++ b/saleor/graphql/product/filters.py@@ -3,7 +3,8 @@ from typing import Dict, List, Optionalimport django_filtersimport graphene-from django.db.models import Q, Subquery, Sum+from django.db.models import F, Q, Subquery, Sum+from django.db.models.functions import Coalescefrom graphene_django.filter import GlobalIDFilter, GlobalIDMultipleChoiceFilterfrom ...product.filters import filter_products_by_attributes_values@@ -115,10 +116,13 @@ def filter_products_by_collections(qs, collections):def filter_products_by_stock_availability(qs, stock_availability):total_stock = (Stock.objects.select_related("product_variant")- .annotate_available_quantity().values("product_variant__product_id")- .annotate(total_quantity=Sum("available_quantity"))- .filter(total_quantity__lte=0)+ .annotate(+ total_quantity_allocated=Coalesce(Sum("allocations__quantity_allocated"), 0)+ )+ .annotate(total_quantity=Coalesce(Sum("quantity"), 0))+ .annotate(total_available=F("total_quantity") - F("total_quantity_allocated"))+ .filter(total_available__lte=0).values_list("product_variant__product_id", flat=True))if stock_availability == StockAvailability.IN_STOCK:diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex 8a7e975469..d0cf939db7 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -20,7 +20,6 @@ from ....product.utils.availability import (get_variant_availability,)from ....product.utils.costs import get_margin_for_variant, get_product_costs_data-from ....warehouse import models as stock_modelsfrom ....warehouse.availability import (get_available_quantity,get_available_quantity_for_customer,@@ -278,14 +277,7 @@ class ProductVariant(CountableDjangoObjectType):@staticmethoddef resolve_stock_quantity(root: models.ProductVariant, info):- country = info.context.country- try:- stock = stock_models.Stock.objects.get_variant_stock_for_country(- country, root- )- except stock_models.Stock.DoesNotExist:- return 0- return get_available_quantity_for_customer(stock)+ return get_available_quantity_for_customer(root, info.context.country)@staticmethod@gql_optimizer.resolver_hints(diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 311d4b72ef..0def7269d1 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -4415,9 +4415,9 @@ type Stock implements Node {warehouse: Warehouse!productVariant: ProductVariant!quantity: Int!- quantityAllocated: Int!id: ID!stockQuantity: Int!+ quantityAllocated: Int!}enum StockAvailability {@@ -4453,7 +4453,6 @@ enum StockErrorCode {input StockFilterInput {quantity: Float- quantityAllocated: Floatsearch: String}diff --git a/saleor/graphql/warehouse/filters.py b/saleor/graphql/warehouse/filters.pyindex d9f39ee967..1f41e26207 100644--- a/saleor/graphql/warehouse/filters.py+++ b/saleor/graphql/warehouse/filters.py@@ -62,7 +62,7 @@ class StockFilter(django_filters.FilterSet):class Meta:model = Stock- fields = ["quantity", "quantity_allocated"]+ fields = ["quantity"]class StockFilterInput(FilterInputObjectType):diff --git a/saleor/graphql/warehouse/types.py b/saleor/graphql/warehouse/types.pyindex b40acce9de..ee20136199 100644--- a/saleor/graphql/warehouse/types.py+++ b/saleor/graphql/warehouse/types.py@@ -1,8 +1,10 @@import graphene+from django.conf import settings+from django.db.models import Sum+from django.db.models.functions import Coalescefrom ...core.permissions import ProductPermissionsfrom ...warehouse import models-from ...warehouse.availability import get_available_quantity_for_customerfrom ..account.enums import CountryCodeEnumfrom ..core.connection import CountableDjangoObjectTypefrom ..decorators import permission_required@@ -80,7 +82,11 @@ class Stock(CountableDjangoObjectType):@staticmethoddef resolve_stock_quantity(root, *_args):- return get_available_quantity_for_customer(root)+ quantity_allocated = root.allocations.aggregate(+ quantity_allocated=Coalesce(Sum("quantity_allocated"), 0)+ )["quantity_allocated"]+ available_quantity = max(root.quantity - quantity_allocated, 0)+ return min(available_quantity, settings.MAX_CHECKOUT_LINE_QUANTITY)@staticmethod@permission_required(ProductPermissions.MANAGE_PRODUCTS)@@ -90,4 +96,6 @@ class Stock(CountableDjangoObjectType):@staticmethod@permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_quantity_allocated(root, *_args):- return root.quantity_allocated+ return root.allocations.aggregate(+ quantity_allocated=Coalesce(Sum("quantity_allocated"), 0)+ )["quantity_allocated"]diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 3224eddb5a..708dd81c42 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -210,7 +210,7 @@ def fulfill_order_line(order_line, quantity):"""Fulfill order line with given quantity."""country = get_order_country(order_line.order)if order_line.variant and order_line.variant.track_inventory:- decrease_stock(order_line.variant, country, quantity)+ decrease_stock(order_line, country, quantity)order_line.quantity_fulfilled += quantityorder_line.save(update_fields=["quantity_fulfilled"])diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 665947b1a3..1c97100759 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -223,7 +223,7 @@ def add_variant_to_order()if variant.track_inventory and track_inventory:- allocate_stock(variant, country, quantity)+ allocate_stock(line, country, quantity)return line@@ -278,9 +278,9 @@ def restock_order_lines(order):for line in order:if line.variant and line.variant.track_inventory:if line.quantity_unfulfilled > 0:- deallocate_stock(line.variant, country, line.quantity_unfulfilled)+ deallocate_stock(line, country, line.quantity_unfulfilled)if line.quantity_fulfilled > 0:- increase_stock(line.variant, country, line.quantity_fulfilled)+ increase_stock(line, country, line.quantity_fulfilled)if line.quantity_fulfilled > 0:line.quantity_fulfilled = 0@@ -292,9 +292,7 @@ def restock_fulfillment_lines(fulfillment):country = get_order_country(fulfillment.order)for line in fulfillment:if line.order_line.variant and line.order_line.variant.track_inventory:- increase_stock(- line.order_line.variant, country, line.quantity, allocate=True- )+ increase_stock(line.order_line, country, line.quantity, allocate=True)def sum_order_totals(qs):diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.pyindex cc66da90c0..9d817056a3 100644--- a/saleor/warehouse/availability.py+++ b/saleor/warehouse/availability.py@@ -2,6 +2,7 @@ from typing import TYPE_CHECKING, Optionalfrom django.conf import settingsfrom django.db.models import Sum+from django.db.models.functions import Coalescefrom ..core.exceptions import InsufficientStockfrom .models import Stock@@ -10,6 +11,17 @@ if TYPE_CHECKING:from ..product.models import Product, ProductVariant+def _get_quantity_allocated(stock: Stock) -> int:+ return stock.allocations.aggregate(+ quantity_allocated=Coalesce(Sum("quantity_allocated"), 0)+ )["quantity_allocated"]+++def _get_available_quantity(stock: Stock) -> int:+ quantity_allocated = _get_quantity_allocated(stock)+ return max(stock.quantity - quantity_allocated, 0)++def check_stock_quantity(variant: "ProductVariant", country_code: str, quantity: int):"""Validate if there is stock available for given variant in given country.@@ -21,7 +33,7 @@ def check_stock_quantity(variant: "ProductVariant", country_code: str, quantity:except Stock.DoesNotExist:raise InsufficientStock(variant)- if variant.track_inventory and quantity > stock.quantity_available:+ if variant.track_inventory and quantity > _get_available_quantity(stock):raise InsufficientStock(variant)@@ -31,7 +43,18 @@ def get_available_quantity(variant: "ProductVariant", country_code: str) -> int:stock = Stock.objects.get_variant_stock_for_country(country_code, variant)except Stock.DoesNotExist:return 0- return stock.quantity_available+ return _get_available_quantity(stock)+++def get_available_quantity_for_customer(+ variant: "ProductVariant", country_code: str+) -> int:+ """Return maximum checkout line quantity."""+ try:+ stock = Stock.objects.get_variant_stock_for_country(country_code, variant)+ except Stock.DoesNotExist:+ return 0+ return min(_get_available_quantity(stock), settings.MAX_CHECKOUT_LINE_QUANTITY)def get_quantity_allocated(variant: "ProductVariant", country_code: str) -> int:@@ -39,7 +62,7 @@ def get_quantity_allocated(variant: "ProductVariant", country_code: str) -> int:stock = Stock.objects.get_variant_stock_for_country(country_code, variant)except Stock.DoesNotExist:return 0- return stock.quantity_allocated+ return _get_quantity_allocated(stock)def is_variant_in_stock(variant: "ProductVariant", country_code: str) -> bool:@@ -89,8 +112,3 @@ def products_with_low_stock(threshold: Optional[int] = None):.annotate(total_stock=Sum("quantity")))return stocks.filter(total_stock__lte=threshold).distinct()---def get_available_quantity_for_customer(stock: Stock) -> int:- """Return maximum checkout line quantity."""- return min(stock.quantity_available, settings.MAX_CHECKOUT_LINE_QUANTITY)diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex fae512b7c9..40bc404399 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -2,57 +2,78 @@ from typing import TYPE_CHECKINGfrom django.db import transaction-from .models import Stock+from .models import Allocation, Stockif TYPE_CHECKING:+ from ..order.models import OrderLinefrom ..product.models import ProductVariant+def _allocate_stock(stock: Stock, order_line: "OrderLine", quantity: int) -> Allocation:+ allocation = (+ stock.allocations.select_for_update(of=("self",))+ .filter(order_line=order_line)+ .first()+ )+ if allocation:+ allocation.allocate_stock(quantity, commit=True)+ else:+ allocation = Allocation.objects.create(+ order_line=order_line, stock=stock, quantity_allocated=quantity+ )+ return allocation+++def _deallocate_stock(+ stock: Stock, order_line: "OrderLine", quantity: int+) -> Allocation:+ allocation = stock.allocations.select_for_update(of=("self",)).get(+ order_line=order_line+ )+ allocation.deallocate_stock(quantity, commit=True)+ return allocation++@transaction.atomicdef allocate_stock(- variant: "ProductVariant", country_code: str, quantity: int, commit: bool = True-) -> Stock:+ order_line: "OrderLine", country_code: str, quantity: int+) -> Allocation:stock = Stock.objects.select_for_update(of=("self",)).get_variant_stock_for_country(- country_code, variant+ country_code, order_line.variant)- stock.allocate_stock(quantity, commit=commit)- return stock+ return _allocate_stock(stock, order_line, quantity)@transaction.atomicdef deallocate_stock(- variant: "ProductVariant", country_code: str, quantity: int, commit: bool = True-) -> Stock:- stock = Stock.objects.select_for_update(of=("self",)).get_variant_stock_for_country(- country_code, variant+ order_line: "OrderLine", country_code: str, quantity: int+) -> Allocation:+ stock = Stock.objects.get_variant_stock_for_country(+ country_code, order_line.variant)- stock.deallocate_stock(quantity, commit=commit)- return stock+ return _deallocate_stock(stock, order_line, quantity)@transaction.atomicdef increase_stock(- variant: "ProductVariant",- country_code: str,- quantity: int,- allocate: bool = False,- commit: bool = True,+ order_line: "OrderLine", country_code: str, quantity: int, allocate: bool = False,) -> Stock:stock = Stock.objects.select_for_update(of=("self",)).get_or_create_for_country(- country_code, variant+ country_code, order_line.variant)- stock.increase_stock(quantity, allocate=allocate, commit=commit)+ stock.increase_stock(quantity, commit=True)+ if allocate:+ _allocate_stock(stock, order_line, quantity)return stock@transaction.atomic-def decrease_stock(- variant: "ProductVariant", country_code: str, quantity: int, commit: bool = True-) -> Stock:+def decrease_stock(order_line: "OrderLine", country_code: str, quantity: int) -> Stock:stock = Stock.objects.select_for_update(of=("self",)).get_variant_stock_for_country(- country_code, variant+ country_code, order_line.variant)- stock.decrease_stock(quantity, commit=commit)+ stock.decrease_stock(quantity, commit=True)+ _deallocate_stock(stock, order_line, quantity)return stockdiff --git a/saleor/warehouse/migrations/0007_auto_20200406_0341.py b/saleor/warehouse/migrations/0007_auto_20200406_0341.pynew file mode 100644index 0000000000..193e4bb47e--- /dev/null+++ b/saleor/warehouse/migrations/0007_auto_20200406_0341.py@@ -0,0 +1,78 @@+# Generated by Django 3.0.4 on 2020-04-06 08:41++import django.db.models.deletion+from django.db import migrations, models+++def create_allocation(+ product_variant, warehouse, order_line, quantity_allocated, Allocation+):+ stock = product_variant.stocks.get(warehouse=warehouse)+ Allocation.objects.create(+ order_line=order_line, stock=stock, quantity_allocated=quantity_allocated+ )+++def create_allocations(apps, schema_editor):+ Allocation = apps.get_model("warehouse", "Allocation")+ OrderLine = apps.get_model("order", "OrderLine")+ Warehouse = apps.get_model("warehouse", "Warehouse")+ for warehouse in Warehouse.objects.iterator():+ shipping_zone_pk = warehouse.shipping_zones.first().pk+ for order_line in OrderLine.objects.filter(+ order__shipping_method__shipping_zone__pk=shipping_zone_pk,+ ).iterator():+ quantity_unfulfilled = order_line.quantity - order_line.quantity_fulfilled+ if quantity_unfulfilled > 0 and order_line.variant:+ create_allocation(+ order_line.variant,+ warehouse,+ order_line,+ quantity_unfulfilled,+ Allocation,+ )+++class Migration(migrations.Migration):++ dependencies = [+ ("order", "0080_invoice"),+ ("warehouse", "0006_auto_20200228_0519"),+ ]++ operations = [+ migrations.CreateModel(+ name="Allocation",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("quantity_allocated", models.PositiveIntegerField(default=0)),+ (+ "order_line",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="allocations",+ to="order.OrderLine",+ ),+ ),+ (+ "stock",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="allocations",+ to="warehouse.Stock",+ ),+ ),+ ],+ options={"unique_together": {("order_line", "stock")}},+ ),+ migrations.RunPython(create_allocations),+ migrations.RemoveField(model_name="stock", name="quantity_allocated",),+ ]diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex a42bcd21c7..5f2aba7b73 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -3,10 +3,11 @@ import uuidfrom typing import Setfrom django.db import models-from django.db.models import F+from django.db.models import F, Sum+from django.db.models.functions import Coalescefrom ..account.models import Address-from ..core.exceptions import InsufficientStock+from ..order.models import OrderLinefrom ..product.models import ProductVariantfrom ..shipping.models import ShippingZone@@ -53,7 +54,10 @@ class Warehouse(models.Model):class StockQuerySet(models.QuerySet):def annotate_available_quantity(self):- return self.annotate(available_quantity=F("quantity") - F("quantity_allocated"))+ return self.annotate(+ available_quantity=F("quantity")+ - Coalesce(Sum("allocations__quantity_allocated"), 0)+ )def for_country(self, country_code: str):query_warehouse = models.Subquery(@@ -90,7 +94,6 @@ class Stock(models.Model):ProductVariant, null=False, on_delete=models.CASCADE, related_name="stocks")quantity = models.PositiveIntegerField(default=0)- quantity_allocated = models.PositiveIntegerField(default=0)objects = StockQuerySet.as_manager()@@ -100,13 +103,37 @@ class Stock(models.Model):def __str__(self):return f"{self.product_variant} - {self.warehouse.name}"- @property- def quantity_available(self) -> int:- return max(self.quantity - self.quantity_allocated, 0)+ def increase_stock(self, quantity: int, commit: bool = True):+ """Return given quantity of product to a stock."""+ self.quantity = F("quantity") + quantity+ if commit:+ self.save(update_fields=["quantity"])++ def decrease_stock(self, quantity: int, commit: bool = True):+ self.quantity = F("quantity") - quantity+ if commit:+ self.save(update_fields=["quantity"])+++class Allocation(models.Model):+ order_line = models.ForeignKey(+ OrderLine,+ null=False,+ blank=False,+ on_delete=models.CASCADE,+ related_name="allocations",+ )+ stock = models.ForeignKey(+ Stock,+ null=False,+ blank=False,+ on_delete=models.CASCADE,+ related_name="allocations",+ )+ quantity_allocated = models.PositiveIntegerField(default=0)- def check_quantity(self, quantity: int):- if quantity > self.quantity_available:- raise InsufficientStock(self)+ class Meta:+ unique_together = [["order_line", "stock"]]def allocate_stock(self, quantity: int, commit: bool = True):self.quantity_allocated = F("quantity_allocated") + quantity@@ -117,21 +144,3 @@ class Stock(models.Model):self.quantity_allocated = F("quantity_allocated") - quantityif commit:self.save(update_fields=["quantity_allocated"])-- def increase_stock(- self, quantity: int, allocate: bool = False, commit: bool = True- ):- """Return given quantity of product to a stock."""- self.quantity = F("quantity") + quantity- update_fields = ["quantity"]- if allocate:- self.quantity_allocated = F("quantity_allocated") + quantity- update_fields.append("quantity_allocated")- if commit:- self.save(update_fields=update_fields)-- def decrease_stock(self, quantity: int, commit: bool = True):- self.quantity = F("quantity") - quantity- self.quantity_allocated = F("quantity_allocated") - quantity- if commit:- self.save(update_fields=["quantity", "quantity_allocated"])diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.pyindex 482b727dcf..f5d79f1df6 100644--- a/tests/api/test_checkout.py+++ b/tests/api/test_checkout.py@@ -26,7 +26,9 @@ from saleor.payment.interface import GatewayResponsefrom saleor.shipping import ShippingMethodTypefrom saleor.shipping.models import ShippingMethodfrom saleor.warehouse.models import Stock-from tests.api.utils import assert_no_permission, get_graphql_content++from ..utils import get_available_quantity_for_stock+from .utils import assert_no_permission, get_graphql_content@pytest.fixture@@ -377,7 +379,7 @@ def test_checkout_create_check_lines_quantity(shipping_address = graphql_address_datavariables = {"checkoutInput": {- "lines": [{"quantity": 3, "variantId": variant_id}],+ "lines": [{"quantity": 16, "variantId": variant_id}],"email": test_email,"shippingAddress": shipping_address,}@@ -387,7 +389,7 @@ def test_checkout_create_check_lines_quantity(content = get_graphql_content(response)data = content["data"]["checkoutCreate"]assert data["errors"][0]["message"] == (- "Could not add item Test product (SKU_A). Only 2 remaining in stock."+ "Could not add item Test product (SKU_A). Only 15 remaining in stock.")assert data["errors"][0]["field"] == "quantity"@@ -631,13 +633,13 @@ def test_checkout_lines_add_check_lines_quantity(user_api_client, checkout, stocvariables = {"checkoutId": checkout_id,- "lines": [{"variantId": variant_id, "quantity": 3}],+ "lines": [{"variantId": variant_id, "quantity": 16}],}response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)content = get_graphql_content(response)data = content["data"]["checkoutLinesAdd"]assert data["errors"][0]["message"] == (- "Could not add item Test product (SKU_A). Only 2 remaining in stock."+ "Could not add item Test product (SKU_A). Only 15 remaining in stock.")assert data["errors"][0]["field"] == "quantity"@@ -739,14 +741,14 @@ def test_checkout_lines_update_check_lines_quantity(variables = {"checkoutId": checkout_id,- "lines": [{"variantId": variant_id, "quantity": 10}],+ "lines": [{"variantId": variant_id, "quantity": 11}],}response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)content = get_graphql_content(response)data = content["data"]["checkoutLinesUpdate"]assert data["errors"][0]["message"] == (- "Could not add item Test product (123). Only 9 remaining in stock."+ "Could not add item Test product (123). Only 10 remaining in stock.")assert data["errors"][0]["field"] == "quantity"@@ -1559,7 +1561,7 @@ def test_checkout_complete_insufficient_stock(checkout = checkout_with_itemcheckout_line = checkout.lines.first()stock = Stock.objects.get(product_variant=checkout_line.variant)- quantity_available = stock.quantity_available+ quantity_available = get_available_quantity_for_stock(stock)checkout_line.quantity = quantity_available + 1checkout_line.save()checkout.shipping_address = addressdiff --git a/tests/api/test_fulfillment.py b/tests/api/test_fulfillment.pyindex 73298dc909..38093ac870 100644--- a/tests/api/test_fulfillment.py+++ b/tests/api/test_fulfillment.py@@ -6,6 +6,7 @@ import pytestfrom saleor.core.permissions import OrderPermissionsfrom saleor.order.events import OrderEventsfrom saleor.order.models import FulfillmentStatus+from saleor.warehouse.models import Allocationfrom tests.api.utils import assert_no_permission, get_graphql_contentCREATE_FULFILLMENT_QUERY = """@@ -324,6 +325,11 @@ def test_create_digital_fulfillment(order_line.variant = digital_content.product_variantorder_line.save()+ stock = digital_content.product_variant.stocks.first()+ Allocation.objects.create(+ order_line=order_line, stock=stock, quantity_allocated=order_line.quantity+ )+second_line = order.lines.last()first_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)second_line_id = graphene.Node.to_global_id("OrderLine", second_line.id)diff --git a/tests/api/test_order.py b/tests/api/test_order.pyindex fe970b7928..4fe2c5259b 100644--- a/tests/api/test_order.py+++ b/tests/api/test_order.py@@ -29,6 +29,7 @@ from saleor.payment.models import Paymentfrom saleor.shipping.models import ShippingMethodfrom saleor.warehouse.models import Stock+from ..utils import get_available_quantity_for_stockfrom .utils import assert_no_permission, get_graphql_content@@ -798,8 +799,8 @@ def test_draft_order_complete(line_1.save(update_fields=["quantity"])stock_1 = Stock.objects.get(product_variant=line_1.variant)stock_2 = Stock.objects.get(product_variant=line_2.variant)- assert stock_1.quantity_available >= line_1.quantity- assert stock_2.quantity_available < line_2.quantity+ assert get_available_quantity_for_stock(stock_1) >= line_1.quantity+ assert get_available_quantity_for_stock(stock_2) < line_2.quantityorder_id = graphene.Node.to_global_id("Order", order.id)variables = {"id": order_id}diff --git a/tests/api/test_product.py b/tests/api/test_product.pyindex f4a3c5fdc5..a9b362a221 100644--- a/tests/api/test_product.py+++ b/tests/api/test_product.py@@ -29,7 +29,7 @@ from saleor.product.models import ()from saleor.product.tasks import update_variants_namesfrom saleor.product.utils.attributes import associate_attribute_values_to_instance-from saleor.warehouse.models import Stock, Warehouse+from saleor.warehouse.models import Allocation, Stock, Warehousefrom tests.api.utils import get_graphql_contentfrom tests.utils import create_image, create_pdf_file_with_image_ext@@ -454,6 +454,29 @@ def test_products_query_with_filter_search_by_sku(assert products[0]["node"]["name"] == product_with_default_variant.name+def test_products_query_with_filter_stock_availability(+ query_products_with_filter,+ staff_api_client,+ product,+ order_line,+ permission_manage_products,+):+ stock = product.variants.first().stocks.first()+ Allocation.objects.create(+ order_line=order_line, stock=stock, quantity_allocated=stock.quantity+ )+ variables = {"filter": {"stockAvailability": "OUT_OF_STOCK"}}+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(query_products_with_filter, variables)+ content = get_graphql_content(response)+ product_id = graphene.Node.to_global_id("Product", product.id)+ products = content["data"]["products"]["edges"]++ assert len(products) == 1+ assert products[0]["node"]["id"] == product_id+ assert products[0]["node"]["name"] == product.name++@pytest.mark.parametrize("quantity_input, warehouse_indexes, count, indexes_of_products_in_result",[diff --git a/tests/api/test_stock.py b/tests/api/test_stock.pyindex 38d65c6b44..cdb7d4fa14 100644--- a/tests/api/test_stock.py+++ b/tests/api/test_stock.py@@ -2,7 +2,9 @@ import graphenefrom saleor.core.permissions import ProductPermissionsfrom saleor.warehouse.models import Stock-from tests.api.utils import assert_no_permission, get_graphql_content++from ..utils import get_quantity_allocated_for_stock+from .utils import assert_no_permission, get_graphql_contentQUERY_STOCK = """query stock($id: ID!) {@@ -79,7 +81,7 @@ def test_query_stock(staff_api_client, stock, permission_manage_products):)assert content_stock["warehouse"]["name"] == stock.warehouse.nameassert content_stock["quantity"] == stock.quantity- assert content_stock["quantityAllocated"] == stock.quantity_allocated+ assert content_stock["quantityAllocated"] == get_quantity_allocated_for_stock(stock)def test_query_stocks_requires_permissions(staff_api_client):@@ -119,31 +121,6 @@ def test_query_stocks_with_filters_quantity(assert total_count == Stock.objects.filter(quantity=max(quantities)).count()-def test_query_stocks_with_filters_quantity_allocated(- staff_api_client, stock, permission_manage_products-):- staff_api_client.user.user_permissions.add(permission_manage_products)- quantities = Stock.objects.all().values_list("quantity_allocated", flat=True)- sum_quantities = sum(quantities)- variables = {"filter": {"quantityAllocated": sum_quantities}}- response = staff_api_client.post_graphql(- QUERY_STOCKS_WITH_FILTERS, variables=variables- )- content = get_graphql_content(response)- total_count = content["data"]["stocks"]["totalCount"]- assert total_count == 0-- variables = {"filter": {"quantityAllocated": max(quantities)}}- response = staff_api_client.post_graphql(- QUERY_STOCKS_WITH_FILTERS, variables=variables- )- content = get_graphql_content(response)- total_count = content["data"]["stocks"]["totalCount"]- assert (- total_count == Stock.objects.filter(quantity_allocated=max(quantities)).count()- )--def test_query_stocks_with_filters_warehouse(staff_api_client, stock, permission_manage_products):@@ -196,7 +173,7 @@ def test_query_available_stock_quantity(staff_api_client.user.user_permissions.add(permission_manage_products)stock_id = graphene.Node.to_global_id("Stock", stock.pk)- available_quantity = stock.quantity - stock.quantity_allocated+ available_quantity = stock.quantity - get_quantity_allocated_for_stock(stock)# set MAX_CHECKOUT_LINE_QUANTITY smaller than available quantitysettings.MAX_CHECKOUT_LINE_QUANTITY = available_quantity - 1diff --git a/tests/conftest.py b/tests/conftest.pyindex 39a9bcc9e3..c3feec9a78 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -44,7 +44,7 @@ from saleor.menu.utils import update_menufrom saleor.order import OrderStatusfrom saleor.order.actions import fulfill_order_linefrom saleor.order.events import OrderEvents-from saleor.order.models import FulfillmentStatus, Order, OrderEvent+from saleor.order.models import FulfillmentStatus, Order, OrderEvent, OrderLinefrom saleor.order.utils import recalculate_orderfrom saleor.page.models import Page, PageTranslationfrom saleor.payment import ChargeStatus, TransactionKind@@ -77,7 +77,7 @@ from saleor.shipping.models import ()from saleor.site import AuthenticationBackendsfrom saleor.site.models import AuthorizationKey, SiteSettings-from saleor.warehouse.models import Stock, Warehouse+from saleor.warehouse.models import Allocation, Stock, Warehousefrom saleor.webhook.event_types import WebhookEventTypefrom saleor.webhook.models import Webhookfrom saleor.wishlist.models import Wishlist@@ -630,9 +630,7 @@ def product(product_type, category, warehouse):variant = ProductVariant.objects.create(product=product, sku="123", cost_price=Money("1.00", "USD"))- Stock.objects.create(- warehouse=warehouse, product_variant=variant, quantity=10, quantity_allocated=1- )+ Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=10)associate_attribute_values_to_instance(variant, variant_attr, variant_attr_value)return product@@ -651,9 +649,7 @@ def product_with_single_variant(product_type, category, warehouse):variant = ProductVariant.objects.create(product=product, sku="SKU_SINGLE_VARIANT", cost_price=Money("1.00", "USD"))- Stock.objects.create(- product_variant=variant, warehouse=warehouse, quantity=101, quantity_allocated=1- )+ Stock.objects.create(product_variant=variant, warehouse=warehouse, quantity=101)return product@@ -679,12 +675,7 @@ def product_with_two_variants(product_type, category, warehouse):ProductVariant.objects.bulk_create(variants)Stock.objects.bulk_create([- Stock(- warehouse=warehouse,- product_variant=variant,- quantity=10,- quantity_allocated=1,- )+ Stock(warehouse=warehouse, product_variant=variant, quantity=10,)for variant in variants])@@ -717,9 +708,6 @@ def product_with_variant_with_two_attributes(variant = ProductVariant.objects.create(product=product, sku="prodVar1", cost_price=Money("1.00", "USD"))- Stock.objects.create(- product_variant=variant, warehouse=warehouse, quantity=10, quantity_allocated=1- )associate_attribute_values_to_instance(variant, color_attribute, color_attribute.values.first()@@ -954,9 +942,7 @@ def unavailable_product_with_variant(product_type, category, warehouse):variant = ProductVariant.objects.create(product=product, sku="123", cost_price=Money(1, "USD"))- Stock.objects.create(- product_variant=variant, warehouse=warehouse, quantity=10, quantity_allocated=1- )+ Stock.objects.create(product_variant=variant, warehouse=warehouse, quantity=10)associate_attribute_values_to_instance(variant, variant_attr, variant_attr_value)return product@@ -1087,12 +1073,12 @@ def order_with_lines(order, product_type, category, shipping_zone, warehouse):variant = ProductVariant.objects.create(product=product, sku="SKU_A", cost_price=Money(1, "USD"))- Stock.objects.create(- warehouse=warehouse, product_variant=variant, quantity=5, quantity_allocated=3+ stock = Stock.objects.create(+ warehouse=warehouse, product_variant=variant, quantity=5)net = variant.get_price()gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)- order.lines.create(+ line = order.lines.create(product_name=str(variant.product),variant_name=str(variant),product_sku=variant.sku,@@ -1102,6 +1088,9 @@ def order_with_lines(order, product_type, category, shipping_zone, warehouse):unit_price=TaxedMoney(net=net, gross=gross),tax_rate=23,)+ Allocation.objects.create(+ order_line=line, stock=stock, quantity_allocated=line.quantity+ )product = Product.objects.create(name="Test product 2",@@ -1114,13 +1103,13 @@ def order_with_lines(order, product_type, category, shipping_zone, warehouse):variant = ProductVariant.objects.create(product=product, sku="SKU_B", cost_price=Money(2, "USD"))- Stock.objects.create(- product_variant=variant, warehouse=warehouse, quantity=2, quantity_allocated=2+ stock = Stock.objects.create(+ product_variant=variant, warehouse=warehouse, quantity=2)net = variant.get_price()gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)- order.lines.create(+ line = order.lines.create(product_name=str(variant.product),variant_name=str(variant),product_sku=variant.sku,@@ -1130,6 +1119,9 @@ def order_with_lines(order, product_type, category, shipping_zone, warehouse):unit_price=TaxedMoney(net=net, gross=gross),tax_rate=23,)+ Allocation.objects.create(+ order_line=line, stock=stock, quantity_allocated=line.quantity+ )order.shipping_address = order.billing_address.get_copy()method = shipping_zone.shipping_methods.get()@@ -1660,10 +1652,7 @@ def digital_content(category, media_root, warehouse) -> DigitalContent:product=product, sku="SKU_554", cost_price=Money(1, "USD"))Stock.objects.create(- product_variant=product_variant,- warehouse=warehouse,- quantity=5,- quantity_allocated=3,+ product_variant=product_variant, warehouse=warehouse, quantity=5,)assert product_variant.is_digital()@@ -1903,8 +1892,70 @@ def warehouse_no_shipping_zone(address):@pytest.fixturedef stock(variant, warehouse):- return Stock.objects.get_or_create(- product_variant=variant,- warehouse=warehouse,- defaults={"quantity": 5, "quantity_allocated": 3},- )[0]+ return Stock.objects.create(+ product_variant=variant, warehouse=warehouse, quantity=15+ )+++def allocation(order_line, stock):+ return Allocation.objects.create(+ order_line=order_line, stock=stock, quantity_allocated=order_line.quantity+ )+++def allocations(order_list, stock):+ variant = stock.product_variant+ net = variant.get_price()+ gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)+ lines = OrderLine.objects.bulk_create(+ [+ OrderLine(+ order=order_list[0],+ variant=variant,+ quantity=1,+ product_name=str(variant.product),+ variant_name=str(variant),+ product_sku=variant.sku,+ is_shipping_required=variant.is_shipping_required(),+ unit_price=TaxedMoney(net=net, gross=gross),+ tax_rate=23,+ ),+ OrderLine(+ order=order_list[1],+ variant=variant,+ quantity=2,+ product_name=str(variant.product),+ variant_name=str(variant),+ product_sku=variant.sku,+ is_shipping_required=variant.is_shipping_required(),+ unit_price=TaxedMoney(net=net, gross=gross),+ tax_rate=23,+ ),+ OrderLine(+ order=order_list[2],+ variant=variant,+ quantity=4,+ product_name=str(variant.product),+ variant_name=str(variant),+ product_sku=variant.sku,+ is_shipping_required=variant.is_shipping_required(),+ unit_price=TaxedMoney(net=net, gross=gross),+ tax_rate=23,+ ),+ ]+ )+ return Allocation.objects.bulk_create(+ [+ Allocation(+ order_line=lines[0], stock=stock, quantity_allocated=lines[0].quantity+ ),+ Allocation(+ order_line=lines[1], stock=stock, quantity_allocated=lines[1].quantity+ ),+ Allocation(+ order_line=lines[2], stock=stock, quantity_allocated=lines[2].quantity+ ),+ ]+ )diff --git a/tests/test_order.py b/tests/test_order.pyindex 084310f6e2..b6d1385e10 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -34,6 +34,8 @@ from saleor.payment.models import Paymentfrom saleor.product.models import Collectionfrom saleor.warehouse.models import Stock+from .utils import get_quantity_allocated_for_stock+def test_total_setter():price = TaxedMoney(net=Money(10, "USD"), gross=Money(15, "USD"))@@ -84,15 +86,15 @@ def test_add_variant_to_order_allocates_stock_for_new_variant(variant.save()stock = Stock.objects.get(product_variant=variant)- stock_before = stock.quantity_allocated+ stock_before = get_quantity_allocated_for_stock(stock)add_variant_to_order(order_with_lines, variant, 1)stock.refresh_from_db()if track_inventory:- assert stock.quantity_allocated == stock_before + 1+ assert get_quantity_allocated_for_stock(stock) == stock_before + 1else:- assert stock.quantity_allocated == stock_before+ assert get_quantity_allocated_for_stock(stock) == stock_beforedef test_add_variant_to_order_edits_line_for_existing_variant(order_with_lines):@@ -113,19 +115,19 @@ def test_add_variant_to_order_allocates_stock_for_existing_variant(order_with_liexisting_line = order_with_lines.lines.first()variant = existing_line.variantstock = Stock.objects.get(product_variant=variant)- stock_before = stock.quantity_allocated+ stock_before = get_quantity_allocated_for_stock(stock)add_variant_to_order(order_with_lines, variant, 1)stock.refresh_from_db()- assert stock.quantity_allocated == stock_before + 1+ assert get_quantity_allocated_for_stock(stock) == stock_before + 1def test_add_variant_to_order_allow_overselling(order_with_lines):existing_line = order_with_lines.lines.first()variant = existing_line.variantstock = Stock.objects.get(product_variant=variant)- stock_before = stock.quantity_allocated+ stock_before = get_quantity_allocated_for_stock(stock)quantity = stock.quantity + 1with pytest.raises(InsufficientStock):@@ -135,7 +137,7 @@ def test_add_variant_to_order_allow_overselling(order_with_lines):add_variant_to_order(order_with_lines, variant, quantity, allow_overselling=True)stock.refresh_from_db()- assert stock.quantity_allocated == stock_before + quantity+ assert get_quantity_allocated_for_stock(stock) == stock_before + quantity@pytest.mark.parametrize("track_inventory", (True, False))@@ -153,8 +155,8 @@ def test_restock_order_lines(order_with_lines, track_inventory):stock_1 = Stock.objects.get(product_variant=line_1.variant)stock_2 = Stock.objects.get(product_variant=line_2.variant)- stock_1_quantity_allocated_before = stock_1.quantity_allocated- stock_2_quantity_allocated_before = stock_2.quantity_allocated+ stock_1_quantity_allocated_before = get_quantity_allocated_for_stock(stock_1)+ stock_2_quantity_allocated_before = get_quantity_allocated_for_stock(stock_2)stock_1_quantity_before = stock_1.quantitystock_2_quantity_before = stock_2.quantity@@ -165,15 +167,19 @@ def test_restock_order_lines(order_with_lines, track_inventory):stock_2.refresh_from_db()if track_inventory:- assert stock_1.quantity_allocated == (+ assert get_quantity_allocated_for_stock(stock_1) == (stock_1_quantity_allocated_before - line_1.quantity)- assert stock_2.quantity_allocated == (+ assert get_quantity_allocated_for_stock(stock_2) == (stock_2_quantity_allocated_before - line_2.quantity)else:- assert stock_1.quantity_allocated == (stock_1_quantity_allocated_before)- assert stock_2.quantity_allocated == (stock_2_quantity_allocated_before)+ assert get_quantity_allocated_for_stock(stock_1) == (+ stock_1_quantity_allocated_before+ )+ assert get_quantity_allocated_for_stock(stock_2) == (+ stock_2_quantity_allocated_before+ )assert stock_1.quantity == stock_1_quantity_beforeassert stock_2.quantity == stock_2_quantity_before@@ -186,8 +192,8 @@ def test_restock_fulfilled_order_lines(fulfilled_order):line_2 = fulfilled_order.lines.last()stock_1 = Stock.objects.get(product_variant=line_1.variant)stock_2 = Stock.objects.get(product_variant=line_2.variant)- stock_1_quantity_allocated_before = stock_1.quantity_allocated- stock_2_quantity_allocated_before = stock_2.quantity_allocated+ stock_1_quantity_allocated_before = get_quantity_allocated_for_stock(stock_1)+ stock_2_quantity_allocated_before = get_quantity_allocated_for_stock(stock_2)stock_1_quantity_before = stock_1.quantitystock_2_quantity_before = stock_2.quantity@@ -195,8 +201,12 @@ def test_restock_fulfilled_order_lines(fulfilled_order):stock_1.refresh_from_db()stock_2.refresh_from_db()- assert stock_1.quantity_allocated == stock_1_quantity_allocated_before- assert stock_2.quantity_allocated == stock_2_quantity_allocated_before+ assert (+ get_quantity_allocated_for_stock(stock_1) == stock_1_quantity_allocated_before+ )+ assert (+ get_quantity_allocated_for_stock(stock_2) == stock_2_quantity_allocated_before+ )assert stock_1.quantity == stock_1_quantity_before + line_1.quantityassert stock_2.quantity == stock_2_quantity_before + line_2.quantity@@ -207,8 +217,8 @@ def test_restock_fulfillment_lines(fulfilled_order):line_2 = fulfillment.lines.last()stock_1 = Stock.objects.get(product_variant=line_1.order_line.variant)stock_2 = Stock.objects.get(product_variant=line_2.order_line.variant)- stock_1_quantity_allocated_before = stock_1.quantity_allocated- stock_2_quantity_allocated_before = stock_2.quantity_allocated+ stock_1_quantity_allocated_before = get_quantity_allocated_for_stock(stock_1)+ stock_2_quantity_allocated_before = get_quantity_allocated_for_stock(stock_2)stock_1_quantity_before = stock_1.quantitystock_2_quantity_before = stock_2.quantity@@ -216,10 +226,10 @@ def test_restock_fulfillment_lines(fulfilled_order):stock_1.refresh_from_db()stock_2.refresh_from_db()- assert stock_1.quantity_allocated == (+ assert get_quantity_allocated_for_stock(stock_1) == (stock_1_quantity_allocated_before + line_1.quantity)- assert stock_2.quantity_allocated == (+ assert get_quantity_allocated_for_stock(stock_2) == (stock_2_quantity_allocated_before + line_2.quantity)assert stock_1.quantity == stock_1_quantity_before + line_1.quantitydiff --git a/tests/test_order_actions.py b/tests/test_order_actions.pyindex c82cce3cdc..59a1e1dba0 100644--- a/tests/test_order_actions.py+++ b/tests/test_order_actions.py@@ -17,7 +17,7 @@ from saleor.order.actions import (from saleor.order.models import Fulfillmentfrom saleor.payment import ChargeStatus, PaymentErrorfrom saleor.product.models import DigitalContent-from saleor.warehouse.models import Stock+from saleor.warehouse.models import Allocation, Stockfrom .utils import create_image@@ -36,18 +36,22 @@ def order_with_digital_line(order, digital_content, stock, site_settings):product_type.is_digital = Trueproduct_type.save()+ quantity = 3net = variant.get_price()gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)- order.lines.create(+ line = order.lines.create(product_name=str(variant.product),variant_name=str(variant),product_sku=variant.sku,is_shipping_required=variant.is_shipping_required(),- quantity=3,+ quantity=quantity,variant=variant,unit_price=TaxedMoney(net=net, gross=gross),tax_rate=23,)++ Allocation.objects.create(order_line=line, stock=stock, quantity_allocated=quantity)+return orderdiff --git a/tests/test_product_availability.py b/tests/test_product_availability.pyindex 816c245abf..dfa473960b 100644--- a/tests/test_product_availability.py+++ b/tests/test_product_availability.py@@ -83,8 +83,7 @@ def test_variant_is_out_of_stock_when_product_is_unavalable()def test_variant_availability_status(stock, current_stock, expected_status):stock.quantity = current_stock- stock.quantity_allocated = 0- stock.save(update_fields=["quantity", "quantity_allocated"])+ stock.save(update_fields=["quantity"])variant = stock.product_variantstatus = get_variant_availability_status(variant, "US")@@ -104,10 +103,7 @@ def test_variant_is_still_available_when_another_variant_is_unavailable(product_variant=unavailable_variant, warehouse=warehouse, quantity=0)Stock.objects.create(- product_variant=available_variant,- warehouse=warehouse,- quantity=1,- quantity_allocated=0,+ product_variant=available_variant, warehouse=warehouse, quantity=1,)status = get_variant_availability_status(available_variant, "US")diff --git a/tests/test_stock.py b/tests/test_stock.pyindex 39bdf48f01..cd1582d012 100644--- a/tests/test_stock.py+++ b/tests/test_stock.py@@ -4,6 +4,8 @@ from saleor.core.exceptions import InsufficientStockfrom saleor.warehouse.availability import (are_all_product_variants_in_stock,check_stock_quantity,+ get_available_quantity,+ get_quantity_allocated,products_with_low_stock,)from saleor.warehouse.management import (@@ -12,7 +14,7 @@ from saleor.warehouse.management import (decrease_stock,increase_stock,)-from saleor.warehouse.models import Stock+from saleor.warehouse.models import Allocation, StockCOUNTRY_CODE = "US"@@ -39,36 +41,54 @@ def test_stock_for_country_does_not_exists(product, warehouse):assert not stock_qs.exists()-def test_check_stock_quantity_is_lower_than_available(product):- stock = Stock.objects.get()- variant = stock.product_variant- new_quantity = stock.quantity_available- assert check_stock_quantity(variant, COUNTRY_CODE, new_quantity) is None+def test_check_stock_quantity_without_allocation(order_line, stock):+ assert not Allocation.objects.filter(order_line=order_line, stock=stock).exists()+ assert (+ check_stock_quantity(order_line.variant, COUNTRY_CODE, order_line.quantity)+ is None+ )-def test_check_stock_quantity_is_not_sufficient(product):- stock = Stock.objects.get()- variant = stock.product_variant- new_quantity = stock.quantity_available + 1+def test_check_stock_quantity_without_stock(order_line):with pytest.raises(InsufficientStock):- check_stock_quantity(variant, COUNTRY_CODE, new_quantity)+ check_stock_quantity(order_line.variant, COUNTRY_CODE, 5)-def test_are_all_product_variants_in_stock_all_in_stock(product):- assert are_all_product_variants_in_stock(product, COUNTRY_CODE)+def test_check_stock_quantity_many_allocations(allocations, variant):+ assert check_stock_quantity(variant, COUNTRY_CODE, 1) is None-def test_are_all_product_variants_in_stock_stock_empty(product):- stock = Stock.objects.first()- stock.quantity_allocated = stock.quantity- stock.save(update_fields=["quantity_allocated"])+def test_check_stock_quantity_many_allocations_out_of_stock(allocations, variant):+ quantity = allocations[0].stock.quantity+ with pytest.raises(InsufficientStock):+ check_stock_quantity(variant, COUNTRY_CODE, quantity)+- assert not are_all_product_variants_in_stock(product, COUNTRY_CODE)+def test_check_stock_quantity_out_of_stock(allocation, variant):+ quantity = allocation.stock.quantity+ with pytest.raises(InsufficientStock):+ check_stock_quantity(variant, COUNTRY_CODE, quantity)-def test_are_all_product_variants_in_stock_lack_of_stocks(product):- Stock.objects.all().delete()- assert not are_all_product_variants_in_stock(product, COUNTRY_CODE)+def test_check_stock_quantity(allocation, variant):+ assert check_stock_quantity(variant, COUNTRY_CODE, 1) is None+++def test_are_all_product_variants_in_stock_all_in_stock(stock):+ assert are_all_product_variants_in_stock(+ stock.product_variant.product, COUNTRY_CODE+ )+++def test_are_all_product_variants_in_stock_stock_empty(allocation, variant):+ allocation.quantity_allocated = allocation.stock.quantity+ allocation.save(update_fields=["quantity_allocated"])++ assert not are_all_product_variants_in_stock(variant.product, COUNTRY_CODE)+++def test_are_all_product_variants_in_stock_lack_of_stocks(variant):+ assert not are_all_product_variants_in_stock(variant.product, COUNTRY_CODE)def test_products_with_low_stock_one_stock(product, settings):@@ -98,22 +118,150 @@ def test_products_with_low_stock_filter_properly(stock, settings):assert len(result) == 0- "func, expected_quantity, expected_quantity_allocated",- (- (increase_stock, 150, 80),- (decrease_stock, 50, 30),- (deallocate_stock, 100, 30),- (allocate_stock, 100, 130),- ),-)-def test_changing_stock(product, func, expected_quantity, expected_quantity_allocated):- stock = Stock.objects.first()+def test_decrease_stock(allocation):+ stock = allocation.stock+ stock.quantity = 100+ stock.save(update_fields=["quantity"])+ allocation.quantity_allocated = 80+ allocation.save(update_fields=["quantity_allocated"])++ decrease_stock(allocation.order_line, COUNTRY_CODE, 50)++ stock.refresh_from_db()+ assert stock.quantity == 50+ allocation.refresh_from_db()+ assert allocation.quantity_allocated == 30+++def test_increase_stock_without_allocate(allocation):+ stock = allocation.stockstock.quantity = 100- stock.quantity_allocated = 80- stock.save()- variant = stock.product_variant- func(variant, COUNTRY_CODE, 50)+ stock.save(update_fields=["quantity"])+ allocation.quantity_allocated = 80+ allocation.save(update_fields=["quantity_allocated"])++ increase_stock(allocation.order_line, COUNTRY_CODE, 50, allocate=False)++ stock.refresh_from_db()+ assert stock.quantity == 150+ allocation.refresh_from_db()+ assert allocation.quantity_allocated == 80+++def test_increase_stock_with_allocate(allocation):+ stock = allocation.stock+ stock.quantity = 100+ stock.save(update_fields=["quantity"])+ allocation.quantity_allocated = 80+ allocation.save(update_fields=["quantity_allocated"])++ increase_stock(allocation.order_line, COUNTRY_CODE, 50, allocate=True)++ stock.refresh_from_db()+ assert stock.quantity == 150+ allocation.refresh_from_db()+ assert allocation.quantity_allocated == 130+++def test_increase_stock_new_allocation(order_line, stock):+ assert not Allocation.objects.filter(order_line=order_line, stock=stock).exists()+ stock.quantity = 100+ stock.save(update_fields=["quantity"])++ increase_stock(order_line, COUNTRY_CODE, 50, allocate=True)+stock.refresh_from_db()- assert stock.quantity == expected_quantity- assert stock.quantity_allocated == expected_quantity_allocated+ assert stock.quantity == 150+ allocation = Allocation.objects.get(order_line=order_line, stock=stock)+ assert allocation.quantity_allocated == 50+++def test_deallocate_stock(allocation):+ stock = allocation.stock+ stock.quantity = 100+ stock.save(update_fields=["quantity"])+ allocation.quantity_allocated = 80+ allocation.save(update_fields=["quantity_allocated"])++ deallocate_stock(allocation.order_line, COUNTRY_CODE, 50)++ stock.refresh_from_db()+ assert stock.quantity == 100+ allocation.refresh_from_db()+ assert allocation.quantity_allocated == 30+++def test_allocate_stock(allocation):+ stock = allocation.stock+ stock.quantity = 100+ stock.save(update_fields=["quantity"])+ allocation.quantity_allocated = 80+ allocation.save(update_fields=["quantity_allocated"])++ allocate_stock(allocation.order_line, COUNTRY_CODE, 20)++ stock.refresh_from_db()+ assert stock.quantity == 100+ allocation.refresh_from_db()+ assert allocation.quantity_allocated == 100+++def test_allocate_stock_new_allocation(order_line, stock):+ assert not Allocation.objects.filter(order_line=order_line, stock=stock).exists()+ stock.quantity = 100+ stock.save(update_fields=["quantity"])++ allocate_stock(order_line, COUNTRY_CODE, 50)++ stock.refresh_from_db()+ assert stock.quantity == 100+ allocation = Allocation.objects.get(order_line=order_line, stock=stock)+ assert allocation.quantity_allocated == 50+++def test_get_quantity_allocated_without_allocation(order_line, stock):+ assert not Allocation.objects.filter(order_line=order_line, stock=stock).exists()+ quantity_allocated = get_quantity_allocated(order_line.variant, COUNTRY_CODE)+ assert quantity_allocated == 0+++def test_get_quantity_allocated_without_stock(order_line):+ quantity_allocated = get_quantity_allocated(order_line.variant, COUNTRY_CODE)+ assert quantity_allocated == 0+++def test_get_quantity_allocated_many_allocations(allocations, variant):+ quantity_allocated = get_quantity_allocated(variant, COUNTRY_CODE)+ assert quantity_allocated == 7+++def test_get_quantity_allocated(allocation):+ quantity_allocated = get_quantity_allocated(+ allocation.order_line.variant, COUNTRY_CODE+ )+ assert quantity_allocated == allocation.order_line.quantity+++def test_get_available_quantity_without_allocation(order_line, stock):+ assert not Allocation.objects.filter(order_line=order_line, stock=stock).exists()+ available_quantity = get_available_quantity(order_line.variant, COUNTRY_CODE)+ assert available_quantity == stock.quantity+++def test_get_available_quantity_without_stock(order_line):+ available_quantity = get_available_quantity(order_line.variant, COUNTRY_CODE)+ assert available_quantity == 0+++def test_get_available_quantity_many_allocations(allocations, variant):+ available_quantity = get_available_quantity(variant, COUNTRY_CODE)+ assert available_quantity == 8+++def test_get_available_quantity(allocation):+ available_quantity = get_available_quantity(+ allocation.order_line.variant, COUNTRY_CODE+ )+ assert available_quantity == (+ allocation.stock.quantity - allocation.quantity_allocated+ )diff --git a/tests/utils.py b/tests/utils.pyindex c987e727f8..b72c96be29 100644--- a/tests/utils.py+++ b/tests/utils.py@@ -4,6 +4,8 @@ from urllib.parse import urlparsefrom django.core.files.uploadedfile import SimpleUploadedFilefrom django.db import connections, transaction+from django.db.models import Sum+from django.db.models.functions import Coalescefrom PIL import Imagefrom prices import Money@@ -76,3 +78,16 @@ def flush_post_commit_hooks():connection.in_atomic_block = Falseconnection.run_and_clear_commit_hooks()connection.in_atomic_block = was_atomic+++def get_quantity_allocated_for_stock(stock):+ """Count how many items are allocated for stock."""+ return stock.allocations.aggregate(+ quantity_allocated=Coalesce(Sum("quantity_allocated"), 0)+ )["quantity_allocated"]+++def get_available_quantity_for_stock(stock):+ """Count how many stock items are available."""+ quantity_allocated = get_quantity_allocated_for_stock(stock)+ return max(stock.quantity - quantity_allocated, 0)