Skip to content

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

Fix dashboard order line change view

Marco Badan07bbed39686a
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 38beb2e86f..60878ea148 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -168,23 +168,25 @@ class CancelItemsForm(forms.Form):
class ChangeQuantityForm(forms.ModelForm):
+ quantity = QuantityField(
+ label=pgettext_lazy('Change quantity form label', 'Quantity'),
+ validators=[MinValueValidator(1)])
+
class Meta:
model = OrderedItem
fields = ['quantity']
def __init__(self, *args, **kwargs):
+ self.variant = kwargs.pop('variant')
super(ChangeQuantityForm, self).__init__(*args, **kwargs)
self.initial_quantity = self.instance.quantity
- self.fields['quantity'].widget.attrs.update({'min': 1})
self.fields['quantity'].initial = self.initial_quantity
def clean_quantity(self):
quantity = self.cleaned_data['quantity']
delta = quantity - self.initial_quantity
- variant = get_object_or_404(
- ProductVariant, sku=self.instance.product_sku)
try:
- variant.check_quantity(delta)
+ self.variant.check_quantity(delta)
except InsufficientStock as e:
raise forms.ValidationError(
npgettext_lazy(
diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.py
index ee0c902ec3..7c5c2ef048 100644
--- a/saleor/dashboard/order/views.py
+++ b/saleor/dashboard/order/views.py
@@ -13,6 +13,7 @@ from prices import Price
from ...core.utils import get_paginator_items
from ...order import OrderStatus
from ...order.models import Order, OrderedItem, OrderNote
+from ...product.models import ProductVariant
from ...userprofile.i18n import AddressForm
from ..order.forms import OrderFilterForm
from ..views import staff_member_required
@@ -160,7 +161,10 @@ def orderline_change_quantity(request, order_pk, line_pk):
order = get_object_or_404(Order, pk=order_pk)
item = get_object_or_404(OrderedItem.objects.filter(
delivery_group__order=order), pk=line_pk)
- form = ChangeQuantityForm(request.POST or None, instance=item)
+ variant = get_object_or_404(
+ ProductVariant, sku=item.product_sku)
+ form = ChangeQuantityForm(
+ request.POST or None, instance=item, variant=variant)
status = 200
old_quantity = item.quantity
if form.is_valid():
@@ -174,6 +178,7 @@ def orderline_change_quantity(request, order_pk, line_pk):
'new_quantity': item.quantity}
order.create_history_entry(comment=msg, user=request.user)
messages.success(request, msg)
+ return redirect('dashboard:order-details', order_pk=order.pk)
elif form.errors:
status = 400
ctx = {'order': order, 'object': item, 'form': form}
diff --git a/tests/conftest.py b/tests/conftest.py
index a0a337d52a..2d7957598c 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -218,7 +218,7 @@ def order_with_items_and_stock(order, product_class):
product = Product.objects.create(
name='Test product', price=Decimal('10.00'),
product_class=product_class)
- variant = ProductVariant.objects.create(product=product, sku='A')
+ variant = ProductVariant.objects.create(product=product, sku='SKU_A')
warehouse = StockLocation.objects.create(name='Warehouse 1')
stock = Stock.objects.create(
variant=variant, cost_price=1, quantity=5, quantity_allocated=3,
@@ -227,7 +227,7 @@ def order_with_items_and_stock(order, product_class):
delivery_group=group,
product=product,
product_name=product.name,
- product_sku='SKU_%d' % (product.pk,),
+ product_sku='SKU_A',
quantity=3,
unit_price_net=Decimal('30.00'),
unit_price_gross=Decimal('30.00'),
@@ -236,7 +236,7 @@ def order_with_items_and_stock(order, product_class):
product = Product.objects.create(
name='Test product 2', price=Decimal('20.00'),
product_class=product_class)
- variant = ProductVariant.objects.create(product=product, sku='B')
+ variant = ProductVariant.objects.create(product=product, sku='SKU_B')
stock = Stock.objects.create(
variant=variant, cost_price=2, quantity=2, quantity_allocated=2,
location=warehouse)
@@ -244,7 +244,7 @@ def order_with_items_and_stock(order, product_class):
delivery_group=group,
product=product,
product_name=product.name,
- product_sku='SKU_%d' % (product.pk,),
+ product_sku='SKU_B',
quantity=2,
unit_price_net=Decimal('20.00'),
unit_price_gross=Decimal('20.00'),
diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.py
index ba88fcf637..1c682cd25a 100644
--- a/tests/dashboard/test_order.py
+++ b/tests/dashboard/test_order.py
@@ -2,9 +2,10 @@ from __future__ import unicode_literals
import pytest
from django.core.urlresolvers import reverse
-from saleor.dashboard.order.forms import MoveItemsForm
+from saleor.dashboard.order.forms import ChangeQuantityForm, MoveItemsForm
from saleor.order.models import Order, OrderHistoryEntry, OrderedItem, DeliveryGroup
-from saleor.product.models import Stock
+from saleor.order.utils import add_items_to_delivery_group
+from saleor.product.models import Stock, ProductVariant
from tests.utils import get_redirect_location, get_url_path
@@ -50,6 +51,131 @@ def test_view_cancel_order_line(admin_client, order_with_items_and_stock):
assert response.context['messages']
+def test_view_change_order_line_quantity(admin_client, order_with_items_and_stock):
+ """
+ user goes to order details page
+ user selects first order line with quantity 3 and changes it to 2
+ """
+ lines_before_quantity_change = order_with_items_and_stock.get_items()
+ lines_before_quantity_change_count = lines_before_quantity_change.count()
+ line = lines_before_quantity_change.first()
+ line_quantity_before_quantity_change = line.quantity
+
+ url = reverse(
+ 'dashboard:orderline-change-quantity', kwargs={
+ 'order_pk': order_with_items_and_stock.pk,
+ 'line_pk': line.pk})
+ response = admin_client.get(url)
+ assert response.status_code == 200
+ response = admin_client.post(
+ url, {'quantity': 2}, follow=True)
+ redirected_to, redirect_status_code = response.redirect_chain[-1]
+ # check redirection
+ assert redirect_status_code == 302
+ assert get_url_path(redirected_to) == reverse(
+ 'dashboard:order-details',
+ args=[order_with_items_and_stock.pk])
+ # success messages should appear after redirect
+ assert response.context['messages']
+ lines_after = Order.objects.get().get_items()
+ # order should have the same lines
+ assert lines_before_quantity_change_count == lines_after.count()
+ # stock allocation should be 2 now
+ assert Stock.objects.first().quantity_allocated == 2
+ line.refresh_from_db()
+ # source line quantity should be decreased to 2
+ assert line.quantity == 2
+ # order should have the same delivery groups count
+ assert order_with_items_and_stock.groups.count() == 1
+ # a note in the order's history should be created
+ assert OrderHistoryEntry.objects.get(
+ order=order_with_items_and_stock).comment == (
+ 'Changed quantity for product %(product)s from'
+ ' %(old_quantity)s to %(new_quantity)s') % {
+ 'product': line.product,
+ 'old_quantity': line_quantity_before_quantity_change,
+ 'new_quantity': 2}
+
+
+def test_view_change_order_line_quantity_with_invalid_data(
+ admin_client, order_with_items_and_stock):
+ """
+ user goes to order details page
+ user selects the first order line with quantity 3 and try to change it to 0 and -1
+ user gets an error.
+ """
+ lines = order_with_items_and_stock.get_items()
+ line = lines.first()
+ url = reverse(
+ 'dashboard:orderline-change-quantity', kwargs={
+ 'order_pk': order_with_items_and_stock.pk,
+ 'line_pk': line.pk})
+ response = admin_client.post(
+ url, {'quantity': 0})
+ assert response.status_code == 400
+
+def test_dashboard_change_quantity_form(request_cart_with_item, order):
+ cart = request_cart_with_item
+ group = DeliveryGroup.objects.create(order=order)
+ add_items_to_delivery_group(group, cart.lines.all())
+ order_line = group.items.get()
+ variant = ProductVariant.objects.get(sku=order_line.product_sku)
+
+ # Check max quantity validation
+ form = ChangeQuantityForm(
+ {'quantity': 9999},
+ instance=order_line,
+ variant=variant)
+ assert not form.is_valid()
+ assert form.errors['quantity'] == ['Ensure this value is less than or equal to 50.']
+
+ # Check minimum quantity validation
+ form = ChangeQuantityForm(
+ {'quantity': 0},
+ instance=order_line,
+ variant=variant)
+ assert not form.is_valid()
+ assert group.items.get().stock.quantity_allocated == 1
+
+ # Check available quantity validation
+ form = ChangeQuantityForm(
+ {'quantity': 20},
+ instance=order_line,
+ variant=variant)
+ assert not form.is_valid()
+ assert group.items.get().stock.quantity_allocated == 1
+ assert form.errors['quantity'] == ['Only 4 remaining in stock.']
+
+ # Save same quantity
+ form = ChangeQuantityForm(
+ {'quantity': 1},
+ instance=order_line,
+ variant=variant)
+ assert form.is_valid()
+ form.save()
+ assert group.items.get().stock.quantity_allocated == 1
+ # Increase quantity
+ form = ChangeQuantityForm(
+ {'quantity': 2},
+ instance=order_line,
+ variant = variant)
+ assert form.is_valid()
+ form.save()
+ assert group.items.get().stock.quantity_allocated == 2
+ # Decrease quantity
+ form = ChangeQuantityForm(
+ {'quantity': 1},
+ instance=order_line,
+ variant=variant)
+ assert form.is_valid()
+ form.save()
+ assert group.items.get().stock.quantity_allocated == 1
+
+
@pytest.mark.integration
@pytest.mark.django_db
def test_view_split_order_line(admin_client, order_with_items_and_stock):
diff --git a/tests/test_order.py b/tests/test_order.py
index c6316180a3..178fe9e71a 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -1,7 +1,6 @@
from prices import Price
from saleor.cart.models import Cart
-from saleor.dashboard.order.forms import ChangeQuantityForm
from saleor.order import models
from saleor.order.utils import add_items_to_delivery_group
@@ -39,37 +38,6 @@ def test_stock_allocation(billing_address, product_in_stock):
assert stock.quantity_allocated == 2
-def test_dashboard_change_quantity_form(request_cart_with_item, order):
- cart = request_cart_with_item
- group = models.DeliveryGroup.objects.create(order=order)
- add_items_to_delivery_group(group, cart.lines.all())
- order_line = group.items.get()
-
- # Check available quantity validation
- form = ChangeQuantityForm({'quantity': 9999},
- instance=order_line)
- assert not form.is_valid()
- assert group.items.get().stock.quantity_allocated == 1
- # Save same quantity
- form = ChangeQuantityForm({'quantity': 1},
- instance=order_line)
- assert form.is_valid()
- form.save()
- assert group.items.get().stock.quantity_allocated == 1
- # Increase quantity
- form = ChangeQuantityForm({'quantity': 2},
- instance=order_line)
- assert form.is_valid()
- form.save()
- assert group.items.get().stock.quantity_allocated == 2
- # Decrease quantity
- form = ChangeQuantityForm({'quantity': 1},
- instance=order_line)
- assert form.is_valid()
- form.save()
- assert group.items.get().stock.quantity_allocated == 1
-
-
def test_order_discount(sale, order, request_cart_with_item):
cart = request_cart_with_item
group = models.DeliveryGroup.objects.create(order=order)