Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix dashboard order line split view - remove no-break space inside template to make form submit functional again - add form validators to avoid invalid submissions - add redirect after form successful submission - add tests
Marco Badan9fef1949fe06
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex 2c0ef81be6..5a5befd5ce 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -2,6 +2,7 @@ from __future__ import unicode_literalsfrom django import formsfrom django.conf import settings+from django.core.validators import MinValueValidator, MaxValueValidatorfrom django.shortcuts import get_object_or_404from django.utils.translation import npgettext_lazy, pgettext_lazyfrom django_prices.forms import PriceField@@ -108,14 +109,18 @@ class ReleasePaymentForm(forms.Form):class MoveItemsForm(forms.Form):+ NEW_SHIPMENT = 'new'quantity = QuantityField(- label=pgettext_lazy('Move items form label', 'Quantity'))+ label=pgettext_lazy('Move items form label', 'Quantity'),+ validators=[MinValueValidator(1)])target_group = forms.ChoiceField(label=pgettext_lazy('Move items form label', 'Target shipment'))def __init__(self, *args, **kwargs):self.item = kwargs.pop('item')super(MoveItemsForm, self).__init__(*args, **kwargs)+ self.fields['quantity'].validators.append(+ MaxValueValidator(self.item.quantity))self.fields['quantity'].widget.attrs.update({'max': self.item.quantity, 'min': 1})self.fields['target_group'].choices = self.get_delivery_group_choices()@@ -124,7 +129,7 @@ class MoveItemsForm(forms.Form):group = self.item.delivery_groupgroups = group.order.groups.exclude(pk=group.pk).exclude(status='cancelled')- choices = [('new', pgettext_lazy(+ choices = [(self.NEW_SHIPMENT, pgettext_lazy('Delivery group value for `target_group` field','New shipment'))]choices.extend([(g.pk, str(g)) for g in groups])@@ -134,7 +139,7 @@ class MoveItemsForm(forms.Form):how_many = self.cleaned_data['quantity']choice = self.cleaned_data['target_group']old_group = self.item.delivery_group- if choice == 'new':+ if choice == self.NEW_SHIPMENT:# For new group we use the same delivery name but zero pricetarget_group = old_group.order.groups.create(status=old_group.status,diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex d43c1213d6..ee0c902ec3 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -208,6 +208,7 @@ def orderline_split(request, order_pk, line_pk):'new_group': target_group}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 = 400ctx = {'order': order, 'object': item, 'form': form, 'line_pk': line_pk}diff --git a/templates/dashboard/order/modal_split_order_line.html b/templates/dashboard/order/modal_split_order_line.htmlindex a71a3a80b8..5b6ce0d202 100644--- a/templates/dashboard/order/modal_split_order_line.html+++ b/templates/dashboard/order/modal_split_order_line.html@@ -1,7 +1,7 @@{% load i18n %}{% load materializecss %}-<form method="post" role="form" class="form-async" action="{% url 'dashboard:orderline-split' order_pk=order.pk line_pk=line_pk %}" novalidate>+<form method="post" role="form" class="form-async" action="{% url 'dashboard:orderline-split' order_pk=order.pk line_pk=line_pk %}" novalidate>{% csrf_token %}<div class="modal-content"><h5>diff --git a/tests/conftest.py b/tests/conftest.pyindex e2414d3d1a..71b09df0da 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -11,8 +11,6 @@ from saleor.cart import utilsfrom saleor.cart.models import Cartfrom saleor.checkout.core import Checkoutfrom saleor.discount.models import Voucher, Sale-from saleor.order.models import Order-from saleor.discount.models import Voucherfrom saleor.order.models import Order, OrderedItem, DeliveryGroupfrom saleor.product.models import (AttributeChoiceValue, Category, Product,ProductAttribute, ProductClass,@@ -251,6 +249,8 @@ def order_with_items_and_stock(order, product_class):unit_price_gross=Decimal('20.00'),stock=stock)+ Order.objects.recalculate_order(order)+ order.refresh_from_db()return orderdiff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.pyindex e22ffe8bdc..ba88fcf637 100644--- a/tests/dashboard/test_order.py+++ b/tests/dashboard/test_order.py@@ -2,9 +2,10 @@ from __future__ import unicode_literalsimport pytestfrom django.core.urlresolvers import reverse+from saleor.dashboard.order.forms import MoveItemsFormfrom saleor.order.models import Order, OrderHistoryEntry, OrderedItem, DeliveryGroupfrom saleor.product.models import Stock-from tests.utils import get_redirect_location+from tests.utils import get_redirect_location, get_url_path@pytest.mark.integration@@ -34,8 +35,8 @@ def test_view_cancel_order_line(admin_client, order_with_items_and_stock):# check stock deallocationassert Stock.objects.first().quantity_allocated == quantity_allocated_before - line_quantity# check note in the order's history- OrderHistoryEntry.objects.get(- order=order_with_items_and_stock).message = 'Cancelled item %s' % product+ assert OrderHistoryEntry.objects.get(+ order=order_with_items_and_stock).comment == 'Cancelled item %s' % producturl = reverse('dashboard:orderline-cancel', kwargs={'order_pk': order_with_items_and_stock.pk,@@ -47,3 +48,103 @@ def test_view_cancel_order_line(admin_client, order_with_items_and_stock):assert DeliveryGroup.objects.count() == 0# check success messages after redirectassert response.context['messages']+++def test_view_split_order_line(admin_client, order_with_items_and_stock):+ """+ user goes to order details page+ user selects first order line with quantity 3 and moves 2 items+ to a new shipment+ user selects the line from the new shipment and moves all items+ back to the first shipment+ """+ lines_before_split = order_with_items_and_stock.get_items()+ lines_before_split_count = lines_before_split.count()+ line = lines_before_split.first()+ line_quantity_before_split = line.quantity+ quantity_allocated_before_split = line.stock.quantity_allocated+ old_delivery_group = DeliveryGroup.objects.get()++ url = reverse(+ 'dashboard:orderline-split', 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, 'target_group': MoveItemsForm.NEW_SHIPMENT},+ 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 one more line+ assert lines_before_split_count + 1 == lines_after.count()+ # stock allocation should not be changed+ assert Stock.objects.first().quantity_allocated == quantity_allocated_before_split+ line.refresh_from_db()+ # source line quantity should be decreased to 1+ assert line.quantity == line_quantity_before_split - 2+ # order should have 2 delivery groups now+ assert order_with_items_and_stock.groups.count() == 2+ # a note in the order's history should be created+ new_group = DeliveryGroup.objects.last()+ assert OrderHistoryEntry.objects.get(+ order=order_with_items_and_stock).comment == (+ 'Moved 2 items %(item)s from '+ '%(old_group)s to %(new_group)s') % {+ 'item': line,+ 'old_group': old_delivery_group,+ 'new_group': new_group}+ new_line = new_group.items.get()+ # the new line should contain the moved quantity+ assert new_line.quantity == 2+ url = reverse(+ 'dashboard:orderline-split', kwargs={+ 'order_pk': order_with_items_and_stock.pk,+ 'line_pk': new_line.pk})+ admin_client.post(+ url, {'quantity': 2, 'target_group': old_delivery_group.pk})+ # an other note in the order's history should be created+ assert OrderHistoryEntry.objects.filter(+ order=order_with_items_and_stock).last().comment ==(+ 'Moved 2 items %(item)s from removed '+ 'group to %(new_group)s') % {+ 'item': line,+ 'new_group': old_delivery_group}+ # the new shipment should be removed+ assert order_with_items_and_stock.groups.count() == 1+ # the related order line should be removed+ assert lines_before_split_count == Order.objects.get().get_items().count()+ line.refresh_from_db()+ # the initial line should get the quantity restored to its initial value+ assert line_quantity_before_split == line.quantity++[email protected]('quantity', [0, 4])+def test_view_split_order_line_with_invalid_data(admin_client, order_with_items_and_stock, quantity):+ """+ user goes to order details page+ user selects first order line with quantity 3 and try move 0 and 4 items to a new shipment+ user gets an error and no delivery groups are created.+ """+ lines = order_with_items_and_stock.get_items()+ line = lines.first()+ url = reverse(+ 'dashboard:orderline-split', kwargs={+ 'order_pk': order_with_items_and_stock.pk,+ 'line_pk': line.pk})+ response = admin_client.post(+ url, {'quantity': quantity, 'target_group': MoveItemsForm.NEW_SHIPMENT})+ assert response.status_code == 400+ assert DeliveryGroup.objects.count() == 1diff --git a/tests/utils.py b/tests/utils.pyindex 7b2c7bfad2..91510f82d8 100644--- a/tests/utils.py+++ b/tests/utils.py@@ -7,13 +7,14 @@ from django.db.models import Qfrom django.utils.encoding import smart_text+def get_url_path(url):+ parsed_url = urlparse(url)+ return parsed_url.path++def get_redirect_location(response):# Due to Django 1.8 compatibility, we have to handle both cases- location = response['Location']- if location.startswith('http'):- url = urlparse(location)- location = url.path- return location+ return get_url_path(response['Location'])def filter_products_by_attribute(queryset, attribute_id, value):