Skip to content

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

Deallocate stocks for order lines in a bulk way (#6896)

Iga Karbowiakcd1840f16f06
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ed0cf8eb8e..8e847e1dd3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -57,6 +57,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Add SearchRank to search product by name and description. New enum added to `ProductOrderField` - `RANK` - which returns results sorted by search rank - #6872 by @d-wysocki
- Allocate stocks for order lines in a bulk way - #6877 by @IKarbowiak
- Add product description_plaintext to populatedb - #6894 by @d-wysocki
+- Deallocate stocks for order lines in a bulk way - #6896 by @IKarbowiak
# 2.11.1
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 3c18a24b09..342a24aa97 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -24,6 +24,9 @@ from ..discount.utils import (
increase_voucher_usage,
remove_voucher_usage_by_customer,
)
+from ..graphql.checkout.utils import (
+ prepare_insufficient_stock_checkout_validation_error,
+)
from ..order import OrderLineData, OrderStatus
from ..order.actions import order_created
from ..order.emails import send_order_confirmation, send_staff_order_confirmation
@@ -471,9 +474,8 @@ def _get_order_data(
discounts=discounts,
)
except InsufficientStock as e:
- raise ValidationError(
- f"Insufficient product stock: {', '.join(e.items)}", code=e.code
- )
+ error = prepare_insufficient_stock_checkout_validation_error(e)
+ raise error
except NotApplicable:
raise ValidationError(
"Voucher not applicable",
@@ -546,9 +548,9 @@ def complete_checkout(
try:
order_data = _get_order_data(manager, checkout, lines, discounts)
- except ValidationError as error:
+ except ValidationError as exc:
gateway.payment_refund_or_void(payment)
- raise error
+ raise exc
txn = _process_payment(
payment=payment, # type: ignore
@@ -578,8 +580,6 @@ def complete_checkout(
except InsufficientStock as e:
release_voucher_usage(order_data)
gateway.payment_refund_or_void(payment)
- raise ValidationError(
- f"Insufficient product stock: {', '.join(e.items)}", code=e.code
- )
-
+ error = prepare_insufficient_stock_checkout_validation_error(e)
+ raise error
return order, action_required, action_data
diff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.py
index cbfef941c4..849da7f9cf 100644
--- a/saleor/core/exceptions.py
+++ b/saleor/core/exceptions.py
@@ -1,23 +1,34 @@
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, List, Optional, Union
+
from ..checkout.error_codes import CheckoutErrorCode
+if TYPE_CHECKING:
+ from ..order.models import OrderLine
+ from ..product.models import ProductVariant
+
+
+@dataclass
+class InsufficientStockData:
+ variant: "ProductVariant"
+ order_line: Optional["OrderLine"] = None
+ warehouse_pk: Union[str, int, None] = None
+ available_quantity: Optional[int] = None
+
class InsufficientStock(Exception):
- def __init__(self, items, context=None):
- items = [str(item) for item in items]
- super().__init__(f"Insufficient stock for {', '.join(items)}")
+ def __init__(self, items: List[InsufficientStockData]):
+ variants = [str(item.variant) for item in items]
+ super().__init__(f"Insufficient stock for {', '.join(variants)}")
self.items = items
- self.context = context
self.code = CheckoutErrorCode.INSUFFICIENT_STOCK
class AllocationError(Exception):
- def __init__(self, order_line, quantity):
- super().__init__(
- f"Can't deallocate {quantity} for variant: {order_line.variant}"
- f" in order: {order_line.order}"
- )
- self.order_line = order_line
- self.quantity = quantity
+ def __init__(self, order_lines):
+ lines = [str(line) for line in order_lines]
+ super().__init__(f"Unable to deallocate stock for lines {', '.join(lines)}.")
+ self.order_lines = order_lines
class ReadOnlyException(Exception):
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 375ca47bd2..23185f0ec6 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -41,6 +41,7 @@ from ..product.types import ProductVariant
from ..shipping.types import ShippingMethod
from ..utils import get_user_country_context
from .types import Checkout, CheckoutLine
+from .utils import prepare_insufficient_stock_checkout_validation_error
ERROR_DOES_NOT_SHIP = "This checkout doesn't need shipping"
@@ -121,12 +122,15 @@ def check_lines_quantity(variants, quantities, country):
try:
check_stock_quantity_bulk(variants, country, quantities)
except InsufficientStock as e:
- remaining = e.context["available_quantity"]
- message = (
- f"Could not add items {', '.join(e.items)}. "
- f"Only {remaining} remaining in stock."
- )
- raise ValidationError({"quantity": ValidationError(message, code=e.code)})
+ errors = [
+ ValidationError(
+ f"Could not add items {item.variant}. "
+ f"Only {item.available_quantity} remaining in stock.",
+ code=e.code,
+ )
+ for item in e.items
+ ]
+ raise ValidationError({"quantity": errors})
def validate_variants_available_for_purchase(variants, channel_id):
@@ -335,9 +339,8 @@ class CheckoutCreate(ModelMutation, I18nMixin):
try:
add_variants_to_checkout(instance, variants, quantities)
except InsufficientStock as exc:
- raise ValidationError(
- f"Insufficient product stock: {', '.join(exc.items)}", code=exc.code
- )
+ error = prepare_insufficient_stock_checkout_validation_error(exc)
+ raise ValidationError({"lines": error})
except ProductNotPublished as exc:
raise ValidationError(
"Can't create checkout with unpublished product.",
@@ -426,10 +429,8 @@ class CheckoutLinesAdd(BaseMutation):
checkout, variant, quantity, replace=replace
)
except InsufficientStock as exc:
- raise ValidationError(
- f"Insufficient product stock: {', '.join(exc.items)}",
- code=exc.code,
- )
+ error = prepare_insufficient_stock_checkout_validation_error(exc)
+ raise ValidationError({"lines": error})
except ProductNotPublished as exc:
raise ValidationError(
"Can't add unpublished product.",
diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.py
index eb659a11ed..d119d82af0 100644
--- a/saleor/graphql/checkout/tests/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py
@@ -8,7 +8,7 @@ from ....checkout import calculations
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.models import Checkout
from ....checkout.utils import fetch_checkout_lines
-from ....core.exceptions import InsufficientStock
+from ....core.exceptions import InsufficientStock, InsufficientStockData
from ....core.taxes import zero_money
from ....order import OrderStatus
from ....order.models import Order
@@ -971,10 +971,12 @@ def test_order_already_exists(
def test_create_order_raises_insufficient_stock(
mocked_create_order, user_api_client, checkout_ready_to_complete, payment_dummy
):
- mocked_create_order.side_effect = InsufficientStock("InsufficientStock")
checkout = checkout_ready_to_complete
manager = get_plugins_manager()
lines = fetch_checkout_lines(checkout)
+ mocked_create_order.side_effect = InsufficientStock(
+ [InsufficientStockData(variant=lines[0].variant)]
+ )
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout, lines, checkout.shipping_address
)
diff --git a/saleor/graphql/checkout/utils.py b/saleor/graphql/checkout/utils.py
new file mode 100644
index 0000000000..179c80847a
--- /dev/null
+++ b/saleor/graphql/checkout/utils.py
@@ -0,0 +1,15 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+
+def prepare_insufficient_stock_checkout_validation_error(exc):
+ variants = [str(item.variant) for item in exc.items]
+ variant_ids = [
+ graphene.Node.to_global_id("ProductVariant", item.variant.pk)
+ for item in exc.items
+ ]
+ return ValidationError(
+ f"Insufficient product stock: {', '.join(variants)}",
+ code=exc.code.value,
+ params={"variants": variant_ids},
+ )
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index d6e11450b4..573ef474c0 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -29,6 +29,7 @@ from ...core.types.common import OrderError
from ...product.types import ProductVariant
from ..types import Order, OrderLine
from ..utils import (
+ prepare_insufficient_stock_order_validation_errors,
validate_draft_order,
validate_product_is_published_in_channel,
validate_variant_channel_listings,
@@ -369,14 +370,8 @@ class DraftOrderComplete(BaseMutation):
try:
allocate_stocks([line_data], country)
except InsufficientStock as exc:
- raise ValidationError(
- {
- "lines": ValidationError(
- f"Insufficient product stock: {', '.join(exc.items)}",
- code=OrderErrorCode.INSUFFICIENT_STOCK,
- )
- }
- )
+ errors = prepare_insufficient_stock_order_validation_errors(exc)
+ raise ValidationError({"lines": errors})
order_created(order, user=info.context.user, from_draft=True)
return DraftOrderComplete(order=order)
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index 6baab5cd41..ec7952c500 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -21,10 +21,10 @@ from ...core.mutations import BaseMutation
from ...core.scalars import PositiveDecimal
from ...core.types.common import OrderError
from ...core.utils import from_global_id_strict_type, get_duplicated_values
-from ...order.types import Fulfillment, FulfillmentLine, Order
from ...utils import get_user_or_app_from_context
from ...warehouse.types import Warehouse
-from ..types import OrderLine
+from ..types import Fulfillment, FulfillmentLine, Order, OrderLine
+from ..utils import prepare_insufficient_stock_order_validation_errors
class OrderFulfillStockInput(graphene.InputObjectType):
@@ -218,24 +218,8 @@ class OrderFulfill(BaseMutation):
user, order, dict(lines_for_warehouses), notify_customer
)
except InsufficientStock as exc:
- order_line_global_id = graphene.Node.to_global_id(
- "OrderLine", exc.context["order_line"].pk
- )
- warehouse_global_id = graphene.Node.to_global_id(
- "Warehouse", exc.context["warehouse_pk"]
- )
- raise ValidationError(
- {
- "stocks": ValidationError(
- f"Insufficient product stock: {', '.join(exc.items)}",
- code=OrderErrorCode.INSUFFICIENT_STOCK,
- params={
- "order_line": order_line_global_id,
- "warehouse": warehouse_global_id,
- },
- )
- }
- )
+ errors = prepare_insufficient_stock_order_validation_errors(exc)
+ raise ValidationError({"stocks": errors})
return OrderFulfill(fulfillments=fulfillments, order=order)
diff --git a/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py b/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py
new file mode 100644
index 0000000000..29f2ee90ae
--- /dev/null
+++ b/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py
@@ -0,0 +1,169 @@
+from unittest.mock import patch
+
+import graphene
+import pytest
+
+from .....payment import ChargeStatus
+from ....tests.utils import get_graphql_content
+
+
[email protected]_queries(autouse=False)
+@patch("saleor.order.actions.gateway.refund")
+def test_fulfillment_refund_products_order_lines(
+ mocked_refund,
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ payment_dummy,
+ count_queries,
+):
+ query = """
+ mutation OrderFulfillmentRefundProducts(
+ $order: ID!, $input: OrderRefundProductsInput!
+ ) {
+ orderFulfillmentRefundProducts(
+ order: $order,
+ input: $input
+ ) {
+ fulfillment{
+ id
+ status
+ lines{
+ id
+ quantity
+ orderLine{
+ id
+ }
+ }
+ }
+ orderErrors {
+ field
+ code
+ message
+ warehouse
+ orderLine
+ }
+ }
+ }
+ """
+ payment_dummy.total = order_with_lines.total_gross_amount
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ order_with_lines.payments.add(payment_dummy)
+ line_to_refund = order_with_lines.lines.first()
+ order_id = graphene.Node.to_global_id("Order", order_with_lines.pk)
+ line_id = graphene.Node.to_global_id("OrderLine", line_to_refund.pk)
+ variables = {
+ "order": order_id,
+ "input": {"orderLines": [{"orderLineId": line_id, "quantity": 2}]},
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ response = staff_api_client.post_graphql(query, variables)
+
+ content = get_graphql_content(response)
+ assert content["data"]["orderFulfillmentRefundProducts"]["fulfillment"]
+
+
[email protected]_queries(autouse=False)
+@patch("saleor.order.actions.gateway.refund")
+def test_fulfillment_return_products_order_lines(
+ mocked_refund,
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ payment_dummy,
+ count_queries,
+):
+ query = """
+ mutation OrderFulfillmentReturnProducts(
+ $order: ID!, $input: OrderReturnProductsInput!
+ ) {
+ orderFulfillmentReturnProducts(
+ order: $order,
+ input: $input
+ ) {
+ returnFulfillment{
+ id
+ status
+ lines{
+ id
+ quantity
+ orderLine{
+ id
+ }
+ }
+ }
+ replaceFulfillment{
+ id
+ status
+ lines{
+ id
+ quantity
+ orderLine{
+ id
+ }
+ }
+ }
+ order{
+ id
+ status
+ }
+ replaceOrder{
+ id
+ status
+ }
+ orderErrors {
+ field
+ code
+ message
+ warehouse
+ orderLine
+ }
+ }
+ }
+ """
+ payment_dummy.total = order_with_lines.total_gross_amount
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ order_with_lines.payments.add(payment_dummy)
+ line_to_return = order_with_lines.lines.first()
+ line_quantity_to_return = 2
+
+ line_to_replace = order_with_lines.lines.last()
+ line_quantity_to_replace = 1
+
+ order_id = graphene.Node.to_global_id("Order", order_with_lines.pk)
+ line_id = graphene.Node.to_global_id("OrderLine", line_to_return.pk)
+ replace_line_id = graphene.Node.to_global_id("OrderLine", line_to_replace.pk)
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "includeShippingCosts": True,
+ "orderLines": [
+ {
+ "orderLineId": line_id,
+ "quantity": line_quantity_to_return,
+ "replace": False,
+ },
+ {
+ "orderLineId": replace_line_id,
+ "quantity": line_quantity_to_replace,
+ "replace": True,
+ },
+ ],
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(query, variables)
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ assert data["returnFulfillment"]
+ assert data["replaceFulfillment"]
diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.py
index 164b7a5f88..8cfa3f45fb 100644
--- a/saleor/graphql/order/tests/test_fulfillment.py
+++ b/saleor/graphql/order/tests/test_fulfillment.py
@@ -3,7 +3,7 @@ from unittest.mock import patch
import graphene
from django.contrib.auth.models import AnonymousUser
-from ....core.exceptions import InsufficientStock
+from ....core.exceptions import InsufficientStock, InsufficientStockData
from ....order import OrderStatus
from ....order.error_codes import OrderErrorCode
from ....order.events import OrderEvents
@@ -398,12 +398,14 @@ def test_order_fulfill_warehouse_with_insufficient_stock_exception(
},
}
- error_context = {
- "order_line": order_line,
- "warehouse_pk": str(warehouse_no_shipping_zone.pk),
- }
mock_create_fulfillments.side_effect = InsufficientStock(
- [order_line.variant], error_context
+ [
+ InsufficientStockData(
+ variant=order_line.variant,
+ order_line=order_line,
+ warehouse_pk=warehouse_no_shipping_zone.pk,
+ )
+ ]
)
response = staff_api_client.post_graphql(
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index e89c71c21b..8140a7f9d6 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -187,7 +187,11 @@ def test_orderline_query(staff_api_client, permission_manage_orders, fulfilled_o
"Warehouse", allocation.stock.warehouse.pk
)
assert first_order_data_line["allocations"] == [
- {"id": allocation_id, "quantity": 0, "warehouse": {"id": warehouse_id}}
+ {
+ "id": allocation_id,
+ "quantity": allocation.quantity_allocated,
+ "warehouse": {"id": warehouse_id},
+ }
]
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index c0c66bdb3e..e7eee159a8 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -82,14 +82,8 @@ def validate_order_lines(order, country):
try:
check_stock_quantity(line.variant, country, line.quantity)
except InsufficientStock as exc:
- raise ValidationError(
- {
- "lines": ValidationError(
- f"Insufficient product stock: {', '.join(exc.items)}",
- code=OrderErrorCode.INSUFFICIENT_STOCK,
- )
- }
- )
+ errors = prepare_insufficient_stock_order_validation_errors(exc)
+ raise ValidationError({"lines": errors})
def validate_product_is_published(order):
@@ -217,3 +211,29 @@ def validate_draft_order(order, country):
validate_product_is_published(order)
validate_product_is_available_for_purchase(order)
validate_channel_is_active(order.channel)
+
+
+def prepare_insufficient_stock_order_validation_errors(exc):
+ errors = []
+ for item in exc.items:
+ order_line_global_id = (
+ graphene.Node.to_global_id("OrderLine", item.order_line.pk)
+ if item.order_line
+ else None
+ )
+ warehouse_global_id = (
+ graphene.Node.to_global_id("Warehouse", item.warehouse_pk)
+ if item.warehouse_pk
+ else None
+ )
+ errors.append(
+ ValidationError(
+ f"Insufficient product stock: {item.variant}",
+ code=OrderErrorCode.INSUFFICIENT_STOCK,
+ params={
+ "order_line": order_line_global_id,
+ "warehouse": warehouse_global_id,
+ },
+ )
+ )
+ return errors
diff --git a/saleor/order/__init__.py b/saleor/order/__init__.py
index 0ca10a6c5e..a0fae0557d 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -172,6 +172,7 @@ class OrderLineData:
quantity: int
variant: Optional["ProductVariant"] = None
replace: bool = False
+ warehouse_pk: Optional[str] = None
@dataclass
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 6c8fb3dd62..2c0f5851d3 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -1,14 +1,15 @@
import logging
+from collections import defaultdict
from copy import deepcopy
from decimal import Decimal
-from typing import TYPE_CHECKING, Dict, List, Optional, Tuple
+from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple
from django.contrib.sites.models import Site
from django.db import transaction
from ..account.models import User
from ..core import analytics
-from ..core.exceptions import AllocationError, InsufficientStock
+from ..core.exceptions import AllocationError, InsufficientStock, InsufficientStockData
from ..order.emails import send_order_confirmed
from ..payment import (
ChargeStatus,
@@ -24,7 +25,9 @@ from ..warehouse.management import (
deallocate_stock,
deallocate_stock_for_order,
decrease_stock,
+ get_order_lines_with_track_inventory,
)
+from ..warehouse.models import Stock
from . import (
FulfillmentLineData,
FulfillmentStatus,
@@ -308,14 +311,22 @@ def clean_mark_order_as_paid(order: "Order"):
)
-def fulfill_order_line(order_line, quantity, warehouse_pk):
+def fulfill_order_lines(order_lines_info: Iterable["OrderLineData"]):
"""Fulfill order line with given quantity."""
- if order_line.variant and order_line.variant.track_inventory:
- decrease_stock(order_line, quantity, warehouse_pk)
- order_line.quantity_fulfilled += quantity
- order_line.save(update_fields=["quantity_fulfilled"])
+ lines_to_decrease_stock = get_order_lines_with_track_inventory(order_lines_info)
+ if lines_to_decrease_stock:
+ decrease_stock(lines_to_decrease_stock)
+ order_lines = []
+ for line_info in order_lines_info:
+ line = line_info.line
+ line.quantity_fulfilled += line_info.quantity
+ order_lines.append(line)
+
+ OrderLine.objects.bulk_update(order_lines, ["quantity_fulfilled"])
def automatically_fulfill_digital_lines(order: "Order"):
"""Fulfill all digital lines which have enabled automatic fulfillment setting.
@@ -329,20 +340,33 @@ def automatically_fulfill_digital_lines(order: "Order"):
if not digital_lines:
return
fulfillment, _ = Fulfillment.objects.get_or_create(order=order)
+
+ fulfillments = []
+ lines_info = []
for line in digital_lines:
if not order_line_needs_automatic_fulfillment(line):
continue
- if line.variant:
- digital_content = line.variant.digital_content
+ variant = line.variant
+ if variant:
+ digital_content = variant.digital_content
digital_content.urls.create(line=line)
quantity = line.quantity
- FulfillmentLine.objects.create(
- fulfillment=fulfillment, order_line=line, quantity=quantity
+ fulfillments.append(
+ FulfillmentLine(fulfillment=fulfillment, order_line=line, quantity=quantity)
)
warehouse_pk = line.allocations.first().stock.warehouse.pk # type: ignore
- fulfill_order_line(
- order_line=line, quantity=quantity, warehouse_pk=warehouse_pk
+ lines_info.append(
+ OrderLineData(
+ line=line,
+ quantity=quantity,
+ variant=line.variant,
+ warehouse_pk=warehouse_pk,
+ )
)
+
+ FulfillmentLine.objects.bulk_create(fulfillments)
+ fulfill_order_lines(lines_info)
+
emails.send_fulfillment_confirmation_to_customer(
order, fulfillment, user=order.user
)
@@ -350,14 +374,14 @@ def automatically_fulfill_digital_lines(order: "Order"):
def _create_fulfillment_lines(
- fulfillment: Fulfillment, warehouse_pk: str, lines: List[Dict]
+ fulfillment: Fulfillment, warehouse_pk: str, lines_data: List[Dict]
) -> List[FulfillmentLine]:
"""Modify stocks and allocations. Return list of unsaved FulfillmentLines.
Args:
fulfillment (Fulfillment): Fulfillment to create lines
warehouse_pk (str): Warehouse to fulfill order.
- lines (List[Dict]): List with information from which system
+ lines_data (List[Dict]): List with information from which system
create FulfillmentLines. Example:
[
{
@@ -375,16 +399,41 @@ def _create_fulfillment_lines(
InsufficientStock: If system hasn't containt enough item in stock for any line.
"""
+ lines = [line_data["order_line"] for line_data in lines_data]
+ variants = [line.variant for line in lines]
+ stocks = Stock.objects.filter(
+ warehouse_id=warehouse_pk, product_variant__in=variants
+ ).select_related("product_variant")
+
+ variant_to_stock: Dict[str, List[Stock]] = defaultdict(list)
+ for stock in stocks:
+ variant_to_stock[stock.product_variant_id].append(stock)
+
+ insufficient_stocks = []
fulfillment_lines = []
- for line in lines:
+ lines_info = []
+ for line in lines_data:
quantity = line["quantity"]
order_line = line["order_line"]
if quantity > 0:
- 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)
- fulfill_order_line(order_line, quantity, warehouse_pk)
+ line_stocks = variant_to_stock.get(order_line.variant_id)
+ if line_stocks is None:
+ error_data = InsufficientStockData(
+ variant=order_line.variant,
+ order_line=order_line,
+ warehouse_pk=warehouse_pk,
+ )
+ insufficient_stocks.append(error_data)
+ continue
+ stock = line_stocks[0]
+ lines_info.append(
+ OrderLineData(
+ line=order_line,
+ quantity=quantity,
+ variant=order_line.variant,
+ warehouse_pk=warehouse_pk,
+ )
+ )
if order_line.is_digital:
order_line.variant.digital_content.urls.create(line=order_line)
fulfillment_lines.append(
@@ -395,6 +444,13 @@ def _create_fulfillment_lines(
stock=stock,
)
)
+
+ if insufficient_stocks:
+ raise InsufficientStock(insufficient_stocks)
+
+ if lines_info:
+ fulfill_order_lines(lines_info)
+
return fulfillment_lines
@@ -495,6 +551,7 @@ def _get_fulfillment_line(
return moved_line, fulfillment_line_existed
def _move_order_lines_to_target_fulfillment(
order_lines_to_move: List[OrderLineData],
lines_in_target_fulfillment: List[FulfillmentLine],
@@ -505,6 +562,7 @@ def _move_order_lines_to_target_fulfillment(
fulfillment_lines_to_update: List[FulfillmentLine] = []
order_lines_to_update: List[OrderLine] = []
+ lines_to_dellocate: List[OrderLineData] = []
for line_data in order_lines_to_move:
line_to_move = line_data.line
quantity_to_move = line_data.quantity
@@ -535,10 +593,17 @@ def _move_order_lines_to_target_fulfillment(
line_allocations_exists = line_to_move.allocations.exists()
if line_allocations_exists:
- try:
- deallocate_stock(line_to_move, unfulfilled_to_move)
- except AllocationError:
- logger.warning(f"Unable to deallocate stock for line {line_to_move.id}")
+ lines_to_dellocate.append(
+ OrderLineData(line=line_to_move, quantity=unfulfilled_to_move)
+ )
+
+ if lines_to_dellocate:
+ try:
+ deallocate_stock(lines_to_dellocate)
+ except AllocationError as e:
+ logger.warning(
+ f"Unable to deallocate stock for line {', '.join(e.order_lines)}."
+ )
# update the fulfillment lines with new values
FulfillmentLine.objects.bulk_update(fulfillment_lines_to_update, ["quantity"])
@@ -546,6 +611,7 @@ def _move_order_lines_to_target_fulfillment(
OrderLine.objects.bulk_update(order_lines_to_update, ["quantity_fulfilled"])
def _move_fulfillment_lines_to_target_fulfillment(
fulfillment_lines_to_move: List[FulfillmentLineData],
lines_in_target_fulfillment: List[FulfillmentLine],
diff --git a/saleor/order/tests/test_fulfullments_actions.py b/saleor/order/tests/test_fulfullments_actions.py
index 63b558851b..de792a0a22 100644
--- a/saleor/order/tests/test_fulfullments_actions.py
+++ b/saleor/order/tests/test_fulfullments_actions.py
@@ -295,55 +295,6 @@ def test_create_fulfillments_without_allocations(
)
-@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
-def test_create_fulfillments_warehouse_with_out_of_stock(
- mock_email_fulfillment,
- staff_user,
- order_with_lines,
- warehouse,
-):
- order = order_with_lines
- order_line1, order_line2 = order.lines.all()
- order_line1.allocations.all().delete()
- stock = order_line1.variant.stocks.get(warehouse=warehouse)
- stock.quantity = 2
- stock.save(update_fields=["quantity"])
- fulfillment_lines_for_warehouses = {
- str(warehouse.pk): [
- {"order_line": order_line1, "quantity": 3},
- {"order_line": order_line2, "quantity": 2},
- ]
- }
-
- with pytest.raises(InsufficientStock) as exc:
- create_fulfillments(staff_user, order, fulfillment_lines_for_warehouses, True)
-
- assert exc.value.items == [str(order_line1.variant)]
- assert exc.value.context == {
- "order_line": order_line1,
- "warehouse_pk": str(warehouse.pk),
- }
-
- order.refresh_from_db()
- assert FulfillmentLine.objects.filter(fulfillment__order=order).count() == 0
-
- assert order.status == OrderStatus.UNFULFILLED
- assert order.fulfillments.all().count() == 0
-
- order_line1, order_line2 = order.lines.all()
- assert order_line1.quantity_fulfilled == 0
- assert order_line2.quantity_fulfilled == 0
-
- assert (
- Allocation.objects.filter(
- order_line__order=order, quantity_allocated__gt=0
- ).count()
- == 1
- )
-
- mock_email_fulfillment.assert_not_called()
-
-
@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
def test_create_fulfillments_warehouse_without_stock(
mock_email_fulfillment,
@@ -363,10 +314,14 @@ 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.items == [str(order_line1.variant)]
- assert exc.value.context == {
- "order_line": order_line1,
- "warehouse_pk": str(warehouse_no_shipping_zone.pk),
+ assert len(exc.value.items) == 2
+ assert {item.variant for item in exc.value.items} == {
+ order_line1.variant,
+ order_line2.variant,
+ }
+ assert {item.order_line for item in exc.value.items} == {order_line1, order_line2}
+ assert {item.warehouse_pk for item in exc.value.items} == {
+ str(warehouse_no_shipping_zone.pk)
}
order.refresh_from_db()
@@ -405,11 +360,10 @@ 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.items == [str(order_line.variant)]
- assert exc.value.context == {
- "order_line": order_line,
- "warehouse_pk": str(warehouse_no_shipping_zone.pk),
- }
+ assert len(exc.value.items) == 1
+ assert exc.value.items[0].variant == order_line.variant
+ assert exc.value.items[0].order_line == order_line
+ assert exc.value.items[0].warehouse_pk == str(warehouse_no_shipping_zone.pk)
order.refresh_from_db()
assert FulfillmentLine.objects.filter(fulfillment__order=order).count() == 0
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index da6b71916e..e63d6e96db 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -4,6 +4,7 @@ from unittest.mock import patch
import pytest
from prices import Money, TaxedMoney
+from ...order import OrderLineData
from ...payment import ChargeStatus, PaymentError, TransactionKind
from ...payment.models import Payment
from ...plugins.manager import get_plugins_manager
@@ -16,7 +17,7 @@ from ..actions import (
cancel_fulfillment,
cancel_order,
clean_mark_order_as_paid,
- fulfill_order_line,
+ fulfill_order_lines,
handle_fully_paid_order,
mark_order_as_paid,
order_refunded,
@@ -254,7 +255,7 @@ def test_order_refunded(
)
-def test_fulfill_order_line(order_with_lines):
+def test_fulfill_order_lines(order_with_lines):
order = order_with_lines
line = order.lines.first()
quantity_fulfilled_before = line.quantity_fulfilled
@@ -262,23 +263,78 @@ def test_fulfill_order_line(order_with_lines):
stock = Stock.objects.get(product_variant=variant)
stock_quantity_after = stock.quantity - line.quantity
- fulfill_order_line(line, line.quantity, stock.warehouse.pk)
+ fulfill_order_lines(
+ [
+ OrderLineData(
+ line=line,
+ quantity=line.quantity,
+ variant=variant,
+ warehouse_pk=stock.warehouse.pk,
+ )
+ ],
+ )
stock.refresh_from_db()
assert stock.quantity == stock_quantity_after
assert line.quantity_fulfilled == quantity_fulfilled_before + line.quantity
-def test_fulfill_order_line_with_variant_deleted(order_with_lines):
+def test_fulfill_order_lines_multiply_lines(order_with_lines):
+ order = order_with_lines
+ lines = order.lines.all()
+
+ assert lines.count() > 1
+
+ quantity_fulfilled_before_1 = lines[0].quantity_fulfilled
+ variant_1 = lines[0].variant
+ stock_1 = Stock.objects.get(product_variant=variant_1)
+ stock_quantity_after_1 = stock_1.quantity - lines[0].quantity
+
+ quantity_fulfilled_before_2 = lines[1].quantity_fulfilled
+ variant_2 = lines[1].variant
+ stock_2 = Stock.objects.get(product_variant=variant_2)
+ stock_quantity_after_2 = stock_2.quantity - lines[1].quantity
+
+ fulfill_order_lines(
+ [
+ OrderLineData(
+ line=lines[0],
+ quantity=lines[0].quantity,
+ variant=variant_1,
+ warehouse_pk=stock_1.warehouse.pk,
+ ),
+ OrderLineData(
+ line=lines[1],
+ quantity=lines[1].quantity,
+ variant=variant_2,
+ warehouse_pk=stock_2.warehouse.pk,
+ ),
+ ],
+ )
+
+ stock_1.refresh_from_db()
+ assert stock_1.quantity == stock_quantity_after_1
+ assert (
+ lines[0].quantity_fulfilled == quantity_fulfilled_before_1 + lines[0].quantity
+ )
+
+ stock_2.refresh_from_db()
+ assert stock_2.quantity == stock_quantity_after_2
+ assert (
+ lines[1].quantity_fulfilled == quantity_fulfilled_before_2 + lines[1].quantity
+ )
+
+
+def test_fulfill_order_lines_with_variant_deleted(order_with_lines):
line = order_with_lines.lines.first()
line.variant.delete()
line.refresh_from_db()
- fulfill_order_line(line, line.quantity, "warehouse_pk")
+ fulfill_order_lines([OrderLineData(line=line, quantity=line.quantity)])
-def test_fulfill_order_line_without_inventory_tracking(order_with_lines):
+def test_fulfill_order_lines_without_inventory_tracking(order_with_lines):
order = order_with_lines
line = order.lines.first()
quantity_fulfilled_before = line.quantity_fulfilled
@@ -290,7 +346,16 @@ def test_fulfill_order_line_without_inventory_tracking(order_with_lines):
# stock should not change
stock_quantity_after = stock.quantity
- fulfill_order_line(line, line.quantity, stock.warehouse.pk)
+ fulfill_order_lines(
+ [
+ OrderLineData(
+ line=line,
+ quantity=line.quantity,
+ variant=variant,
+ warehouse_pk=stock.warehouse.pk,
+ )
+ ]
+ )
stock.refresh_from_db()
assert stock.quantity == stock_quantity_after
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index c20c9e1db8..9f3c502633 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -12,7 +12,7 @@ from ..core.taxes import zero_money
from ..core.weight import zero_weight
from ..discount.models import NotApplicable, Voucher, VoucherType
from ..discount.utils import get_products_voucher_discount, validate_voucher_in_order
-from ..order import FulfillmentStatus, OrderStatus
+from ..order import FulfillmentStatus, OrderLineData, OrderStatus
from ..order.models import Order, OrderLine
from ..plugins.manager import get_plugins_manager
from ..product.utils.digital_products import get_default_digital_content_settings
@@ -335,10 +335,13 @@ def restock_order_lines(order):
shipping_zones__countries__contains=country
).first()
+ dellocating_stock_lines: List[OrderLineData] = []
for line in order:
if line.variant and line.variant.track_inventory:
if line.quantity_unfulfilled > 0:
- deallocate_stock(line, line.quantity_unfulfilled)
+ dellocating_stock_lines.append(
+ OrderLineData(line=line, quantity=line.quantity_unfulfilled)
+ )
if line.quantity_fulfilled > 0:
allocation = line.allocations.first()
warehouse = (
@@ -350,6 +353,9 @@ def restock_order_lines(order):
line.quantity_fulfilled = 0
line.save(update_fields=["quantity_fulfilled"])
+ if dellocating_stock_lines:
+ deallocate_stock(dellocating_stock_lines)
+
def restock_fulfillment_lines(fulfillment, warehouse):
"""Return fulfilled products to corresponding stocks.
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 63110ec758..e1bd70c5b7 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -53,8 +53,8 @@ from ..discount.models import (
)
from ..giftcard.models import GiftCard
from ..menu.models import Menu, MenuItem, MenuItemTranslation
-from ..order import OrderStatus
-from ..order.actions import cancel_fulfillment, fulfill_order_line
+from ..order import OrderLineData, OrderStatus
+from ..order.actions import cancel_fulfillment, fulfill_order_lines
from ..order.events import OrderEvents
from ..order.models import FulfillmentStatus, Order, OrderEvent, OrderLine
from ..order.utils import recalculate_order
@@ -2445,9 +2445,17 @@ def fulfilled_order(order_with_lines):
stock_2 = line_2.allocations.get().stock
warehouse_2_pk = stock_2.warehouse.pk
fulfillment.lines.create(order_line=line_1, quantity=line_1.quantity, stock=stock_1)
- fulfill_order_line(line_1, line_1.quantity, warehouse_1_pk)
fulfillment.lines.create(order_line=line_2, quantity=line_2.quantity, stock=stock_2)
- fulfill_order_line(line_2, line_2.quantity, warehouse_2_pk)
+ fulfill_order_lines(
+ [
+ OrderLineData(
+ line=line_1, quantity=line_1.quantity, warehouse_pk=warehouse_1_pk
+ ),
+ OrderLineData(
+ line=line_2, quantity=line_2.quantity, warehouse_pk=warehouse_2_pk
+ ),
+ ],
+ )
order.status = OrderStatus.FULFILLED
order.save(update_fields=["status"])
return order
@@ -2463,7 +2471,9 @@ def fulfilled_order_without_inventory_tracking(
stock = line.variant.stocks.get()
warehouse_pk = stock.warehouse.pk
fulfillment.lines.create(order_line=line, quantity=line.quantity, stock=stock)
- fulfill_order_line(line, line.quantity, warehouse_pk)
+ fulfill_order_lines(
+ [OrderLineData(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk)]
+ )
order.status = OrderStatus.FULFILLED
order.save(update_fields=["status"])
return order
diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.py
index 43a06b9ed7..effc965193 100644
--- a/saleor/warehouse/availability.py
+++ b/saleor/warehouse/availability.py
@@ -1,10 +1,10 @@
from collections import defaultdict
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, List
from django.db.models import Sum
from django.db.models.functions import Coalesce
-from ..core.exceptions import InsufficientStock
+from ..core.exceptions import InsufficientStock, InsufficientStockData
from .models import Stock, StockQuerySet
if TYPE_CHECKING:
@@ -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([InsufficientStockData(variant=variant)])
if quantity > _get_available_quantity(stocks):
- raise InsufficientStock([variant])
+ raise InsufficientStock([InsufficientStockData(variant=variant)])
def check_stock_quantity_bulk(variants, country_code, quantities):
@@ -52,21 +52,29 @@ def check_stock_quantity_bulk(variants, country_code, quantities):
for stock in all_variants_stocks:
variant_stocks[stock.product_variant_id].append(stock)
+ insufficient_stocks: List[InsufficientStockData] = []
for variant, quantity in zip(variants, quantities):
stocks = variant_stocks.get(variant.pk, [])
available_quantity = sum([stock.available_quantity for stock in stocks])
if not stocks:
- raise InsufficientStock(
- [variant], context={"available_quantity": available_quantity}
+ insufficient_stocks.append(
+ InsufficientStockData(
+ variant=variant, available_quantity=available_quantity
+ )
)
if variant.track_inventory:
if quantity > available_quantity:
- raise InsufficientStock(
- [variant], context={"available_quantity": available_quantity}
+ insufficient_stocks.append(
+ InsufficientStockData(
+ variant=variant, available_quantity=available_quantity
+ )
)
+ if insufficient_stocks:
+ raise InsufficientStock(insufficient_stocks)
+
def get_available_quantity(variant: "ProductVariant", country_code: str) -> int:
"""Return available quantity for given product in given country."""
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index 95b3fb0e30..e931a2d6f8 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -3,15 +3,13 @@ from typing import TYPE_CHECKING, Dict, Iterable, List
from django.db import transaction
from django.db.models import F, Sum
-from django.db.models.functions import Coalesce
-from ..core.exceptions import AllocationError, InsufficientStock
+from ..core.exceptions import AllocationError, InsufficientStock, InsufficientStockData
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"])
@@ -30,11 +28,10 @@ def allocate_stocks(order_lines_info: Iterable["OrderLineData"], country_code: s
"""
# 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
- ]
+ order_lines_info = get_order_lines_with_track_inventory(order_lines_info)
+ if not order_lines_info:
+ return
+
variants = [line_info.variant for line_info in order_lines_info]
stocks = (
@@ -63,7 +60,7 @@ def allocate_stocks(order_lines_info: Iterable["OrderLineData"], country_code: s
variant = stock_data.pop("product_variant")
variant_to_stocks[variant].append(StockData(**stock_data))
- insufficient_stock: List["ProductVariant"] = []
+ insufficient_stock: List[InsufficientStockData] = []
allocations: List[Allocation] = []
for line_info in order_lines_info:
stocks = variant_to_stocks[line_info.variant.pk] # type: ignore
@@ -83,7 +80,7 @@ def _create_allocations(
line_info: "OrderLineData",
stocks: List[StockData],
quantity_allocation_for_stocks: dict,
- insufficient_stock: List["ProductVariant"],
+ insufficient_stock: List[InsufficientStockData],
):
quantity = line_info.quantity
quantity_allocated = 0
@@ -112,22 +109,28 @@ def _create_allocations(
return insufficient_stock, allocations
if not quantity_allocated == quantity:
- insufficient_stock.append(line_info.variant) # type: ignore
+ insufficient_stock.append(
+ InsufficientStockData(
+ variant=line_info.variant, order_line=line_info.line # type: ignore
+ )
+ )
return insufficient_stock, []
@transaction.atomic
-def deallocate_stock(order_line: "OrderLine", quantity: int):
- """Deallocate stocks for given `order_line`.
+def deallocate_stock(order_lines_data: Iterable["OrderLineData"]):
+ """Deallocate stocks for given `order_lines`.
- Function lock for update stocks and allocations related to given `order_line`.
+ Function lock for update stocks and allocations related to given `order_lines`.
Iterate over allocations sorted by `stock.pk` and deallocate as many items
as needed of available in stock for order line, until deallocated all required
quantity for the order line. If there is less quantity in stocks then
raise an exception.
"""
- allocations = (
- order_line.allocations.select_related("stock")
+ lines = [line_info.line for line_info in order_lines_data]
+ lines_allocations = (
+ Allocation.objects.filter(order_line__in=lines)
+ .select_related("stock")
.select_for_update(
of=(
"self",
@@ -136,21 +139,37 @@ def deallocate_stock(order_line: "OrderLine", quantity: int):
)
.order_by("stock__pk")
)
- quantity_dealocated = 0
- for allocation in allocations:
- quantity_to_deallocate = min(
- (quantity - quantity_dealocated), allocation.quantity_allocated
- )
- if quantity_to_deallocate > 0:
- allocation.quantity_allocated = (
- F("quantity_allocated") - quantity_to_deallocate
+
+ line_to_allocations: Dict[int, List[Allocation]] = defaultdict(list)
+ for allocation in lines_allocations:
+ line_to_allocations[allocation.order_line_id].append(allocation)
+
+ allocations_to_update = []
+ not_dellocated_lines = []
+ for line_info in order_lines_data:
+ order_line = line_info.line
+ quantity = line_info.quantity
+ allocations = line_to_allocations[order_line.pk]
+ quantity_dealocated = 0
+ for allocation in allocations:
+ quantity_to_deallocate = min(
+ (quantity - quantity_dealocated), allocation.quantity_allocated
)
- quantity_dealocated += quantity_to_deallocate
- if quantity_dealocated == quantity:
- Allocation.objects.bulk_update(allocations, ["quantity_allocated"])
- break
- if not quantity_dealocated == quantity:
- raise AllocationError(order_line, quantity)
+ if quantity_to_deallocate > 0:
+ allocation.quantity_allocated = (
+ allocation.quantity_allocated - quantity_to_deallocate
+ )
+ quantity_dealocated += quantity_to_deallocate
+ allocations_to_update.append(allocation)
+ if quantity_dealocated == quantity:
+ break
+ if not quantity_dealocated == quantity:
+ not_dellocated_lines.append(order_line)
+
+ if not_dellocated_lines:
+ raise AllocationError(not_dellocated_lines)
+
+ Allocation.objects.bulk_update(allocations_to_update, ["quantity_allocated"])
@transaction.atomic
@@ -193,8 +212,8 @@ def increase_stock(
@transaction.atomic
-def decrease_stock(order_line: "OrderLine", quantity: int, warehouse_pk: str):
- """Decrease stock quantity for given `order_line` in given warehouse.
+def decrease_stock(order_lines_info: Iterable["OrderLineData"]):
+ """Decrease stocks quantities for given `order_lines` in given warehouses.
Function deallocate as many quantities as requested if order_line has less quantity
from requested function deallocate whole quantity. Next function try to find the
@@ -202,31 +221,100 @@ def decrease_stock(order_line: "OrderLine", quantity: int, warehouse_pk: str):
the function raise InsufficientStock exception. When the stock has enough quantity
function decrease it by given value.
"""
+ variants = [line_info.variant for line_info in order_lines_info]
+ warehouse_pks = [line_info.warehouse_pk for line_info in order_lines_info]
try:
- deallocate_stock(order_line, quantity)
- except AllocationError:
- order_line.allocations.update(quantity_allocated=0)
+ deallocate_stock(order_lines_info)
+ except AllocationError as exc:
+ Allocation.objects.filter(order_line__in=exc.order_lines).update(
+ quantity_allocated=0
+ )
- try:
- stock = (
- order_line.variant.stocks.select_for_update() # type: ignore
- .prefetch_related("allocations")
- .get(warehouse__pk=warehouse_pk)
+ stocks = (
+ Stock.objects.select_for_update(of=("self",))
+ .filter(product_variant__in=variants)
+ .filter(warehouse_id__in=warehouse_pks)
+ .select_related("product_variant", "warehouse")
+ .order_by("pk")
+ )
+
+ variant_and_warehouse_to_stock: Dict[int, Dict[str, Stock]] = defaultdict(dict)
+ for stock in stocks:
+ variant_and_warehouse_to_stock[stock.product_variant_id][
+ str(stock.warehouse_id)
+ ] = stock
+
+ quantity_allocation_list = list(
+ Allocation.objects.filter(
+ stock__in=stocks,
+ quantity_allocated__gt=0,
+ )
+ .values("stock")
+ .annotate(Sum("quantity_allocated"))
+ )
+
+ quantity_allocation_for_stocks: Dict[int, int] = defaultdict(int)
+ for allocation in quantity_allocation_list:
+ quantity_allocation_for_stocks[allocation["stock"]] += allocation[
+ "quantity_allocated__sum"
+ ]
+
+ _decrease_stocks_quantity(
+ order_lines_info, variant_and_warehouse_to_stock, quantity_allocation_for_stocks
+ )
+
+
+def _decrease_stocks_quantity(
+ order_lines_info: Iterable["OrderLineData"],
+ variant_and_warehouse_to_stock: Dict[int, Dict[str, Stock]],
+ quantity_allocation_for_stocks: Dict[int, int],
+):
+ insufficient_stocks: List[InsufficientStockData] = []
+ stocks_to_update = []
+ for line_info in order_lines_info:
+ variant = line_info.variant
+ warehouse_pk = str(line_info.warehouse_pk)
+ stock = variant_and_warehouse_to_stock.get(variant.pk, {}).get( # type: ignore
+ warehouse_pk
)
- except Stock.DoesNotExist:
- error_context = {"order_line": order_line, "warehouse_pk": warehouse_pk}
- raise InsufficientStock([order_line.variant], error_context)
+ if stock is None:
+ insufficient_stocks.append(
+ InsufficientStockData(
+ variant, line_info.line, warehouse_pk # type: ignore
+ )
+ )
+ continue
+
+ quantity_allocated = quantity_allocation_for_stocks.get(stock.pk, 0)
+
+ if stock.quantity - quantity_allocated < line_info.quantity:
+ insufficient_stocks.append(
+ InsufficientStockData(
+ variant=variant, # type: ignore
+ order_line=line_info.line,
+ warehouse_pk=warehouse_pk,
+ )
+ )
+ continue
- quantity_allocated = stock.allocations.aggregate(
- quantity_allocated=Coalesce(Sum("quantity_allocated"), 0)
- )["quantity_allocated"]
+ stock.quantity = stock.quantity - line_info.quantity
+ stocks_to_update.append(stock)
- if stock.quantity - quantity_allocated < quantity:
- error_context = {"order_line": order_line, "warehouse_pk": warehouse_pk}
- raise InsufficientStock([order_line.variant], error_context)
+ if insufficient_stocks:
+ raise InsufficientStock(insufficient_stocks)
- stock.quantity = F("quantity") - quantity
- stock.save(update_fields=["quantity"])
+ Stock.objects.bulk_update(stocks_to_update, ["quantity"])
+
+
+def get_order_lines_with_track_inventory(
+ order_lines_info: Iterable["OrderLineData"],
+) -> Iterable["OrderLineData"]:
+ """Return order lines with variants with track inventory set to True."""
+ return [
+ line_info
+ for line_info in order_lines_info
+ if line_info.variant and line_info.variant.track_inventory
+ ]
@transaction.atomic
diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.py
index 561ad429b8..e43ec60aa7 100644
--- a/saleor/warehouse/tests/test_stock_management.py
+++ b/saleor/warehouse/tests/test_stock_management.py
@@ -154,7 +154,7 @@ def test_allocate_stock_insufficient_stocks_for_multiply_lines(
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 set(item.variant for item in exc._excinfo[1].items) == {variant, variant_2}
assert not Allocation.objects.filter(
order_line=order_line, stock__in=stocks
@@ -168,7 +168,13 @@ def test_deallocate_stock(allocation):
allocation.quantity_allocated = 80
allocation.save(update_fields=["quantity_allocated"])
- deallocate_stock(allocation.order_line, 80)
+ deallocate_stock(
+ [
+ OrderLineData(
+ line=allocation.order_line, quantity=80, variant=stock.product_variant
+ )
+ ]
+ )
stock.refresh_from_db()
assert stock.quantity == 100
@@ -183,7 +189,13 @@ def test_deallocate_stock_partially(allocation):
allocation.quantity_allocated = 80
allocation.save(update_fields=["quantity_allocated"])
- deallocate_stock(allocation.order_line, 50)
+ deallocate_stock(
+ [
+ OrderLineData(
+ line=allocation.order_line, quantity=50, variant=stock.product_variant
+ )
+ ]
+ )
stock.refresh_from_db()
assert stock.quantity == 100
@@ -196,7 +208,9 @@ def test_deallocate_stock_many_allocations(
):
order_line = order_line_with_allocation_in_many_stocks
- deallocate_stock(order_line, 3)
+ deallocate_stock(
+ [OrderLineData(line=order_line, quantity=3, variant=order_line.variant)]
+ )
allocations = order_line.allocations.all()
assert allocations[0].quantity_allocated == 0
@@ -208,7 +222,9 @@ def test_deallocate_stock_many_allocations_partially(
):
order_line = order_line_with_allocation_in_many_stocks
- deallocate_stock(order_line, 1)
+ deallocate_stock(
+ [OrderLineData(line=order_line, quantity=1, variant=order_line.variant)]
+ )
allocations = order_line.allocations.all()
assert allocations[0].quantity_allocated == 1
@@ -266,7 +282,16 @@ def test_decrease_stock(allocation):
allocation.save(update_fields=["quantity_allocated"])
warehouse_pk = allocation.stock.warehouse.pk
- decrease_stock(allocation.order_line, 50, warehouse_pk)
+ decrease_stock(
+ [
+ OrderLineData(
+ line=allocation.order_line,
+ quantity=50,
+ variant=stock.product_variant,
+ warehouse_pk=warehouse_pk,
+ )
+ ],
+ )
stock.refresh_from_db()
assert stock.quantity == 50
@@ -274,6 +299,44 @@ def test_decrease_stock(allocation):
assert allocation.quantity_allocated == 30
+def test_decrease_stock_multiply_lines(allocations):
+ allocation_1 = allocations[0]
+ allocation_2 = allocations[0]
+
+ stock = allocation_1.stock
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+ allocation_1.quantity_allocated = 80
+ allocation_1.save(update_fields=["quantity_allocated"])
+ warehouse_pk_1 = allocation_1.stock.warehouse.pk
+
+ allocation_2.quantity_allocated = 80
+ allocation_2.save(update_fields=["quantity_allocated"])
+ warehouse_pk_2 = allocation_2.stock.warehouse.pk
+
+ decrease_stock(
+ [
+ OrderLineData(
+ line=allocation_1.order_line,
+ quantity=50,
+ variant=allocation_1.order_line.variant,
+ warehouse_pk=warehouse_pk_1,
+ ),
+ OrderLineData(
+ line=allocation_2.order_line,
+ quantity=20,
+ variant=allocation_2.order_line.variant,
+ warehouse_pk=warehouse_pk_2,
+ ),
+ ],
+ )
+
+ stock.refresh_from_db()
+ assert stock.quantity == 30
+ allocation_1.refresh_from_db()
+ assert allocation_1.quantity_allocated == 10
+
+
def test_decrease_stock_partially(allocation):
stock = allocation.stock
stock.quantity = 100
@@ -282,7 +345,16 @@ def test_decrease_stock_partially(allocation):
allocation.save(update_fields=["quantity_allocated"])
warehouse_pk = allocation.stock.warehouse.pk
- decrease_stock(allocation.order_line, 80, warehouse_pk)
+ decrease_stock(
+ [
+ OrderLineData(
+ line=allocation.order_line,
+ quantity=80,
+ variant=stock.product_variant,
+ warehouse_pk=str(warehouse_pk),
+ )
+ ],
+ )
stock.refresh_from_db()
assert stock.quantity == 20
@@ -297,7 +369,16 @@ def test_decrease_stock_many_allocations(
allocations = order_line.allocations.all()
warehouse_pk = allocations[1].stock.warehouse.pk
- decrease_stock(order_line, 3, warehouse_pk)
+ decrease_stock(
+ [
+ OrderLineData(
+ line=order_line,
+ quantity=3,
+ variant=order_line.variant,
+ warehouse_pk=str(warehouse_pk),
+ )
+ ],
+ )
assert allocations[0].quantity_allocated == 0
assert allocations[1].quantity_allocated == 0
@@ -312,7 +393,16 @@ def test_decrease_stock_many_allocations_partially(
allocations = order_line.allocations.all()
warehouse_pk = allocations[0].stock.warehouse.pk
- decrease_stock(order_line, 2, warehouse_pk)
+ decrease_stock(
+ [
+ OrderLineData(
+ line=order_line,
+ quantity=2,
+ variant=order_line.variant,
+ warehouse_pk=str(warehouse_pk),
+ )
+ ],
+ )
assert allocations[0].quantity_allocated == 0
assert allocations[1].quantity_allocated == 1
@@ -331,14 +421,50 @@ def test_decrease_stock_more_then_allocated(
)["quantity_allocated"]
assert quantity_allocated < 4
- decrease_stock(order_line, 4, warehouse_pk)
+ decrease_stock(
+ [
+ OrderLineData(
+ line=order_line,
+ quantity=4,
+ variant=order_line.variant,
+ warehouse_pk=warehouse_pk,
+ )
+ ],
+ )
+ allocations = order_line.allocations.all()
assert allocations[0].quantity_allocated == 0
assert allocations[1].quantity_allocated == 0
assert allocations[0].stock.quantity == 0
assert allocations[1].stock.quantity == 3
+def test_decrease_stock_insufficient_stock(allocation):
+ stock = allocation.stock
+ stock.quantity = 20
+ stock.save(update_fields=["quantity"])
+ allocation.quantity_allocated = 80
+ allocation.save(update_fields=["quantity_allocated"])
+ warehouse_pk = allocation.stock.warehouse.pk
+
+ with pytest.raises(InsufficientStock):
+ decrease_stock(
+ [
+ OrderLineData(
+ line=allocation.order_line,
+ quantity=50,
+ variant=stock.product_variant,
+ warehouse_pk=warehouse_pk,
+ )
+ ],
+ )
+
+ stock.refresh_from_db()
+ assert stock.quantity == 20
+ allocation.refresh_from_db()
+ assert allocation.quantity_allocated == 80
+
+
def test_deallocate_stock_for_order(
order_line_with_allocation_in_many_stocks,
):