Skip to content

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

Restock products on order cancel

Anna Siwik5de8fa615335
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 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 QuantityField
from ...core.exceptions import InsufficientStock
from ...discount.utils import decrease_voucher_usage
+from ...order import OrderStatus
from ...order.emails import send_note_confirmation
from ...order.models import Fulfillment, FulfillmentLine, OrderLine, OrderNote
from ...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, Stock
from ...product.utils import allocate_stock, deallocate_stock
from ..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 data
def 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 = Fulfillment
fields = ['tracking_number']
diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.py
index 6caaa5877e..4eefed5e0c 100644
--- a/saleor/dashboard/order/views.py
+++ b/saleor/dashboard/order/views.py
@@ -7,7 +7,7 @@ from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect
from django.template.context_processors import csrf
from django.template.response import TemplateResponse
-from django.utils.translation import pgettext_lazy
+from django.utils.translation import npgettext_lazy, pgettext_lazy
from django_prices.templatetags import prices_i18n
from payments import PaymentStatus
from 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 email
elif 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_required
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 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.UNFULFILLED
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 3c06e0e816..c34706deea 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -9,7 +9,7 @@ from prices import Money, TaxedMoney, fixed_discount
from . import GroupStatus
from ..account.utils import store_user_address
from ..core.exceptions import InsufficientStock
-from ..product.utils import allocate_stock, deallocate_stock
+from ..product.utils import allocate_stock, deallocate_stock, increase_stock
def 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.py
index 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 object
diff --git a/templates/dashboard/order/modal/cancel_order.html b/templates/dashboard/order/modal/cancel_order.html
index 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.py
index 4bf915b3ca..292e909abf 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -15,8 +15,9 @@ from saleor.account.models import Address, User
from saleor.cart import utils
from saleor.cart.models import Cart
from saleor.checkout.core import Checkout
+from saleor.dashboard.order.utils import fulfill_order_line
from saleor.discount.models import Sale, Voucher
-from saleor.order.models import Fulfillment, Order, OrderLine
+from saleor.order.models import Order, OrderLine
from saleor.order.utils import recalculate_order
from saleor.page.models import Page
from 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.py
index 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 == 302
staff_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 == 200
diff --git a/tests/test_order.py b/tests/test_order.py
index 2d4d2bcba6..f473245b37 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -7,7 +7,8 @@ from tests.utils import get_redirect_location
from saleor.order import models
from saleor.order.emails import collect_data_for_email
from 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.quantity
diff --git a/tests/test_product.py b/tests/test_product.py
index 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 = 100
stock.quantity_allocated = 80
stock.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 == 80
def test_product_page_redirects_to_correct_slug(client, product_in_stock):