Skip to content

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

Stock quantity_allocated on field level (#9172)

Tomasz Szymański03721d89ed9e
diff --git a/saleor/settings.py b/saleor/settings.py
index b49978e827..c48ef78567 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -534,6 +534,10 @@ CELERY_BEAT_SCHEDULE = {
"task": "saleor.giftcard.tasks.deactivate_expired_cards_task",
"schedule": crontab(hour=0, minute=0),
},
+ "update-stocks-quantity-allocated": {
+ "task": "saleor.warehouse.tasks.update_stocks_quantity_allocated_task",
+ "schedule": crontab(hour=0, minute=0),
+ },
}
EVENT_PAYLOAD_DELETE_PERIOD = timedelta(
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 2a570cf8a8..a982a503c2 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -3195,6 +3195,12 @@ def order_line_with_allocation_in_many_stocks(
]
)
+ stocks_to_update = list(stocks)
+ stocks_to_update[0].quantity_allocated = 2
+ stocks_to_update[1].quantity_allocated = 1
+
+ Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])
+
return order_line
@@ -3240,6 +3246,9 @@ def order_line_with_one_allocation(
Allocation.objects.create(
order_line=order_line, stock=stocks[0], quantity_allocated=1
)
+ stock = stocks[0]
+ stock.quantity_allocated = 1
+ stock.save(update_fields=["quantity_allocated"])
return order_line
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index 17f2d7a231..c537d0887f 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -3,6 +3,7 @@ from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, ca
from django.db import transaction
from django.db.models import F, Sum
+from django.db.models.expressions import Exists, OuterRef
from django.db.models.functions import Coalesce
from ..checkout.models import CheckoutLine
@@ -14,6 +15,7 @@ from ..core.exceptions import (
)
from ..core.tracing import traced_atomic_transaction
from ..order.fetch import OrderLineInfo
+from ..order.models import OrderLine
from ..plugins.manager import PluginsManager
from ..product.models import ProductVariant, ProductVariantChannelListing
from .models import (
@@ -26,7 +28,7 @@ from .models import (
)
if TYPE_CHECKING:
- from ..order.models import Order, OrderLine
+ from ..order.models import Order
StockData = namedtuple("StockData", ["pk", "quantity"])
@@ -70,7 +72,7 @@ def allocate_stocks(
.order_by("pk")
.values("id", "product_variant", "pk", "quantity")
)
- stocks_id = [stock.pop("id") for stock in stocks]
+ stocks_id = (stock.pop("id") for stock in stocks)
quantity_reservation_for_stocks: Dict = defaultdict(int)
@@ -128,7 +130,14 @@ def allocate_stocks(
raise InsufficientStock(insufficient_stock)
if allocations:
- Allocation.objects.bulk_create(allocations)
+ stocks_to_update = []
+ for alloc in Allocation.objects.bulk_create(allocations):
+ stock = alloc.stock
+ stock.quantity_allocated = (
+ F("quantity_allocated") + alloc.quantity_allocated
+ )
+ stocks_to_update.append(stock)
+ Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])
for allocation in allocations:
allocated_stock = (
@@ -212,6 +221,7 @@ def deallocate_stock(
line_to_allocations[allocation.order_line_id].append(allocation)
allocations_to_update = []
+ stocks_to_update = []
not_dellocated_lines = []
for line_info in order_lines_data:
order_line = line_info.line
@@ -226,6 +236,11 @@ def deallocate_stock(
allocation.quantity_allocated = (
allocation.quantity_allocated - quantity_to_deallocate
)
+ stock = allocation.stock
+ stock.quantity_allocated = (
+ F("quantity_allocated") - quantity_to_deallocate
+ )
+ stocks_to_update.append(stock)
quantity_dealocated += quantity_to_deallocate
allocations_to_update.append(allocation)
if quantity_dealocated == quantity:
@@ -255,13 +270,15 @@ def deallocate_stock(
)
)
+ Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])
+
if not_dellocated_lines:
raise AllocationError(not_dellocated_lines)
@traced_atomic_transaction()
def increase_stock(
- order_line: "OrderLine",
+ order_line: OrderLine,
warehouse: Warehouse,
quantity: int,
allocate: bool = False,
@@ -296,6 +313,8 @@ def increase_stock(
Allocation.objects.create(
order_line=order_line, stock=stock, quantity_allocated=quantity
)
+ stock.quantity_allocated = F("quantity_allocated") + quantity
+ stock.save(update_fields=["quantity_allocated"])
@traced_atomic_transaction()
@@ -321,7 +340,13 @@ def increase_allocations(
# line_info.quantity resembles amount to add, sum it with already allocated.
line_info.quantity += allocated
+ stocks_to_update = []
+ for alloc in allocations:
+ stock = alloc.stock
+ stock.quantity_allocated = F("quantity_allocated") - alloc.quantity_allocated
+ stocks_to_update.append(stock)
Allocation.objects.filter(pk__in=allocation_pks_to_delete).delete()
+ Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])
allocate_stocks(
lines_info,
@@ -389,12 +414,12 @@ def decrease_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"
- ]
if update_stocks:
+ 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,
@@ -474,9 +499,16 @@ def get_order_lines_with_track_inventory(
@traced_atomic_transaction()
def deallocate_stock_for_order(order: "Order", manager: PluginsManager):
"""Remove all allocations for given order."""
+ lines = OrderLine.objects.filter(order_id=order.id)
allocations = Allocation.objects.filter(
- order_line__order=order, quantity_allocated__gt=0
- )
+ Exists(lines.filter(id=OuterRef("order_line_id"))), quantity_allocated__gt=0
+ ).select_related("stock")
+
+ stocks_to_update = []
+ for alloc in allocations:
+ stock = alloc.stock
+ stock.quantity_allocated = F("quantity_allocated") - alloc.quantity_allocated
+ stocks_to_update.append(stock)
for allocation in allocations.annotate_stock_available_quantity():
if allocation.stock_available_quantity <= 0:
@@ -485,6 +517,7 @@ def deallocate_stock_for_order(order: "Order", manager: PluginsManager):
)
allocations.update(quantity_allocated=0)
+ Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])
@traced_atomic_transaction()
diff --git a/saleor/warehouse/migrations/0020_stock_quantity_allocated.py b/saleor/warehouse/migrations/0020_stock_quantity_allocated.py
new file mode 100644
index 0000000000..f962e9845b
--- /dev/null
+++ b/saleor/warehouse/migrations/0020_stock_quantity_allocated.py
@@ -0,0 +1,39 @@
+# Generated by Django 3.2.6 on 2022-02-16 09:11
+
+from django.db import migrations, models
+from django.db.models import OuterRef, Subquery, Sum
+from django.db.models.functions import Coalesce
+
+
+def assign_quantity_allocated_to_stocks(apps, schema_editor):
+ Stock = apps.get_model("warehouse", "Stock")
+
+ Stock.objects.update(
+ quantity_allocated=Subquery(
+ Stock.objects.filter(id=OuterRef("id"))
+ .annotate(
+ allocations_allocated=Coalesce(
+ Sum("allocations__quantity_allocated"), 0
+ )
+ )
+ .values("allocations_allocated")[:1]
+ )
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("warehouse", "0019_auto_20211019_1438"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="stock",
+ name="quantity_allocated",
+ field=models.IntegerField(default=0),
+ ),
+ migrations.RunPython(
+ assign_quantity_allocated_to_stocks, migrations.RunPython.noop
+ ),
+ ]
diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.py
index 703fc3a7da..fb0ace74b6 100644
--- a/saleor/warehouse/models.py
+++ b/saleor/warehouse/models.py
@@ -245,6 +245,7 @@ class Stock(models.Model):
ProductVariant, null=False, on_delete=models.CASCADE, related_name="stocks"
)
quantity = models.IntegerField(default=0)
+ quantity_allocated = models.IntegerField(default=0)
objects = models.Manager.from_queryset(StockQuerySet)()
diff --git a/saleor/warehouse/tasks.py b/saleor/warehouse/tasks.py
index bd75ef3a20..808c04f096 100644
--- a/saleor/warehouse/tasks.py
+++ b/saleor/warehouse/tasks.py
@@ -1,8 +1,10 @@
from celery.utils.log import get_task_logger
+from django.db.models import F, Sum
+from django.db.models.functions import Coalesce
from django.utils import timezone
from ..celeryconf import app
-from .models import Allocation, PreorderReservation, Reservation
+from .models import Allocation, PreorderReservation, Reservation, Stock
task_logger = get_task_logger(__name__)
@@ -29,3 +31,25 @@ def delete_expired_reservations_task():
stock_reservations,
preorder_reservations,
)
+
+
+def update_stocks_quantity_allocated_task():
+ stocks_to_update = []
+ for mismatched_stock in Stock.objects.annotate(
+ allocations_allocated=Coalesce(Sum("allocations__quantity_allocated"), 0)
+ ).exclude(quantity_allocated=F("allocations_allocated")):
+ task_logger.info(
+ "Mismatch updating quantity_allocated: stock %d had "
+ "%d allocated, but should have %d.",
+ mismatched_stock.pk,
+ mismatched_stock.quantity_allocated,
+ mismatched_stock.allocations_allocated,
+ )
+ mismatched_stock.quantity_allocated = mismatched_stock.allocations_allocated
+ stocks_to_update.append(mismatched_stock)
+
+ Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])
+ task_logger.info(
+ "Finished updating quantity_allocated on stocks, %d were corrected.",
+ len(stocks_to_update),
+ )
diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.py
index 735a60707e..09cf9410f0 100644
--- a/saleor/warehouse/tests/test_stock_management.py
+++ b/saleor/warehouse/tests/test_stock_management.py
@@ -38,7 +38,7 @@ def test_allocate_stocks(order_line, stock, channel_USD):
assert stock.quantity == 100
assert stock.quantity == 100
allocation = Allocation.objects.get(order_line=order_line, stock=stock)
- assert allocation.quantity_allocated == 50
+ assert allocation.quantity_allocated == stock.quantity_allocated == 50
def test_allocate_stocks_multiple_lines(order_line, order, product, stock, channel_USD):
@@ -75,11 +75,11 @@ def test_allocate_stocks_multiple_lines(order_line, order, product, stock, chann
stock.refresh_from_db()
assert stock.quantity == 100
allocation = Allocation.objects.get(order_line=order_line, stock=stock)
- assert allocation.quantity_allocated == quantity_1
+ assert allocation.quantity_allocated == stock.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
+ assert allocation.quantity_allocated == stock_2.quantity_allocated == quantity_2
def test_allocate_stock_many_stocks(order_line, variant_with_many_stocks, channel_USD):
@@ -92,8 +92,8 @@ def test_allocate_stock_many_stocks(order_line, variant_with_many_stocks, channe
)
allocations = Allocation.objects.filter(order_line=order_line, stock__in=stocks)
- assert allocations[0].quantity_allocated == 4
- assert allocations[1].quantity_allocated == 1
+ assert allocations[0].quantity_allocated == stocks[0].quantity_allocated == 4
+ assert allocations[1].quantity_allocated == stocks[1].quantity_allocated == 1
def test_allocate_stock_with_reservations(
@@ -253,7 +253,8 @@ def test_allocate_stock_insufficient_stocks_for_multiple_lines(
def test_deallocate_stock(allocation):
stock = allocation.stock
stock.quantity = 100
- stock.save(update_fields=["quantity"])
+ stock.quantity_allocated = 80
+ stock.save(update_fields=["quantity", "quantity_allocated"])
allocation.quantity_allocated = 80
allocation.save(update_fields=["quantity_allocated"])
@@ -268,6 +269,7 @@ def test_deallocate_stock(allocation):
stock.refresh_from_db()
assert stock.quantity == 100
+ assert stock.quantity_allocated == 0
allocation.refresh_from_db()
assert allocation.quantity_allocated == 0
@@ -297,7 +299,8 @@ def test_deallocate_stock_when_quantity_less_than_zero(allocation):
def test_deallocate_stock_partially(allocation):
stock = allocation.stock
stock.quantity = 100
- stock.save(update_fields=["quantity"])
+ stock.quantity_allocated = 80
+ stock.save(update_fields=["quantity", "quantity_allocated"])
allocation.quantity_allocated = 80
allocation.save(update_fields=["quantity_allocated"])
@@ -312,6 +315,7 @@ def test_deallocate_stock_partially(allocation):
stock.refresh_from_db()
assert stock.quantity == 100
+ assert stock.quantity_allocated == 30
allocation.refresh_from_db()
assert allocation.quantity_allocated == 30
@@ -349,7 +353,8 @@ def test_deallocate_stock_many_allocations_partially(
def test_increase_stock_without_allocate(allocation):
stock = allocation.stock
stock.quantity = 100
- stock.save(update_fields=["quantity"])
+ stock.quantity_allocated = 80
+ stock.save(update_fields=["quantity", "quantity_allocated"])
allocation.quantity_allocated = 80
allocation.save(update_fields=["quantity_allocated"])
@@ -357,6 +362,7 @@ def test_increase_stock_without_allocate(allocation):
stock.refresh_from_db()
assert stock.quantity == 150
+ assert stock.quantity_allocated == 80
allocation.refresh_from_db()
assert allocation.quantity_allocated == 80
@@ -364,7 +370,8 @@ def test_increase_stock_without_allocate(allocation):
def test_increase_stock_with_allocate(allocation):
stock = allocation.stock
stock.quantity = 100
- stock.save(update_fields=["quantity"])
+ stock.quantity_allocated = 80
+ stock.save(update_fields=["quantity", "quantity_allocated"])
allocation.quantity_allocated = 80
allocation.save(update_fields=["quantity_allocated"])
@@ -372,6 +379,7 @@ def test_increase_stock_with_allocate(allocation):
stock.refresh_from_db()
assert stock.quantity == 150
+ assert stock.quantity_allocated == 130
allocation.refresh_from_db()
assert allocation.quantity_allocated == 130
@@ -385,6 +393,7 @@ def test_increase_stock_with_new_allocation(order_line, stock):
stock.refresh_from_db()
assert stock.quantity == 150
+ assert stock.quantity_allocated == 50
allocation = Allocation.objects.get(order_line=order_line, stock=stock)
assert allocation.quantity_allocated == 50
@@ -400,7 +409,8 @@ def test_increase_allocations(quantity, allocation):
)
stock = allocation.stock
stock.quantity = 100
- stock.save(update_fields=["quantity"])
+ stock.quantity_allocated = 80
+ stock.save(update_fields=["quantity", "quantity_allocated"])
initially_allocated = 80
allocation.quantity_allocated = initially_allocated
allocation.save(update_fields=["quantity_allocated"])
@@ -415,6 +425,7 @@ def test_increase_allocations(quantity, allocation):
order_line.allocations.all().aggregate(Sum("quantity_allocated"))[
"quantity_allocated__sum"
]
+ == stock.quantity_allocated
== initially_allocated + quantity
)
@@ -427,10 +438,11 @@ def test_increase_allocation_insufficient_stock(allocation):
variant=order_line.variant,
warehouse_pk=allocation.stock.warehouse.pk,
)
+ initially_allocated = 80
stock = allocation.stock
stock.quantity = 100
- stock.save(update_fields=["quantity"])
- initially_allocated = 80
+ stock.quantity_allocated = initially_allocated
+ stock.save(update_fields=["quantity", "quantity_allocated"])
allocation.quantity_allocated = initially_allocated
allocation.save(update_fields=["quantity_allocated"])
@@ -443,6 +455,7 @@ def test_increase_allocation_insufficient_stock(allocation):
stock.refresh_from_db()
assert stock.quantity == 100
+ assert stock.quantity_allocated == initially_allocated
assert (
order_line.allocations.all().aggregate(Sum("quantity_allocated"))[
"quantity_allocated__sum"
@@ -470,7 +483,8 @@ def test_increase_stock_with_back_in_stock_webhook_triggered_without_allocation(
def test_decrease_stock(allocation):
stock = allocation.stock
stock.quantity = 100
- stock.save(update_fields=["quantity"])
+ stock.quantity_allocated = 80
+ stock.save(update_fields=["quantity", "quantity_allocated"])
allocation.quantity_allocated = 80
allocation.save(update_fields=["quantity_allocated"])
warehouse_pk = allocation.stock.warehouse.pk
@@ -489,6 +503,7 @@ def test_decrease_stock(allocation):
stock.refresh_from_db()
assert stock.quantity == 50
+ assert stock.quantity_allocated == 30
allocation.refresh_from_db()
assert allocation.quantity_allocated == 30
@@ -497,7 +512,8 @@ def test_decrease_stock(allocation):
def test_decrease_stock_without_stock_update(quantity, expected_allocated, allocation):
stock = allocation.stock
stock.quantity = 100
- stock.save(update_fields=["quantity"])
+ stock.quantity_allocated = 80
+ stock.save(update_fields=["quantity", "quantity_allocated"])
allocation.quantity_allocated = 80
allocation.save(update_fields=["quantity_allocated"])
warehouse_pk = allocation.stock.warehouse.pk
@@ -517,6 +533,7 @@ def test_decrease_stock_without_stock_update(quantity, expected_allocated, alloc
stock.refresh_from_db()
assert stock.quantity == 100
+ assert stock.quantity_allocated == expected_allocated
allocation.refresh_from_db()
assert allocation.quantity_allocated == expected_allocated
@@ -730,7 +747,9 @@ def test_decrease_stock_more_then_allocated(
allocations = order_line.allocations.all()
assert allocations[0].quantity_allocated == 0
+ assert allocations[0].stock.quantity_allocated == 0
assert allocations[1].quantity_allocated == 0
+ assert allocations[1].stock.quantity_allocated == 0
assert allocations[0].stock.quantity == 0
assert allocations[1].stock.quantity == 3
@@ -738,7 +757,8 @@ def test_decrease_stock_more_then_allocated(
def test_decrease_stock_insufficient_stock(allocation):
stock = allocation.stock
stock.quantity = 20
- stock.save(update_fields=["quantity"])
+ stock.quantity_allocated = 80
+ stock.save(update_fields=["quantity", "quantity_allocated"])
allocation.quantity_allocated = 80
allocation.save(update_fields=["quantity_allocated"])
warehouse_pk = allocation.stock.warehouse.pk
@@ -758,21 +778,28 @@ def test_decrease_stock_insufficient_stock(allocation):
stock.refresh_from_db()
assert stock.quantity == 20
+ assert stock.quantity_allocated == 80
allocation.refresh_from_db()
assert allocation.quantity_allocated == 80
-def test_deallocate_stock_for_order(
- order_line_with_allocation_in_many_stocks,
-):
+def test_deallocate_stock_for_order(order_line_with_allocation_in_many_stocks):
order_line = order_line_with_allocation_in_many_stocks
order = order_line.order
deallocate_stock_for_order(order, manager=get_plugins_manager())
allocations = order_line.allocations.all()
- assert allocations[0].quantity_allocated == 0
- assert allocations[1].quantity_allocated == 0
+ assert (
+ allocations[0].quantity_allocated
+ == allocations[0].stock.quantity_allocated
+ == 0
+ )
+ assert (
+ allocations[1].quantity_allocated
+ == allocations[1].stock.quantity_allocated
+ == 0
+ )
@mock.patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
diff --git a/saleor/warehouse/tests/test_tasks.py b/saleor/warehouse/tests/test_tasks.py
index b59177df89..90a62728b0 100644
--- a/saleor/warehouse/tests/test_tasks.py
+++ b/saleor/warehouse/tests/test_tasks.py
@@ -1,9 +1,13 @@
from datetime import timedelta
+import pytest
from django.utils import timezone
from ..models import PreorderReservation, Reservation
-from ..tasks import delete_expired_reservations_task
+from ..tasks import (
+ delete_expired_reservations_task,
+ update_stocks_quantity_allocated_task,
+)
def test_delete_expired_reservations_task_deletes_expired_stock_reservations(
@@ -42,3 +46,42 @@ def test_delete_expired_reservations_task_skips_active_preorder_reservations(
)
delete_expired_reservations_task()
assert PreorderReservation.objects.count() == reservations_count
+
+
+ "allocation_allocated, stock_allocated, expected",
+ (
+ (10, 9, 10),
+ (9, 10, 9),
+ (0, 9, 0),
+ (9, 0, 9),
+ ),
+)
+def test_update_stocks_quantity_allocated_task(
+ allocation_allocated, stock_allocated, expected, allocation
+):
+ allocation.quantity_allocated = allocation_allocated
+ allocation.save(update_fields=["quantity_allocated"])
+ stock = allocation.stock
+ stock.quantity_allocated = stock_allocated
+ stock.save(update_fields=["quantity_allocated"])
+
+ update_stocks_quantity_allocated_task()
+
+ allocation.refresh_from_db()
+ stock.refresh_from_db()
+ assert allocation.quantity_allocated == allocation_allocated
+ assert stock.quantity_allocated == allocation_allocated
+
+
+def test_update_stocks_quantity_allocated_task_stock_without_allocations(stock):
+ stock_allocated = 9
+
+ stock.allocations.all().delete()
+ stock.quantity_allocated = stock_allocated
+ stock.save(update_fields=["quantity_allocated"])
+
+ update_stocks_quantity_allocated_task()
+
+ stock.refresh_from_db()
+ assert stock.quantity_allocated == 0