Skip to content

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

Allocate stocks for order lines in a bulk way (#6877)

Iga Karbowiakfb72855c1b97
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8a40643b75..82edd31016 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -50,6 +50,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Fix `product_updated` and `product_created` webhooks - #6798 by @d-wysocki
- Add interface for integrating the auth plugins - #6799 by @korycins
- Fix page `contentJson` field to return JSON - #6832 by @d-wysocki
+- Allocate stocks for order lines in a bulk way - #6877 by @IKarbowiak
# 2.11.1
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 1b4d240793..3c18a24b09 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -24,7 +24,7 @@ from ..discount.utils import (
increase_voucher_usage,
remove_voucher_usage_by_customer,
)
-from ..order import OrderStatus
+from ..order import OrderLineData, OrderStatus
from ..order.actions import order_created
from ..order.emails import send_order_confirmation, send_staff_order_confirmation
from ..order.models import Order, OrderLine
@@ -33,7 +33,7 @@ from ..payment.models import Payment, Transaction
from ..payment.utils import store_customer_id
from ..product.models import ProductTranslation, ProductVariantTranslation
from ..warehouse.availability import check_stock_quantity_bulk
-from ..warehouse.management import allocate_stock
+from ..warehouse.management import allocate_stocks
from . import AddressType, models
from .checkout_cleaner import clean_checkout_payment, clean_checkout_shipping
from .models import Checkout
@@ -137,7 +137,7 @@ def _create_line_for_order(
channel: "Channel",
products_translation: Dict[int, Optional[str]],
variants_translation: Dict[int, Optional[str]],
-) -> OrderLine:
+) -> OrderLineData:
"""Create a line for the given order.
:raises InsufficientStock: when there is not enough items in stock for this variant.
@@ -196,7 +196,9 @@ def _create_line_for_order(
tax_rate=tax_rate,
)
- return line
+ line_info = OrderLineData(line=line, quantity=quantity, variant=variant)
+
+ return line_info
def _create_lines_for_order(
@@ -205,7 +207,7 @@ def _create_lines_for_order(
lines: Iterable["CheckoutLineInfo"],
discounts: Iterable[DiscountInfo],
channel: "Channel",
-) -> Iterable[OrderLine]:
+) -> Iterable[OrderLineData]:
"""Create a lines for the given order.
:raises InsufficientStock: when there is not enough items in stock for this variant.
@@ -324,7 +326,9 @@ def _prepare_order_data(
@transaction.atomic
-def _create_order(*, checkout: Checkout, order_data: dict, user: User) -> Order:
+def _create_order(
+ *, checkout: Checkout, order_data: dict, user: User, site_settings=None
+) -> Order:
"""Create an order from the checkout.
Each order will get a private copy of both the billing and the shipping
@@ -343,10 +347,11 @@ def _create_order(*, checkout: Checkout, order_data: dict, user: User) -> Order:
return order
total_price_left = order_data.pop("total_price_left")
- order_lines = order_data.pop("lines")
+ order_lines_info = order_data.pop("lines")
+
+ if site_settings is None:
+ site_settings = Site.objects.get_current().settings
- # TODO: refactor to use request.site / info.context site
- site_settings = Site.objects.get_current().settings
status = (
OrderStatus.UNFULFILLED
if site_settings.automatically_confirm_all_new_orders
@@ -358,15 +363,16 @@ def _create_order(*, checkout: Checkout, order_data: dict, user: User) -> Order:
status=status,
channel=checkout.channel,
)
- for line in order_lines:
+ order_lines = []
+ for line_info in order_lines_info:
+ line = line_info.line
line.order_id = order.pk
- order_lines = OrderLine.objects.bulk_create(order_lines)
+ order_lines.append(line)
- # allocate stocks from the lines
- for line in order_lines: # type: OrderLine
- variant = line.variant
- if variant and variant.track_inventory:
- allocate_stock(line, checkout.get_country(), line.quantity)
+ OrderLine.objects.bulk_create(order_lines)
+
+ country_code = checkout.get_country()
+ allocate_stocks(order_lines_info, country_code)
# Add gift cards to the order
for gift_card in checkout.gift_cards.select_for_update():
@@ -465,7 +471,9 @@ def _get_order_data(
discounts=discounts,
)
except InsufficientStock as e:
- raise ValidationError(f"Insufficient product stock: {e.item}", code=e.code)
+ raise ValidationError(
+ f"Insufficient product stock: {', '.join(e.items)}", code=e.code
+ )
except NotApplicable:
raise ValidationError(
"Voucher not applicable",
@@ -515,6 +523,7 @@ def complete_checkout(
store_source,
discounts,
user,
+ site_settings=None,
tracking_code=None,
redirect_url=None,
) -> Tuple[Optional[Order], bool, dict]:
@@ -562,12 +571,15 @@ def complete_checkout(
checkout=checkout,
order_data=order_data,
user=user, # type: ignore
+ site_settings=site_settings,
)
# remove checkout after order is successfully created
checkout.delete()
except InsufficientStock as e:
release_voucher_usage(order_data)
gateway.payment_refund_or_void(payment)
- raise ValidationError(f"Insufficient product stock: {e.item}", code=e.code)
+ raise ValidationError(
+ f"Insufficient product stock: {', '.join(e.items)}", code=e.code
+ )
return order, action_required, action_data
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index 1c8fb32063..f87be2d298 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -791,7 +791,7 @@ def test_create_order_use_tanslations(
order_data = _prepare_order_data(
manager=manager, checkout=checkout, lines=lines, discounts=None
)
- order_line = order_data["lines"][0]
+ order_line = order_data["lines"][0].line
assert order_line.translated_product_name == translated_product_name
assert order_line.translated_variant_name == translated_variant_name
diff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.py
index 8829435c3a..cbfef941c4 100644
--- a/saleor/core/exceptions.py
+++ b/saleor/core/exceptions.py
@@ -2,9 +2,10 @@ from ..checkout.error_codes import CheckoutErrorCode
class InsufficientStock(Exception):
- def __init__(self, item, context=None):
- super().__init__("Insufficient stock for %r" % (item,))
- self.item = item
+ def __init__(self, items, context=None):
+ items = [str(item) for item in items]
+ super().__init__(f"Insufficient stock for {', '.join(items)}")
+ self.items = items
self.context = context
self.code = CheckoutErrorCode.INSUFFICIENT_STOCK
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 521537b21f..375ca47bd2 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -122,9 +122,9 @@ def check_lines_quantity(variants, quantities, country):
check_stock_quantity_bulk(variants, country, quantities)
except InsufficientStock as e:
remaining = e.context["available_quantity"]
- item_name = e.item.display_product()
message = (
- f"Could not add item {item_name}. Only {remaining} remaining in stock."
+ f"Could not add items {', '.join(e.items)}. "
+ f"Only {remaining} remaining in stock."
)
raise ValidationError({"quantity": ValidationError(message, code=e.code)})
@@ -336,7 +336,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):
add_variants_to_checkout(instance, variants, quantities)
except InsufficientStock as exc:
raise ValidationError(
- f"Insufficient product stock: {exc.item}", code=exc.code
+ f"Insufficient product stock: {', '.join(exc.items)}", code=exc.code
)
except ProductNotPublished as exc:
raise ValidationError(
@@ -427,7 +427,8 @@ class CheckoutLinesAdd(BaseMutation):
)
except InsufficientStock as exc:
raise ValidationError(
- f"Insufficient product stock: {exc.item}", code=exc.code
+ f"Insufficient product stock: {', '.join(exc.items)}",
+ code=exc.code,
)
except ProductNotPublished as exc:
raise ValidationError(
@@ -869,6 +870,7 @@ class CheckoutComplete(BaseMutation):
store_source=store_source,
discounts=info.context.discounts,
user=info.context.user,
+ site_settings=info.context.site.settings,
tracking_code=tracking_code,
redirect_url=data.get("redirect_url"),
)
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 55c6c85dc7..3f11b3600a 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -910,7 +910,7 @@ def test_checkout_create_check_lines_quantity_multiple_warehouse(
content = get_graphql_content(response)
data = content["data"]["checkoutCreate"]
assert data["checkoutErrors"][0]["message"] == (
- "Could not add item Test product (SKU_A). Only 7 remaining in stock."
+ "Could not add items SKU_A. Only 7 remaining in stock."
)
assert data["checkoutErrors"][0]["field"] == "quantity"
@@ -1004,7 +1004,7 @@ def test_checkout_create_check_lines_quantity(
content = get_graphql_content(response)
data = content["data"]["checkoutCreate"]
assert data["checkoutErrors"][0]["message"] == (
- "Could not add item Test product (SKU_A). Only 15 remaining in stock."
+ "Could not add items SKU_A. Only 15 remaining in stock."
)
assert data["checkoutErrors"][0]["field"] == "quantity"
@@ -1493,7 +1493,7 @@ def test_checkout_lines_add_check_lines_quantity(user_api_client, checkout, stoc
content = get_graphql_content(response)
data = content["data"]["checkoutLinesAdd"]
assert data["checkoutErrors"][0]["message"] == (
- "Could not add item Test product (SKU_A). Only 15 remaining in stock."
+ "Could not add items SKU_A. Only 15 remaining in stock."
)
assert data["checkoutErrors"][0]["field"] == "quantity"
@@ -1664,7 +1664,7 @@ def test_checkout_lines_update_check_lines_quantity(
data = content["data"]["checkoutLinesUpdate"]
assert data["checkoutErrors"][0]["message"] == (
- "Could not add item Test product (123). Only 10 remaining in stock."
+ "Could not add items 123. Only 10 remaining in stock."
)
assert data["checkoutErrors"][0]["field"] == "quantity"
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index 0fd1da9120..d6e11450b4 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -8,7 +8,7 @@ from ....core.exceptions import InsufficientStock
from ....core.permissions import OrderPermissions
from ....core.taxes import TaxError, zero_taxed_money
from ....core.utils.url import validate_storefront_url
-from ....order import OrderStatus, events, models
+from ....order import OrderLineData, OrderStatus, events, models
from ....order.actions import order_created
from ....order.error_codes import OrderErrorCode
from ....order.utils import (
@@ -19,7 +19,7 @@ from ....order.utils import (
recalculate_order,
update_order_prices,
)
-from ....warehouse.management import allocate_stock
+from ....warehouse.management import allocate_stocks
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
from ...channel.types import Channel
@@ -363,13 +363,16 @@ class DraftOrderComplete(BaseMutation):
for line in order:
if line.variant.track_inventory:
+ line_data = OrderLineData(
+ line=line, quantity=line.quantity, variant=line.variant
+ )
try:
- allocate_stock(line, country, line.quantity)
+ allocate_stocks([line_data], country)
except InsufficientStock as exc:
raise ValidationError(
{
"lines": ValidationError(
- f"Insufficient product stock: {exc.item}",
+ f"Insufficient product stock: {', '.join(exc.items)}",
code=OrderErrorCode.INSUFFICIENT_STOCK,
)
}
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index d618b23847..6baab5cd41 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -227,7 +227,7 @@ class OrderFulfill(BaseMutation):
raise ValidationError(
{
"stocks": ValidationError(
- f"Insufficient product stock: {exc.item}",
+ f"Insufficient product stock: {', '.join(exc.items)}",
code=OrderErrorCode.INSUFFICIENT_STOCK,
params={
"order_line": order_line_global_id,
diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.py
index 929658fe8f..164b7a5f88 100644
--- a/saleor/graphql/order/tests/test_fulfillment.py
+++ b/saleor/graphql/order/tests/test_fulfillment.py
@@ -403,7 +403,7 @@ def test_order_fulfill_warehouse_with_insufficient_stock_exception(
"warehouse_pk": str(warehouse_no_shipping_zone.pk),
}
mock_create_fulfillments.side_effect = InsufficientStock(
- order_line.variant, error_context
+ [order_line.variant], error_context
)
response = staff_api_client.post_graphql(
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index 5bc749c23b..c0c66bdb3e 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -85,7 +85,7 @@ def validate_order_lines(order, country):
raise ValidationError(
{
"lines": ValidationError(
- f"Insufficient product stock: {exc.item}",
+ f"Insufficient product stock: {', '.join(exc.items)}",
code=OrderErrorCode.INSUFFICIENT_STOCK,
)
}
diff --git a/saleor/order/__init__.py b/saleor/order/__init__.py
index 37a4dd90af..0ca10a6c5e 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -1,7 +1,8 @@
from dataclasses import dataclass
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
+ from ..product.models import ProductVariant
from .models import FulfillmentLine, OrderLine
@@ -169,6 +170,7 @@ class OrderEventsEmails:
class OrderLineData:
line: "OrderLine"
quantity: int
+ variant: Optional["ProductVariant"] = None
replace: bool = False
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 4e4eca2aed..6c8fb3dd62 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -383,7 +383,7 @@ def _create_fulfillment_lines(
stock = order_line.variant.stocks.filter(warehouse=warehouse_pk).first()
if stock is None:
error_context = {"order_line": order_line, "warehouse_pk": warehouse_pk}
- raise InsufficientStock(order_line.variant, error_context)
+ raise InsufficientStock([order_line.variant], error_context)
fulfill_order_line(order_line, quantity, warehouse_pk)
if order_line.is_digital:
order_line.variant.digital_content.urls.create(line=order_line)
diff --git a/saleor/order/tests/test_fulfullments_actions.py b/saleor/order/tests/test_fulfullments_actions.py
index af9c24b9f8..63b558851b 100644
--- a/saleor/order/tests/test_fulfullments_actions.py
+++ b/saleor/order/tests/test_fulfullments_actions.py
@@ -318,7 +318,7 @@ def test_create_fulfillments_warehouse_with_out_of_stock(
with pytest.raises(InsufficientStock) as exc:
create_fulfillments(staff_user, order, fulfillment_lines_for_warehouses, True)
- assert exc.value.item == order_line1.variant
+ assert exc.value.items == [str(order_line1.variant)]
assert exc.value.context == {
"order_line": order_line1,
"warehouse_pk": str(warehouse.pk),
@@ -363,7 +363,7 @@ def test_create_fulfillments_warehouse_without_stock(
with pytest.raises(InsufficientStock) as exc:
create_fulfillments(staff_user, order, fulfillment_lines_for_warehouses, True)
- assert exc.value.item == order_line1.variant
+ assert exc.value.items == [str(order_line1.variant)]
assert exc.value.context == {
"order_line": order_line1,
"warehouse_pk": str(warehouse_no_shipping_zone.pk),
@@ -405,7 +405,7 @@ def test_create_fulfillments_with_variant_without_inventory_tracking_and_without
with pytest.raises(InsufficientStock) as exc:
create_fulfillments(staff_user, order, fulfillment_lines_for_warehouses, True)
- assert exc.value.item == order_line.variant
+ assert exc.value.items == [str(order_line.variant)]
assert exc.value.context == {
"order_line": order_line,
"warehouse_pk": str(warehouse_no_shipping_zone.pk),
diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.py
index 65297247ec..43a06b9ed7 100644
--- a/saleor/warehouse/availability.py
+++ b/saleor/warehouse/availability.py
@@ -31,10 +31,10 @@ def check_stock_quantity(variant: "ProductVariant", country_code: str, quantity:
if variant.track_inventory:
stocks = Stock.objects.get_variant_stocks_for_country(country_code, variant)
if not stocks:
- raise InsufficientStock(variant)
+ raise InsufficientStock([variant])
if quantity > _get_available_quantity(stocks):
- raise InsufficientStock(variant)
+ raise InsufficientStock([variant])
def check_stock_quantity_bulk(variants, country_code, quantities):
@@ -58,13 +58,13 @@ def check_stock_quantity_bulk(variants, country_code, quantities):
if not stocks:
raise InsufficientStock(
- variant, context={"available_quantity": available_quantity}
+ [variant], context={"available_quantity": available_quantity}
)
if variant.track_inventory:
if quantity > available_quantity:
raise InsufficientStock(
- variant, context={"available_quantity": available_quantity}
+ [variant], context={"available_quantity": available_quantity}
)
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index 7353f3cce1..95b3fb0e30 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -1,5 +1,5 @@
-from collections import defaultdict
-from typing import TYPE_CHECKING, Dict
+from collections import defaultdict, namedtuple
+from typing import TYPE_CHECKING, Dict, Iterable, List
from django.db import transaction
from django.db.models import F, Sum
@@ -9,27 +9,38 @@ from ..core.exceptions import AllocationError, InsufficientStock
from .models import Allocation, Stock, Warehouse
if TYPE_CHECKING:
+ from ..order import OrderLineData
from ..order.models import Order, OrderLine
+ from ..product.models import ProductVariant
+
+
+StockData = namedtuple("StockData", ["pk", "quantity"])
@transaction.atomic
-def allocate_stock(
- order_line: "OrderLine",
- country_code: str,
- quantity: int,
-):
- """Allocate stocks for given `order_line` in given country.
+def allocate_stocks(order_lines_info: Iterable["OrderLineData"], country_code: str):
+ """Allocate stocks for given `order_lines` in given country.
- Function lock for update all stocks and allocations for variant in
+ Function lock for update all stocks and allocations for variants in
given country and order by pk. Next, generate the dictionary
({"stock_pk": "quantity_allocated"}) with actual allocated quantity for stocks.
Iterate by stocks and allocate as many items as needed or available in stock
for order line, until allocated all required quantity for the order line.
If there is less quantity in stocks then rise InsufficientStock exception.
"""
+ # allocation only applied to order lines with variants with track inventory
+ # set to True
+ order_lines_info = [
+ line_info
+ for line_info in order_lines_info
+ if line_info.variant and line_info.variant.track_inventory
+ ]
+ variants = [line_info.variant for line_info in order_lines_info]
+
stocks = (
Stock.objects.select_for_update(of=("self",))
- .get_variant_stocks_for_country(country_code, order_line.variant)
+ .for_country(country_code)
+ .filter(product_variant__in=variants)
.order_by("pk")
)
@@ -47,13 +58,42 @@ def allocate_stock(
"quantity_allocated__sum"
]
+ variant_to_stocks: Dict[str, List[StockData]] = defaultdict(list)
+ for stock_data in stocks.values("product_variant", "pk", "quantity"):
+ variant = stock_data.pop("product_variant")
+ variant_to_stocks[variant].append(StockData(**stock_data))
+
+ insufficient_stock: List["ProductVariant"] = []
+ allocations: List[Allocation] = []
+ for line_info in order_lines_info:
+ stocks = variant_to_stocks[line_info.variant.pk] # type: ignore
+ insufficient_stock, allocation_items = _create_allocations(
+ line_info, stocks, quantity_allocation_for_stocks, insufficient_stock
+ )
+ allocations.extend(allocation_items)
+
+ if insufficient_stock:
+ raise InsufficientStock(insufficient_stock)
+
+ if allocations:
+ Allocation.objects.bulk_create(allocations)
+
+
+def _create_allocations(
+ line_info: "OrderLineData",
+ stocks: List[StockData],
+ quantity_allocation_for_stocks: dict,
+ insufficient_stock: List["ProductVariant"],
+):
+ quantity = line_info.quantity
quantity_allocated = 0
allocations = []
+ for stock_data in stocks:
+ quantity_allocated_in_stock = quantity_allocation_for_stocks.get(
+ stock_data.pk, 0
+ )
- for stock in stocks:
- quantity_allocated_in_stock = quantity_allocation_for_stocks.get(stock.pk, 0)
-
- quantity_available_in_stock = stock.quantity - quantity_allocated_in_stock
+ quantity_available_in_stock = stock_data.quantity - quantity_allocated_in_stock
quantity_to_allocate = min(
(quantity - quantity_allocated), quantity_available_in_stock
@@ -61,18 +101,19 @@ def allocate_stock(
if quantity_to_allocate > 0:
allocations.append(
Allocation(
- order_line=order_line,
- stock=stock,
+ order_line=line_info.line,
+ stock_id=stock_data.pk,
quantity_allocated=quantity_to_allocate,
)
)
quantity_allocated += quantity_to_allocate
if quantity_allocated == quantity:
- Allocation.objects.bulk_create(allocations)
- break
+ return insufficient_stock, allocations
+
if not quantity_allocated == quantity:
- raise InsufficientStock(order_line.variant)
+ insufficient_stock.append(line_info.variant) # type: ignore
+ return insufficient_stock, []
@transaction.atomic
@@ -174,7 +215,7 @@ def decrease_stock(order_line: "OrderLine", quantity: int, warehouse_pk: str):
)
except Stock.DoesNotExist:
error_context = {"order_line": order_line, "warehouse_pk": warehouse_pk}
- raise InsufficientStock(order_line.variant, error_context)
+ raise InsufficientStock([order_line.variant], error_context)
quantity_allocated = stock.allocations.aggregate(
quantity_allocated=Coalesce(Sum("quantity_allocated"), 0)
@@ -182,7 +223,7 @@ def decrease_stock(order_line: "OrderLine", quantity: int, warehouse_pk: str):
if stock.quantity - quantity_allocated < quantity:
error_context = {"order_line": order_line, "warehouse_pk": warehouse_pk}
- raise InsufficientStock(order_line.variant, error_context)
+ raise InsufficientStock([order_line.variant], error_context)
stock.quantity = F("quantity") - quantity
stock.save(update_fields=["quantity"])
diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.py
index ee28882c59..561ad429b8 100644
--- a/saleor/warehouse/tests/test_stock_management.py
+++ b/saleor/warehouse/tests/test_stock_management.py
@@ -3,8 +3,11 @@ from django.db.models import Sum
from django.db.models.functions import Coalesce
from ...core.exceptions import InsufficientStock
+from ...order import OrderLineData
+from ...order.models import OrderLine
+from ...warehouse.models import Stock
from ..management import (
- allocate_stock,
+ allocate_stocks,
deallocate_stock,
deallocate_stock_for_order,
decrease_stock,
@@ -15,11 +18,13 @@ from ..models import Allocation
COUNTRY_CODE = "US"
-def test_allocate_stock(order_line, stock):
+def test_allocate_stocks(order_line, stock):
stock.quantity = 100
stock.save(update_fields=["quantity"])
- allocate_stock(order_line, COUNTRY_CODE, 50)
+ line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=50)
+
+ allocate_stocks([line_data], COUNTRY_CODE)
stock.refresh_from_db()
assert stock.quantity == 100
@@ -27,11 +32,48 @@ def test_allocate_stock(order_line, stock):
assert allocation.quantity_allocated == 50
+def test_allocate_stocks_multiply_lines(order_line, order, product, stock):
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+
+ variant_2 = product.variants.first()
+ stock_2 = Stock.objects.get(product_variant=variant_2)
+
+ order_line_2 = OrderLine.objects.get(pk=order_line.pk)
+ order_line_2.pk = None
+ order_line_2.product_name = product.name
+ order_line_2.variant_name = variant_2.name
+ order_line_2.product_sku = variant_2.sku
+ order_line_2.variant = variant_2
+ order_line_2.save()
+
+ quantity_1 = 50
+ quantity_2 = 5
+ line_data_1 = OrderLineData(
+ line=order_line, variant=order_line.variant, quantity=quantity_1
+ )
+ line_data_2 = OrderLineData(
+ line=order_line_2, variant=variant_2, quantity=quantity_2
+ )
+
+ allocate_stocks([line_data_1, line_data_2], COUNTRY_CODE)
+
+ stock.refresh_from_db()
+ assert stock.quantity == 100
+ allocation = Allocation.objects.get(order_line=order_line, stock=stock)
+ assert allocation.quantity_allocated == quantity_1
+
+ stock_2.refresh_from_db()
+ allocation = Allocation.objects.get(order_line=order_line_2, stock=stock_2)
+ assert allocation.quantity_allocated == quantity_2
+
+
def test_allocate_stock_many_stocks(order_line, variant_with_many_stocks):
variant = variant_with_many_stocks
stocks = variant.stocks.all()
- allocate_stock(order_line, COUNTRY_CODE, 5)
+ line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=5)
+ allocate_stocks([line_data], COUNTRY_CODE)
allocations = Allocation.objects.filter(order_line=order_line, stock__in=stocks)
assert allocations[0].quantity_allocated == 4
@@ -47,7 +89,8 @@ def test_allocate_stock_many_stocks_partially_allocated(
variant = allocated_line.variant
stocks = variant.stocks.all()
- allocate_stock(order_line, COUNTRY_CODE, 3)
+ line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=3)
+ allocate_stocks([line_data], COUNTRY_CODE)
allocations = Allocation.objects.filter(order_line=order_line, stock__in=stocks)
assert allocations[0].quantity_allocated == 1
@@ -61,8 +104,9 @@ def test_allocate_stock_partially_allocated_insufficient_stocks(
variant = allocated_line.variant
stocks = variant.stocks.all()
+ line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=6)
with pytest.raises(InsufficientStock):
- allocate_stock(order_line, COUNTRY_CODE, 6)
+ allocate_stocks([line_data], COUNTRY_CODE)
assert not Allocation.objects.filter(
order_line=order_line, stock__in=stocks
@@ -73,8 +117,44 @@ def test_allocate_stock_insufficient_stocks(order_line, variant_with_many_stocks
variant = variant_with_many_stocks
stocks = variant.stocks.all()
+ line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=10)
with pytest.raises(InsufficientStock):
- allocate_stock(order_line, COUNTRY_CODE, 10)
+ allocate_stocks([line_data], COUNTRY_CODE)
+
+ assert not Allocation.objects.filter(
+ order_line=order_line, stock__in=stocks
+ ).exists()
+
+
+def test_allocate_stock_insufficient_stocks_for_multiply_lines(
+ order_line, variant_with_many_stocks, product
+):
+ variant = variant_with_many_stocks
+ stocks = variant.stocks.all()
+
+ variant_2 = product.variants.first()
+
+ order_line_2 = OrderLine.objects.get(pk=order_line.pk)
+ order_line_2.pk = None
+ order_line_2.product_name = product.name
+ order_line_2.variant_name = variant_2.name
+ order_line_2.product_sku = variant_2.sku
+ order_line_2.variant = variant_2
+ order_line_2.save()
+
+ quantity_1 = 100
+ quantity_2 = 100
+ line_data_1 = OrderLineData(
+ line=order_line, variant=order_line.variant, quantity=quantity_1
+ )
+ line_data_2 = OrderLineData(
+ line=order_line_2, variant=variant_2, quantity=quantity_2
+ )
+
+ with pytest.raises(InsufficientStock) as exc:
+ allocate_stocks([line_data_1, line_data_2], COUNTRY_CODE)
+
+ assert set(exc._excinfo[1].items) == {str(variant), str(variant_2)}
assert not Allocation.objects.filter(
order_line=order_line, stock__in=stocks