Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Stock quantity_allocated on field level (#9172)
Tomasz Szymański03721d89ed9e
diff --git a/saleor/settings.py b/saleor/settings.pyindex 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.pyindex 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_linediff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex 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, cafrom django.db import transactionfrom django.db.models import F, Sum+from django.db.models.expressions import Exists, OuterReffrom django.db.models.functions import Coalescefrom ..checkout.models import CheckoutLine@@ -14,6 +15,7 @@ from ..core.exceptions import ()from ..core.tracing import traced_atomic_transactionfrom ..order.fetch import OrderLineInfo+from ..order.models import OrderLinefrom ..plugins.manager import PluginsManagerfrom ..product.models import ProductVariant, ProductVariantChannelListingfrom .models import (@@ -26,7 +28,7 @@ from .models import ()if TYPE_CHECKING:- from ..order.models import Order, OrderLine+ from ..order.models import OrderStockData = 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_deallocateallocations_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.pynew file mode 100644index 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.pyindex 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.pyindex 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 Coalescefrom django.utils import timezonefrom ..celeryconf import app-from .models import Allocation, PreorderReservation, Reservation+from .models import Allocation, PreorderReservation, Reservation, Stocktask_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.pyindex 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 == 100assert stock.quantity == 100allocation = Allocation.objects.get(order_line=order_line, stock=stock)- assert allocation.quantity_allocated == 50+ assert allocation.quantity_allocated == stock.quantity_allocated == 50def 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, channstock.refresh_from_db()assert stock.quantity == 100allocation = Allocation.objects.get(order_line=order_line, stock=stock)- assert allocation.quantity_allocated == quantity_1+ assert allocation.quantity_allocated == stock.quantity_allocated == quantity_1stock_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_2def 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 == 1def 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.stockstock.quantity = 100- stock.save(update_fields=["quantity"])+ stock.quantity_allocated = 80+ stock.save(update_fields=["quantity", "quantity_allocated"])allocation.quantity_allocated = 80allocation.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 == 0allocation.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.stockstock.quantity = 100- stock.save(update_fields=["quantity"])+ stock.quantity_allocated = 80+ stock.save(update_fields=["quantity", "quantity_allocated"])allocation.quantity_allocated = 80allocation.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 == 30allocation.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.stockstock.quantity = 100- stock.save(update_fields=["quantity"])+ stock.quantity_allocated = 80+ stock.save(update_fields=["quantity", "quantity_allocated"])allocation.quantity_allocated = 80allocation.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 == 80allocation.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.stockstock.quantity = 100- stock.save(update_fields=["quantity"])+ stock.quantity_allocated = 80+ stock.save(update_fields=["quantity", "quantity_allocated"])allocation.quantity_allocated = 80allocation.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 == 130allocation.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 == 50allocation = 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.stockstock.quantity = 100- stock.save(update_fields=["quantity"])+ stock.quantity_allocated = 80+ stock.save(update_fields=["quantity", "quantity_allocated"])initially_allocated = 80allocation.quantity_allocated = initially_allocatedallocation.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 = 80stock = allocation.stockstock.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_allocatedallocation.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_allocatedassert (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.stockstock.quantity = 100- stock.save(update_fields=["quantity"])+ stock.quantity_allocated = 80+ stock.save(update_fields=["quantity", "quantity_allocated"])allocation.quantity_allocated = 80allocation.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 == 30allocation.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.stockstock.quantity = 100- stock.save(update_fields=["quantity"])+ stock.quantity_allocated = 80+ stock.save(update_fields=["quantity", "quantity_allocated"])allocation.quantity_allocated = 80allocation.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, allocstock.refresh_from_db()assert stock.quantity == 100+ assert stock.quantity_allocated == expected_allocatedallocation.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 == 0assert allocations[1].quantity_allocated == 0+ assert allocations[1].stock.quantity_allocated == 0assert allocations[0].stock.quantity == 0assert 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.stockstock.quantity = 20- stock.save(update_fields=["quantity"])+ stock.quantity_allocated = 80+ stock.save(update_fields=["quantity", "quantity_allocated"])allocation.quantity_allocated = 80allocation.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 == 80allocation.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_stocksorder = order_line.orderdeallocate_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.pyindex 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 pytestfrom django.utils import timezonefrom ..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