Skip to content

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

Handle allocations when editing order (#6984)

Tomasz Szymańskief4d31a09e7c
diff --git a/saleor/attribute/tests/test_utils.py b/saleor/attribute/tests/test_utils.py
index 0e90cc130e..d13b09fba5 100644
--- a/saleor/attribute/tests/test_utils.py
+++ b/saleor/attribute/tests/test_utils.py
@@ -47,8 +47,8 @@ def test_associate_attribute_to_product_instance_without_values(product):
assert new_assignment.values.count() == 0
-def test_associate_attribute_to_product_instance_multiply_values(product):
- """Ensure multiply values in proper order are assigned."""
+def test_associate_attribute_to_product_instance_multiple_values(product):
+ """Ensure multiple values in proper order are assigned."""
old_assignment = product.attributes.first()
assert old_assignment is not None, "The product doesn't have attribute-values"
assert old_assignment.values.count() == 1
@@ -69,8 +69,8 @@ def test_associate_attribute_to_product_instance_multiply_values(product):
) == [(values[1].pk, 0), (values[0].pk, 1)]
-def test_associate_attribute_to_page_instance_multiply_values(page):
- """Ensure multiply values in proper order are assigned."""
+def test_associate_attribute_to_page_instance_multiple_values(page):
+ """Ensure multiple values in proper order are assigned."""
old_assignment = page.attributes.first()
assert old_assignment is not None, "The page doesn't have attribute-values"
assert old_assignment.values.count() == 1
@@ -91,8 +91,8 @@ def test_associate_attribute_to_page_instance_multiply_values(page):
) == [(values[1].pk, 0), (values[0].pk, 1)]
-def test_associate_attribute_to_variant_instance_multiply_values(variant):
- """Ensure multiply values in proper order are assigned."""
+def test_associate_attribute_to_variant_instance_multiple_values(variant):
+ """Ensure multiple values in proper order are assigned."""
attribute = variant.product.product_type.variant_attributes.first()
values = attribute.values.all()
diff --git a/saleor/graphql/account/tests/test_account_permission_group.py b/saleor/graphql/account/tests/test_account_permission_group.py
index 4e3b007067..309a4062e1 100644
--- a/saleor/graphql/account/tests/test_account_permission_group.py
+++ b/saleor/graphql/account/tests/test_account_permission_group.py
@@ -1392,7 +1392,7 @@ def test_permission_group_update_mutation_out_of_scope_users(
assert staff in group_users
-def test_permission_group_update_mutation_multiply_errors(
+def test_permission_group_update_mutation_multiple_errors(
permission_group_manage_users,
staff_user,
customer_user,
diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.py
index fb273b7149..ad5ee64050 100644
--- a/saleor/graphql/attribute/tests/test_utils.py
+++ b/saleor/graphql/attribute/tests/test_utils.py
@@ -250,7 +250,7 @@ def test_validate_attributes_input_for_product_lack_of_required_attribute(
}
-def test_validate_attributes_input_for_product_multiply_errors(
+def test_validate_attributes_input_for_product_multiple_errors(
weight_attribute, color_attribute, product_type
):
# given
@@ -545,7 +545,7 @@ def test_validate_attributes_input_for_page_lack_of_required_attribute(
}
-def test_validate_attributes_input_for_page_multiply_errors(
+def test_validate_attributes_input_for_page_multiple_errors(
weight_attribute, color_attribute, page_type
):
# given
@@ -838,7 +838,7 @@ def test_validate_attributes_input_empty_values_given(
}
-def test_validate_attributes_input_multiply_errors(
+def test_validate_attributes_input_multiple_errors(
weight_attribute, color_attribute, product_type
):
# given
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 9c1542ad22..788cc0c59d 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -3,9 +3,10 @@ from django.core.exceptions import ValidationError
from django.db import transaction
from ....account.models import User
+from ....core.exceptions import InsufficientStock
from ....core.permissions import OrderPermissions
from ....core.taxes import TaxError, zero_taxed_money
-from ....order import OrderStatus, events, models
+from ....order import OrderLineData, OrderStatus, events, models
from ....order.actions import (
cancel_order,
clean_mark_order_as_paid,
@@ -664,7 +665,9 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
def add_lines_to_order(order, lines_to_add):
try:
return [
- add_variant_to_order(order, variant, quantity)
+ add_variant_to_order(
+ order, variant, quantity, allocate_stock=order.is_unconfirmed()
+ )
for quantity, variant in lines_to_add
]
except TaxError as tax_error:
@@ -709,12 +712,22 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):
@classmethod
def perform_mutation(cls, _root, info, id):
- line = cls.get_node_or_error(info, id, only_type=OrderLine)
+ line = cls.get_node_or_error(
+ info,
+ id,
+ only_type=OrderLine,
+ )
order = line.order
cls.validate_order(line.order)
db_id = line.id
- delete_order_line(line)
+ line_info = OrderLineData(
+ line=line,
+ quantity=line.quantity,
+ variant=line.variant,
+ warehouse_pk=line.allocations.first().stock.warehouse.pk,
+ )
+ delete_order_line(line_info)
line.id = db_id
# Create the removal event
@@ -762,9 +775,21 @@ class OrderLineUpdate(EditableOrderValidationMixin, ModelMutation):
@classmethod
def save(cls, info, instance, cleaned_input):
- change_order_line_quantity(
- info.context.user, instance, instance.old_quantity, instance.quantity
+ line_info = OrderLineData(
+ line=instance,
+ quantity=instance.quantity,
+ variant=instance.variant,
+ warehouse_pk=instance.allocations.first().stock.warehouse.pk,
)
+ try:
+ change_order_line_quantity(
+ info.context.user, line_info, instance.old_quantity, instance.quantity
+ )
+ except InsufficientStock:
+ raise ValidationError(
+ "Cannot set new quantity because of insufficient stock.",
+ code=OrderErrorCode.INSUFFICIENT_STOCK,
+ )
recalculate_order(instance.order)
@classmethod
diff --git a/saleor/graphql/page/tests/test_page_type_update.py b/saleor/graphql/page/tests/test_page_type_update.py
index c51578e261..4a486339cb 100644
--- a/saleor/graphql/page/tests/test_page_type_update.py
+++ b/saleor/graphql/page/tests/test_page_type_update.py
@@ -311,7 +311,7 @@ def test_page_type_update_duplicated_slug(
assert errors[0]["field"] == "slug"
-def test_page_type_update_multiply_errors(
+def test_page_type_update_multiple_errors(
staff_api_client,
page_type,
permission_manage_page_types_and_attributes,
@@ -319,7 +319,7 @@ def test_page_type_update_multiply_errors(
size_page_attribute,
color_attribute,
):
- """Ensure that if multiply errors occurred all will raised."""
+ """Ensure that if multiple errors occurred all will be raised."""
# given
staff_user = staff_api_client.user
diff --git a/saleor/graphql/product/tests/test_attributes.py b/saleor/graphql/product/tests/test_attributes.py
index 2c9d728d2f..69e795655c 100644
--- a/saleor/graphql/product/tests/test_attributes.py
+++ b/saleor/graphql/product/tests/test_attributes.py
@@ -532,7 +532,7 @@ def test_assign_page_attribute_to_product_type(
assert errors[0]["attributes"] == [tag_page_attr_id]
-def test_assign_attribute_to_product_type_multiply_errors_returned(
+def test_assign_attribute_to_product_type_multiple_errors_returned(
staff_api_client,
permission_manage_product_types_and_attributes,
color_attribute,
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index 5ad5e25b4a..8fbda14fa8 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -581,22 +581,19 @@ def test_order_weight_add_new_variant(order_with_lines, product):
)
-def test_order_weight_change_line_quantity(staff_user, order_with_lines):
- line = order_with_lines.lines.first()
- new_quantity = line.quantity + 2
- change_order_line_quantity(staff_user, line, new_quantity, line.quantity)
- order_with_lines.refresh_from_db()
- assert order_with_lines.weight == _calculate_order_weight_from_lines(
- order_with_lines
- )
+def test_order_weight_change_line_quantity(staff_user, lines_info):
+ line_info = lines_info[0]
+ new_quantity = line_info.quantity + 2
+ change_order_line_quantity(staff_user, line_info, new_quantity, line_info.quantity)
+ order = line_info.line.order
+ assert order.weight == _calculate_order_weight_from_lines(order)
-def test_order_weight_delete_line(order_with_lines):
- line = order_with_lines.lines.first()
- delete_order_line(line)
- assert order_with_lines.weight == _calculate_order_weight_from_lines(
- order_with_lines
- )
+def test_order_weight_delete_line(lines_info):
+ order = lines_info[0].line.order
+ line_info = lines_info[0]
+ delete_order_line(line_info)
+ assert order.weight == _calculate_order_weight_from_lines(order)
def test_get_order_weight_non_existing_product(order_with_lines, product):
@@ -872,23 +869,23 @@ def test_category_voucher_checkout_discount_raises_not_applicable(
get_voucher_discount_for_order(order_with_lines)
-def test_ordered_item_change_quantity(staff_user, transactional_db, order_with_lines):
- assert not order_with_lines.events.count()
- lines = order_with_lines.lines.all()
- change_order_line_quantity(staff_user, lines[1], lines[1].quantity, 0)
- change_order_line_quantity(staff_user, lines[0], lines[0].quantity, 0)
- assert order_with_lines.get_total_quantity() == 0
+def test_ordered_item_change_quantity(staff_user, transactional_db, lines_info):
+ order = lines_info[0].line.order
+ assert not order.events.count()
+ change_order_line_quantity(staff_user, lines_info[1], lines_info[1].quantity, 0)
+ change_order_line_quantity(staff_user, lines_info[0], lines_info[0].quantity, 0)
+ assert order.get_total_quantity() == 0
def test_change_order_line_quantity_changes_total_prices(
- staff_user, transactional_db, order_with_lines
+ staff_user, transactional_db, lines_info
):
- assert not order_with_lines.events.count()
- line = order_with_lines.lines.all()[0]
- new_quantity = line.quantity + 1
- change_order_line_quantity(staff_user, line, line.quantity, new_quantity)
- line.refresh_from_db()
- assert line.total_price == line.unit_price * new_quantity
+ order = lines_info[0].line.order
+ assert not order.events.count()
+ line_info = lines_info[0]
+ new_quantity = line_info.quantity + 1
+ change_order_line_quantity(staff_user, line_info, line_info.quantity, new_quantity)
+ assert line_info.line.total_price == line_info.line.unit_price * new_quantity
@patch("saleor.order.actions.emails.send_fulfillment_confirmation")
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index e63d6e96db..62fb74090f 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -279,7 +279,7 @@ def test_fulfill_order_lines(order_with_lines):
assert line.quantity_fulfilled == quantity_fulfilled_before + line.quantity
-def test_fulfill_order_lines_multiply_lines(order_with_lines):
+def test_fulfill_order_lines_multiple_lines(order_with_lines):
order = order_with_lines
lines = order.lines.all()
diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.py
index f1642e1b3b..4934ed7efa 100644
--- a/saleor/order/tests/test_order_utils.py
+++ b/saleor/order/tests/test_order_utils.py
@@ -1,6 +1,6 @@
import pytest
-from .. import OrderStatus
+from .. import OrderLineData, OrderStatus
from ..events import OrderEvents
from ..models import Order, OrderEvent
from ..utils import change_order_line_quantity, match_orders_with_new_user
@@ -30,8 +30,17 @@ def test_change_quantity_generates_proper_event(
line = order_with_lines.lines.last()
line.quantity = previous_quantity
+ line_info = OrderLineData(
+ line=line,
+ quantity=line.quantity,
+ variant=line.variant,
+ warehouse_pk=line.allocations.first().stock.warehouse.pk,
+ )
+ stock = line.allocations.first().stock
+ stock.quantity = 5
+ stock.save(update_fields=["quantity"])
- change_order_line_quantity(staff_user, line, previous_quantity, new_quantity)
+ change_order_line_quantity(staff_user, line_info, previous_quantity, new_quantity)
if removed_count:
expected_type = OrderEvents.REMOVED_PRODUCTS
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 48e3efc2b5..6f22aa3118 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -19,7 +19,13 @@ from ..order.models import Order, OrderLine
from ..plugins.manager import get_plugins_manager
from ..product.utils.digital_products import get_default_digital_content_settings
from ..shipping.models import ShippingMethod
-from ..warehouse.management import deallocate_stock, increase_stock
+from ..warehouse.management import (
+ deallocate_stock,
+ decrease_allocations,
+ get_order_lines_with_track_inventory,
+ increase_allocations,
+ increase_stock,
+)
from ..warehouse.models import Warehouse
from . import events
@@ -289,7 +295,9 @@ def update_order_status(order):
@transaction.atomic
-def add_variant_to_order(order, variant, quantity, discounts=None):
+def add_variant_to_order(
+ order, variant, quantity, discounts=None, allocate_stock=False
+):
"""Add total_quantity of variant to order.
Returns an order line the variant was added to.
@@ -346,6 +354,18 @@ def add_variant_to_order(order, variant, quantity, discounts=None):
]
)
+ if allocate_stock:
+ increase_allocations(
+ [
+ OrderLineData(
+ line=line,
+ quantity=quantity,
+ variant=variant,
+ warehouse_pk=None,
+ )
+ ]
+ )
+
return line
@@ -367,9 +387,29 @@ def add_gift_card_to_order(order, gift_card, total_price_left):
return total_price_left
-def change_order_line_quantity(user, line, old_quantity, new_quantity):
+def _update_allocations_for_line(
+ line_info: OrderLineData, old_quantity: int, new_quantity: int
+):
+ if old_quantity == new_quantity:
+ return
+
+ if not get_order_lines_with_track_inventory([line_info]):
+ return
+
+ if old_quantity < new_quantity:
+ line_info.quantity = new_quantity - old_quantity
+ increase_allocations([line_info])
+ else:
+ line_info.quantity = old_quantity - new_quantity
+ decrease_allocations([line_info])
+
+
+def change_order_line_quantity(user, line_info, old_quantity: int, new_quantity: int):
"""Change the quantity of ordered items in a order line."""
+ line = line_info.line
if new_quantity:
+ if line.order.is_unconfirmed():
+ _update_allocations_for_line(line_info, old_quantity, new_quantity)
line.quantity = new_quantity
total_price_net_amount = line.quantity * line.unit_price_net_amount
total_price_gross_amount = line.quantity * line.unit_price_gross_amount
@@ -385,7 +425,7 @@ def change_order_line_quantity(user, line, old_quantity, new_quantity):
]
)
else:
- delete_order_line(line)
+ delete_order_line(line_info)
quantity_diff = old_quantity - new_quantity
@@ -400,9 +440,11 @@ def change_order_line_quantity(user, line, old_quantity, new_quantity):
)
-def delete_order_line(line):
+def delete_order_line(line_info):
"""Delete an order line from an order."""
- line.delete()
+ if line_info.line.order.is_unconfirmed():
+ decrease_allocations([line_info])
+ line_info.line.delete()
def restock_order_lines(order):
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 3717ac6a59..f297f70042 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -2349,6 +2349,19 @@ def order_with_lines(
return order
+def lines_info(order_with_lines):
+ return [
+ OrderLineData(
+ line=line,
+ quantity=line.quantity,
+ variant=line.variant,
+ warehouse_pk=line.allocations.first().stock.warehouse.pk,
+ )
+ for line in order_with_lines.lines.all()
+ ]
+
+
@pytest.fixture
def order_with_lines_and_events(order_with_lines, staff_user):
events = []
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index c1a048b392..e88f516a50 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -5,11 +5,11 @@ from django.db import transaction
from django.db.models import F, Sum
from ..core.exceptions import AllocationError, InsufficientStock, InsufficientStockData
+from ..order import OrderLineData
from ..product.models import ProductVariant
from .models import Allocation, Stock, Warehouse
if TYPE_CHECKING:
- from ..order import OrderLineData
from ..order.models import Order, OrderLine
@@ -219,7 +219,44 @@ def increase_stock(
@transaction.atomic
-def decrease_stock(order_lines_info: Iterable["OrderLineData"]):
+def increase_allocations(lines_info: Iterable["OrderLineData"]):
+ """Increase allocation for order lines with appropriate quantity."""
+ line_pks = [info.line.pk for info in lines_info]
+ allocations = list(
+ Allocation.objects.filter(order_line__in=line_pks)
+ .select_related("stock", "order_line")
+ .select_for_update(of=("self", "stock"))
+ )
+ # evaluate allocations query to trigger select_for_update lock
+ allocation_pks_to_delete = [alloc.pk for alloc in allocations]
+ allocation_quantity_map: Dict[int, list] = defaultdict(list)
+
+ for alloc in allocations:
+ allocation_quantity_map[alloc.order_line.pk].append(alloc.quantity_allocated)
+
+ for line_info in lines_info:
+ allocated = sum(allocation_quantity_map[line_info.line.pk])
+ # line_info.quantity resembles amount to add, sum it with already allocated.
+ line_info.quantity += allocated
+
+ Allocation.objects.filter(pk__in=allocation_pks_to_delete).delete()
+
+ allocate_stocks(
+ lines_info,
+ lines_info[0].line.order.shipping_address.country.code, # type: ignore
+ )
+
+
+def decrease_allocations(lines_info: Iterable["OrderLineData"]):
+ """Decreate allocations for provided order lines."""
+ tracked_lines = get_order_lines_with_track_inventory(lines_info)
+ if not tracked_lines:
+ return
+ decrease_stock(tracked_lines, update_stocks=False)
+
+
+def decrease_stock(order_lines_info: Iterable["OrderLineData"], update_stocks=True):
"""Decrease stocks quantities for given `order_lines` in given warehouses.
Function deallocate as many quantities as requested if order_line has less quantity
@@ -227,6 +264,8 @@ def decrease_stock(order_lines_info: Iterable["OrderLineData"]):
stock in a given warehouse, if stock not exists or have not enough stock,
the function raise InsufficientStock exception. When the stock has enough quantity
function decrease it by given value.
+ If update_stocks is False, allocations will decrease but stocks quantities
+ will stay unmodified (case of unconfirmed order editing).
"""
variants = [line_info.variant for line_info in order_lines_info]
warehouse_pks = [line_info.warehouse_pk for line_info in order_lines_info]
@@ -266,9 +305,12 @@ def decrease_stock(order_lines_info: Iterable["OrderLineData"]):
"quantity_allocated__sum"
]
- _decrease_stocks_quantity(
- order_lines_info, variant_and_warehouse_to_stock, quantity_allocation_for_stocks
- )
+ if update_stocks:
+ _decrease_stocks_quantity(
+ order_lines_info,
+ variant_and_warehouse_to_stock,
+ quantity_allocation_for_stocks,
+ )
def _decrease_stocks_quantity(
diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.py
index e43ec60aa7..e30ccf6086 100644
--- a/saleor/warehouse/tests/test_stock_management.py
+++ b/saleor/warehouse/tests/test_stock_management.py
@@ -11,6 +11,7 @@ from ..management import (
deallocate_stock,
deallocate_stock_for_order,
decrease_stock,
+ increase_allocations,
increase_stock,
)
from ..models import Allocation
@@ -32,7 +33,7 @@ def test_allocate_stocks(order_line, stock):
assert allocation.quantity_allocated == 50
-def test_allocate_stocks_multiply_lines(order_line, order, product, stock):
+def test_allocate_stocks_multiple_lines(order_line, order, product, stock):
stock.quantity = 100
stock.save(update_fields=["quantity"])
@@ -126,7 +127,7 @@ def test_allocate_stock_insufficient_stocks(order_line, variant_with_many_stocks
).exists()
-def test_allocate_stock_insufficient_stocks_for_multiply_lines(
+def test_allocate_stock_insufficient_stocks_for_multiple_lines(
order_line, variant_with_many_stocks, product
):
variant = variant_with_many_stocks
@@ -274,6 +275,62 @@ def test_increase_stock_with_new_allocation(order_line, stock):
assert allocation.quantity_allocated == 50
[email protected]("quantity", (19, 20))
+def test_increase_allocations(quantity, allocation):
+ order_line = allocation.order_line
+ order_line_info = OrderLineData(
+ line=order_line,
+ quantity=quantity,
+ variant=order_line.variant,
+ warehouse_pk=allocation.stock.warehouse.pk,
+ )
+ stock = allocation.stock
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+ initially_allocated = 80
+ allocation.quantity_allocated = initially_allocated
+ allocation.save(update_fields=["quantity_allocated"])
+
+ increase_allocations([order_line_info])
+
+ stock.refresh_from_db()
+ assert stock.quantity == 100
+ assert (
+ order_line.allocations.all().aggregate(Sum("quantity_allocated"))[
+ "quantity_allocated__sum"
+ ]
+ == initially_allocated + quantity
+ )
+
+
+def test_increase_allocation_insufficient_stock(allocation):
+ order_line = allocation.order_line
+ order_line_info = OrderLineData(
+ line=order_line,
+ quantity=21,
+ variant=order_line.variant,
+ warehouse_pk=allocation.stock.warehouse.pk,
+ )
+ stock = allocation.stock
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+ initially_allocated = 80
+ allocation.quantity_allocated = initially_allocated
+ allocation.save(update_fields=["quantity_allocated"])
+
+ with pytest.raises(InsufficientStock):
+ increase_allocations([order_line_info])
+
+ stock.refresh_from_db()
+ assert stock.quantity == 100
+ assert (
+ order_line.allocations.all().aggregate(Sum("quantity_allocated"))[
+ "quantity_allocated__sum"
+ ]
+ == initially_allocated
+ )
+
+
def test_decrease_stock(allocation):
stock = allocation.stock
stock.quantity = 100
@@ -299,7 +356,34 @@ def test_decrease_stock(allocation):
assert allocation.quantity_allocated == 30
-def test_decrease_stock_multiply_lines(allocations):
[email protected]("quantity, expected_allocated", ((50, 30), (200, 0)))
+def test_decrease_stock_without_stock_update(quantity, expected_allocated, allocation):
+ stock = allocation.stock
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+ allocation.quantity_allocated = 80
+ allocation.save(update_fields=["quantity_allocated"])
+ warehouse_pk = allocation.stock.warehouse.pk
+
+ decrease_stock(
+ [
+ OrderLineData(
+ line=allocation.order_line,
+ quantity=quantity,
+ variant=stock.product_variant,
+ warehouse_pk=warehouse_pk,
+ )
+ ],
+ update_stocks=False,
+ )
+
+ stock.refresh_from_db()
+ assert stock.quantity == 100
+ allocation.refresh_from_db()
+ assert allocation.quantity_allocated == expected_allocated
+
+
+def test_decrease_stock_multiple_lines(allocations):
allocation_1 = allocations[0]
allocation_2 = allocations[0]