Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Handle stock management when adding item to group
Anna Siwikdc03b43a46d7
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex 554386acca..50619b6d23 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -387,6 +387,5 @@ class AddDeliveryGroupItemForm(forms.Form):def save(self):variant = self.cleaned_data['variant']quantity = self.cleaned_data['quantity']- line = add_item_to_delivery_group(self.group, variant, quantity)+ add_item_to_delivery_group(self.group, variant, quantity)Order.objects.recalculate_order(self.group.order)- return linediff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex 72bd9f2e05..6ca3ebc44e 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -11,6 +11,7 @@ from django.utils.translation import pgettext_lazyfrom django_prices.templatetags.prices_i18n import grossfrom payments import PaymentStatusfrom prices import Price+from satchless.item import InsufficientStockfrom .forms import (AddDeliveryGroupItemForm, CancelGroupForm, CancelLinesForm,@@ -313,13 +314,25 @@ def add_item_delivery_group(request, order_pk, group_pk):form = AddDeliveryGroupItemForm(request.POST or None, group=group)status = 200if form.is_valid():- with transaction.atomic():- form.save()- msg = pgettext_lazy(- 'Dashboard message related to a delivery group',- 'Added %s to %s') % (form.cleaned_data['variant'], group)- messages.success(request, msg)- group.order.create_history_entry(comment=msg, user=request.user)+ msg_dict = {+ 'quantity': form.cleaned_data['quantity'],+ 'variant': form.cleaned_data['variant'],+ 'group': group+ }+ try:+ with transaction.atomic():+ form.save()+ msg = pgettext_lazy(+ 'Dashboard message related to a delivery group',+ 'Added %(quantity)d x %(variant)s to %(group)s') % msg_dict+ group.order.create_history_entry(comment=msg, user=request.user)+ messages.success(request, msg)+ except InsufficientStock:+ msg = pgettext_lazy(+ 'Dashboard message related to a delivery group',+ 'Insufficient stock: could not add %(quantity)d x '+ '%(variant)s to %(group)s') % msg_dict+ messages.warning(request, msg)return redirect('dashboard:order-details', order_pk=order_pk)elif form.errors:status = 400diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 1e1a2e591d..c826bea5aa 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -1,6 +1,7 @@import loggingfrom functools import wraps+from django.db.models import Ffrom django.dispatch import receiverfrom django.shortcuts import get_object_or_404, redirectfrom django.utils.translation import pgettext_lazy@@ -93,35 +94,43 @@ def add_items_to_delivery_group(delivery_group, partition, discounts=None):def add_item_to_delivery_group(group, variant, quantity):- try:- item = group.items.get(- product=variant.product, product_sku=variant.sku)- if not item.stock or item.stock.quantity_available < quantity:- raise InsufficientStock(variant)+ items = group.items.filter(+ product=variant.product, product_sku=variant.sku, stock__isnull=False,+ stock__quantity__gte=F('stock__quantity_allocated') + quantity)+ if items.exists():+ item = items.first()item.quantity += quantityitem.save()Stock.objects.allocate_stock(item.stock, quantity)- except (OrderedItem.DoesNotExist, InsufficientStock):+ else:price = variant.get_price_per_item()- item = create_item_in_delivery_group(group, variant, quantity, price)- return item---def create_item_in_delivery_group(group, variant, quantity, price):- stock = variant.select_stockrecord(quantity=quantity)- item = group.items.create(- product=variant.product,- product_name=variant.display_product(),- product_sku=variant.sku,- quantity=quantity,- unit_price_net=price.net,- unit_price_gross=price.gross,- stock=stock,- stock_location=stock.location.name if stock else None)- if stock:+ create_item_in_delivery_group(group, variant, quantity, price)+++def create_item_in_delivery_group(group, variant, total_quantity, price):+ while total_quantity > 0:+ stock = variant.select_stockrecord()+ if not stock:+ raise InsufficientStock(variant)+ quantity = (+ stock.quantity_available+ if total_quantity > stock.quantity_available+ else total_quantity+ )+ item = group.items.create(+ product=variant.product,+ product_name=variant.display_product(),+ product_sku=variant.sku,+ quantity=quantity,+ unit_price_net=price.net,+ unit_price_gross=price.gross,+ stock=stock,+ stock_location=stock.location.name)# allocate quantity to avoid oversellingStock.objects.allocate_stock(stock, quantity)- return item+ # refresh stock to get quantity_allocated in next loop+ stock.refresh_from_db()+ total_quantity -= quantitydef cancel_delivery_group(group, cancel_order=True):diff --git a/tests/test_order.py b/tests/test_order.pyindex e98faf3fee..d33e8572de 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -54,10 +54,10 @@ def test_add_item_to_delivery_group_adds_item_for_new_variant(variant = product_in_stock.variants.get()items_before = group.items.count()- item = add_item_to_delivery_group(group, variant, 1)+ add_item_to_delivery_group(group, variant, 1)+ item = group.items.last()assert group.items.count() == items_before + 1- assert group.items.last().pk == item.pkassert item.product_sku == variant.skuassert item.quantity == 1@@ -84,12 +84,12 @@ def test_add_item_to_delivery_group_edits_item_for_existing_variant(items_before = group.items.count()item_quantity_before = existing_item.quantity- item = add_item_to_delivery_group(group, variant, 1)+ add_item_to_delivery_group(group, variant, 1)+ existing_item.refresh_from_db()assert group.items.count() == items_before- assert item.pk == existing_item.pk- assert item.product_sku == variant.sku- assert item.quantity == item_quantity_before + 1+ assert existing_item.product_sku == variant.sku+ assert existing_item.quantity == item_quantity_before + 1def test_add_item_to_delivery_group_allocates_stock_for_existing_variant(