Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Restock products on order cancel
Anna Siwik5de8fa615335
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex 990e2b0944..bb2e94bc8d 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -11,11 +11,12 @@ from ...account.i18n import (from ...cart.forms import QuantityFieldfrom ...core.exceptions import InsufficientStockfrom ...discount.utils import decrease_voucher_usage+from ...order import OrderStatusfrom ...order.emails import send_note_confirmationfrom ...order.models import Fulfillment, FulfillmentLine, OrderLine, OrderNotefrom ...order.utils import (- add_variant_to_order, cancel_order, change_order_line_quantity,- fulfill_order_line, merge_duplicates_into_order_line, recalculate_order)+ add_variant_to_order, change_order_line_quantity, fulfill_order_line,+ merge_duplicates_into_order_line, recalculate_order, restock_order_lines)from ...product.models import Product, ProductVariant, Stockfrom ...product.utils import allocate_stock, deallocate_stockfrom ..forms import AjaxSelect2ChoiceField@@ -177,10 +178,16 @@ class CancelOrderForm(forms.Form):Deallocates corresponding stocks for each order line."""+ restock = forms.BooleanField(initial=True, required=False)def __init__(self, *args, **kwargs):self.order = kwargs.pop('order')super().__init__(*args, **kwargs)+ self.fields['restock'].label = npgettext_lazy(+ 'Cancel order form action',+ 'Restock %(quantity)d item',+ 'Restock %(quantity)d items',+ 'quantity') % {'quantity': self.order.get_total_quantity()}def clean(self):data = super().clean()@@ -192,7 +199,10 @@ class CancelOrderForm(forms.Form):return datadef cancel_order(self):- cancel_order(self.order)+ if self.cleaned_data.get('restock'):+ restock_order_lines(self.order)+ self.order.status = OrderStatus.CANCELED+ self.order.save(update_fields=['status'])class RemoveVoucherForm(forms.Form):@@ -325,6 +335,7 @@ class AddressForm(StorefrontAddressForm):class FulfillmentForm(forms.ModelForm):"""Create fulfillment group for a given order."""+class Meta:model = Fulfillmentfields = ['tracking_number']diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex 6caaa5877e..4eefed5e0c 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -7,7 +7,7 @@ from django.http import HttpResponsefrom django.shortcuts import get_object_or_404, redirectfrom django.template.context_processors import csrffrom django.template.response import TemplateResponse-from django.utils.translation import pgettext_lazy+from django.utils.translation import npgettext_lazy, pgettext_lazyfrom django_prices.templatetags import prices_i18nfrom payments import PaymentStatusfrom prices import Money, TaxedMoney@@ -287,18 +287,26 @@ def cancel_order(request, order_pk):order = get_object_or_404(Order, pk=order_pk)form = CancelOrderForm(request.POST or None, order=order)if form.is_valid():- msg = pgettext_lazy('Dashboard message', 'Cancelled order')+ msg = pgettext_lazy('Dashboard message', 'Order canceled')with transaction.atomic():form.cancel_order()+ if form.cleaned_data.get('restock'):+ restock_msg = npgettext_lazy(+ 'Dashboard message',+ 'Restocked %(quantity)d item',+ 'Restocked %(quantity)d items',+ 'quantity') % {'quantity': order.get_total_quantity()}+ order.history.create(content=restock_msg, user=request.user)order.history.create(content=msg, user=request.user)- messages.success(request, 'Order cancelled')+ messages.success(request, msg)return redirect('dashboard:order-details', order_pk=order.pk)# TODO: send status confirmation emailelif form.errors:status = 400- ctx = {'order': order}- return TemplateResponse(request, 'dashboard/order/modal/cancel_order.html',- ctx, status=status)+ ctx = {'form': form, 'order': order}+ return TemplateResponse(+ request, 'dashboard/order/modal/cancel_order.html', ctx,+ status=status)@staff_member_requireddiff --git a/saleor/order/models.py b/saleor/order/models.pyindex 2e1993e442..7f914e5b6d 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -143,6 +143,9 @@ class Order(models.Model):subtotal_iterator = (line.get_total() for line in self)return sum(subtotal_iterator, ZERO_TAXED_MONEY)+ def get_total_quantity(self):+ return sum([line.quantity for line in self])+def can_edit(self):return self.status == OrderStatus.UNFULFILLEDdiff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 3c06e0e816..c34706deea 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -9,7 +9,7 @@ from prices import Money, TaxedMoney, fixed_discountfrom . import GroupStatusfrom ..account.utils import store_user_addressfrom ..core.exceptions import InsufficientStock-from ..product.utils import allocate_stock, deallocate_stock+from ..product.utils import allocate_stock, deallocate_stock, increase_stockdef check_order_status(func):@@ -32,13 +32,6 @@ def check_order_status(func):return decorator-def cancel_order(order):- """Cancel order by deallocating stock for all order lines."""- for line in order:- if line.stock:- deallocate_stock(line.stock, line.quantity)--def recalculate_order(order):"""Recalculate and assign total price of order.@@ -156,3 +149,13 @@ def change_order_line_quantity(line, new_quantity):line.save()else:line.delete()+++def restock_order_lines(order):+ """Return ordered products to corresponding stocks."""+ for line in order:+ if line.stock:+ if line.quantity_fulfilled > 0:+ increase_stock(line.stock, line.quantity_fulfilled)+ if line.quantity_unfulfilled > 0:+ deallocate_stock(line.stock, line.quantity_unfulfilled)diff --git a/saleor/product/utils.py b/saleor/product/utils.pyindex d5c71d16d7..2ec59f1430 100644--- a/saleor/product/utils.py+++ b/saleor/product/utils.py@@ -393,6 +393,11 @@ def decrease_stock(stock, quantity):stock.save(update_fields=['quantity', 'quantity_allocated'])+def increase_stock(stock, quantity):+ stock.quantity = F('quantity') + quantity+ stock.save(update_fields=['quantity'])++def get_product_list_context(request, filter_set):""":param request: request objectdiff --git a/templates/dashboard/order/modal/cancel_order.html b/templates/dashboard/order/modal/cancel_order.htmlindex f9964d259e..d1bf96af63 100644--- a/templates/dashboard/order/modal/cancel_order.html+++ b/templates/dashboard/order/modal/cancel_order.html@@ -16,6 +16,7 @@{% blocktrans trimmed with order=order context "Modal cancel order text" %}Are you sure you want cancel order {{ order }}?{% endblocktrans %}+ {{ form.restock|materializecss }}</div>{% endblock %}diff --git a/tests/conftest.py b/tests/conftest.pyindex 4bf915b3ca..292e909abf 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -15,8 +15,9 @@ from saleor.account.models import Address, Userfrom saleor.cart import utilsfrom saleor.cart.models import Cartfrom saleor.checkout.core import Checkout+from saleor.dashboard.order.utils import fulfill_order_linefrom saleor.discount.models import Sale, Voucher-from saleor.order.models import Fulfillment, Order, OrderLine+from saleor.order.models import Order, OrderLinefrom saleor.order.utils import recalculate_orderfrom saleor.page.models import Pagefrom saleor.product.models import (@@ -457,6 +458,19 @@ def order_with_lines_and_stock(order, product_type, default_category):return order+def fulfilled_order(order_with_lines_and_stock):+ order = order_with_lines_and_stock+ fulfillment = order.fulfillments.create()+ line_1 = order.lines.first()+ line_2 = order.lines.last()+ fulfillment.lines.create(order_line=line_1, quantity=line_1.quantity)+ fulfill_order_line(line_1, line_1.quantity)+ fulfillment.lines.create(order_line=line_2, quantity=line_2.quantity)+ fulfill_order_line(line_2, line_2.quantity)+ return order++@pytest.fixture()def order_with_variant_from_different_stocks(order_with_lines_and_stock):line = OrderLine.objects.get(product_sku='SKU_A')diff --git a/tests/dashboard/test_permissions.py b/tests/dashboard/test_permissions.pyindex 6e4bde6fa2..dde916bf4a 100644--- a/tests/dashboard/test_permissions.py+++ b/tests/dashboard/test_permissions.py@@ -640,16 +640,16 @@ def test_staff_group_member_can_view_order_add_note(def test_staff_group_member_can_view_cancel_order(staff_client, staff_user, staff_group, permission_edit_order,order):- assert not staff_user.has_perm("order.edit_order")- response = staff_client.get(reverse('dashboard:order-add-note',- args=[order.pk]))+ assert not staff_user.has_perm('order.edit_order')+ response = staff_client.get(+ reverse('dashboard:order-cancel', args=[order.pk]))assert response.status_code == 302staff_group.permissions.add(permission_edit_order)staff_user.groups.add(staff_group)staff_user = User.objects.get(pk=staff_user.pk)- assert staff_user.has_perm("order.edit_order")- response = staff_client.get(reverse('dashboard:order-add-note',- args=[order.pk]))+ assert staff_user.has_perm('order.edit_order')+ response = staff_client.get(+ reverse('dashboard:order-cancel', args=[order.pk]))assert response.status_code == 200diff --git a/tests/test_order.py b/tests/test_order.pyindex 2d4d2bcba6..f473245b37 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -7,7 +7,8 @@ from tests.utils import get_redirect_locationfrom saleor.order import modelsfrom saleor.order.emails import collect_data_for_emailfrom saleor.order.forms import OrderNoteForm-from saleor.order.utils import recalculate_order+from saleor.order.utils import (+ add_variant_to_order, recalculate_order, restock_order_lines)def test_total_setter():@@ -140,3 +141,44 @@ def test_collect_data_for_email(order):order_url = reverse('order:details', kwargs={'token': order.token})assert order_url in email_data['url']assert email_data['email'] == order.user_email+++def test_restock_order_lines(order_with_lines_and_stock):+ order = order_with_lines_and_stock+ line_1 = order.lines.first()+ line_2 = order.lines.last()+ stock_1_quantity_allocated_before = line_1.stock.quantity_allocated+ stock_2_quantity_allocated_before = line_2.stock.quantity_allocated+ stock_1_quantity_before = line_1.stock.quantity+ stock_2_quantity_before = line_2.stock.quantity++ restock_order_lines(order)++ line_1.stock.refresh_from_db()+ line_2.stock.refresh_from_db()+ assert line_1.stock.quantity_allocated == (+ stock_1_quantity_allocated_before - line_1.quantity)+ assert line_2.stock.quantity_allocated == (+ stock_2_quantity_allocated_before - line_2.quantity)+ assert line_1.stock.quantity == stock_1_quantity_before+ assert line_2.stock.quantity == stock_2_quantity_before+++def test_restock_fulfilled_order_lines(fulfilled_order):+ line_1 = fulfilled_order.lines.first()+ line_2 = fulfilled_order.lines.last()+ stock_1_quantity_allocated_before = line_1.stock.quantity_allocated+ stock_2_quantity_allocated_before = line_2.stock.quantity_allocated+ stock_1_quantity_before = line_1.stock.quantity+ stock_2_quantity_before = line_2.stock.quantity++ restock_order_lines(fulfilled_order)++ line_1.stock.refresh_from_db()+ line_2.stock.refresh_from_db()+ assert line_1.stock.quantity_allocated == (+ stock_1_quantity_allocated_before)+ assert line_2.stock.quantity_allocated == (+ stock_2_quantity_allocated_before)+ assert line_1.stock.quantity == stock_1_quantity_before + line_1.quantity+ assert line_2.stock.quantity == stock_2_quantity_before + line_2.quantitydiff --git a/tests/test_product.py b/tests/test_product.pyindex d6fd872db9..ee1eb3247f 100644--- a/tests/test_product.py+++ b/tests/test_product.py@@ -16,7 +16,7 @@ from saleor.product.utils import (allocate_stock, deallocate_stock, decrease_stock,get_attributes_display_map, get_availability,get_product_availability_status, get_variant_availability_status,- get_variant_picker_data)+ get_variant_picker_data, increase_stock)@pytest.fixture()@@ -42,6 +42,17 @@ def test_allocate_stock(product_in_stock):assert stock.quantity_allocated == 1+def test_deallocate_stock(product_in_stock):+ stock = product_in_stock.variants.first().stock.first()+ stock.quantity = 100+ stock.quantity_allocated = 80+ stock.save()+ deallocate_stock(stock, 50)+ stock.refresh_from_db()+ assert stock.quantity == 100+ assert stock.quantity_allocated == 30++def test_decrease_stock(product_in_stock):stock = product_in_stock.variants.first().stock.first()stock.quantity = 100@@ -53,15 +64,15 @@ def test_decrease_stock(product_in_stock):assert stock.quantity_allocated == 30-def test_deallocate_stock(product_in_stock):+def test_increase_stock(product_in_stock):stock = product_in_stock.variants.first().stock.first()stock.quantity = 100stock.quantity_allocated = 80stock.save()- deallocate_stock(stock, 50)+ increase_stock(stock, 50)stock.refresh_from_db()- assert stock.quantity == 100- assert stock.quantity_allocated == 30+ assert stock.quantity == 150+ assert stock.quantity_allocated == 80def test_product_page_redirects_to_correct_slug(client, product_in_stock):