Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Test order edit shipping view
Anna Siwik02166d5cd4b0
diff --git a/saleor/dashboard/forms.py b/saleor/dashboard/forms.pyindex 997bc7bb7b..b7f5bf3f41 100644--- a/saleor/dashboard/forms.py+++ b/saleor/dashboard/forms.py@@ -65,7 +65,7 @@ class AjaxSelect2ChoiceField(forms.ChoiceField):def set_initial(self, obj, obj_id=None, label=None):"""Set initially selected objects on field's widget."""selected = {- 'id': obj_id if obj_id else obj.pk,+ 'id': obj_id if obj_id is not None else obj.pk,'text': label if label else str(obj)}self.widget.attrs['data-initial'] = json.dumps(selected)diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex e2e3b43215..66f31cfc0e 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -23,7 +23,7 @@ from ...order.utils import (recalculate_order)from ...product.models import Product, ProductVariant, Stockfrom ...product.utils import allocate_stock, deallocate_stock-from ...shipping.models import ShippingMethodCountry+from ...shipping.models import ANY_COUNTRY, ShippingMethodCountryfrom ..forms import AjaxSelect2ChoiceFieldfrom ..widgets import PhonePrefixWidgetfrom .utils import fulfill_order_line, update_order_with_user_addresses@@ -56,6 +56,17 @@ class ConfirmDraftOrderForm(forms.ModelForm):errors.append(forms.ValidationError(pgettext_lazy('Confirm draft order form error','Shipping method is required to handle shipping')))+ method = self.instance.shipping_method+ shipping_address = self.instance.shipping_address+ if (+ method and shipping_address and+ method.country_code != ANY_COUNTRY and+ shipping_address.country.code != method.country_code+ ):+ errors.append(forms.ValidationError(pgettext_lazy(+ 'Confirm draft order form error',+ 'Shipping method is not valid for chosen shipping '+ 'address')))if errors:raise forms.ValidationError(errors)return self.cleaned_data@@ -115,7 +126,7 @@ class OrderShippingForm(forms.ModelForm):shipping_method = AjaxSelect2ChoiceField(queryset=ShippingMethodCountry.objects.all(),- required=True, min_input=0)+ required=False, min_input=0)class Meta:model = Order@@ -126,14 +137,23 @@ class OrderShippingForm(forms.ModelForm):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)- method = self.instance.shipping_method- if method:- self.fields['shipping_method'].set_initial(- method, label=method.label)+ method_field = self.fields['shipping_method']fetch_data_url = reverse('dashboard:ajax-order-shipping-methods',kwargs={'order_pk': self.instance.id})- self.fields['shipping_method'].set_fetch_data_url(fetch_data_url)+ method_field.set_fetch_data_url(fetch_data_url)++ method = self.instance.shipping_method+ if method:+ method_field.set_initial(method, label=method.label)+ else:+ method_field.set_initial(None, obj_id='', label='----')++ if self.instance.shipping_address:+ country_code = self.instance.shipping_address.country.code+ queryset = method_field.queryset.unique_for_country_code(+ country_code)+ method_field.queryset = querysetdef save(self, commit=True):method = self.instance.shipping_method@@ -141,7 +161,7 @@ class OrderShippingForm(forms.ModelForm):self.instance.shipping_method_name = method.shipping_method.nameself.instance.shipping_price = method.get_total_price()else:- self.instance.shipping_method_name = ''+ self.instance.shipping_method_name = Noneself.instance.shipping_price = ZERO_TAXED_MONEYreturn super().save(commit)diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex f3ed25799c..574af0bf28 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -357,7 +357,7 @@ def order_customer_edit(request, order_pk):@staff_member_required@permission_required('order.edit_order')def order_shipping_edit(request, order_pk):- order = Order.objects.get(pk=order_pk)+ order = get_object_or_404(Order, pk=order_pk, status=OrderStatus.DRAFT)form = OrderShippingForm(request.POST or None, instance=order)status = 200if form.is_valid():@@ -623,7 +623,8 @@ def ajax_shipping_methods_list(request, order_pk):Q(shipping_method__name__icontains=search_query) |Q(price__icontains=search_query))- shipping_methods = [+ shipping_methods = [{'id': '', 'text': '----'}]+ shipping_methods += [{'id': method.pk, 'text': method.label}for method in queryset]return JsonResponse({'results': shipping_methods})diff --git a/saleor/dashboard/views.py b/saleor/dashboard/views.pyindex 57f342102c..7eb18c45be 100644--- a/saleor/dashboard/views.py+++ b/saleor/dashboard/views.py@@ -38,7 +38,8 @@ def index(request):orders_to_ship = Order.objects.filter(status__in=statuses).select_related('user').prefetch_related('lines', 'payments')orders_to_ship = [- order for order in orders_to_ship if order.is_fully_paid()]+ order for order in orders_to_ship+ if order.is_fully_paid() and order.status == OrderStatus.FULFILLED]payments = Payment.objects.filter(status=PaymentStatus.PREAUTH).order_by('-created')payments = payments.select_related('order', 'order__user')diff --git a/saleor/order/migrations/0044_auto_20180322_0704.py b/saleor/order/migrations/0044_auto_20180322_0704.pynew file mode 100644index 0000000000..39c27385c0--- /dev/null+++ b/saleor/order/migrations/0044_auto_20180322_0704.py@@ -0,0 +1,18 @@+# Generated by Django 2.0.3 on 2018-03-22 12:04++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('order', '0043_auto_20180321_1110'),+ ]++ operations = [+ migrations.AlterField(+ model_name='order',+ name='language_code',+ field=models.CharField(default='en', max_length=35),+ ),+ ]diff --git a/templates/dashboard/order/detail.html b/templates/dashboard/order/detail.htmlindex 174d209da3..ed6f0a5e42 100644--- a/templates/dashboard/order/detail.html+++ b/templates/dashboard/order/detail.html@@ -325,10 +325,15 @@<tr class="last-no-border"><td class="right-align" colspan="3"><p>{% trans "Subtotal" context "Order subtotal" %}</p>- <a href="#base-modal" data-href="{% url 'dashboard:order-shipping-edit' order_pk=order.pk %}"- class="modal-trigger-custom" title="{% trans "Edit shipping" context "Order totals action" %}">+ <p>+ {% if order.is_draft %}+ <a href="#base-modal" data-href="{% url 'dashboard:order-shipping-edit' order_pk=order.pk %}"+ class="modal-trigger-custom" title="{% trans "Edit shipping" context "Order totals action" %}">+ {% trans "Shipping" context "Order totals header" %} ({{ order.shipping_method_name|default:"-" }})+ </a>+ {% else %}{% trans "Shipping" context "Order totals header" %} ({{ order.shipping_method_name|default:"-" }})- </a>+ {% endif %}</p>{% if order.is_draft or order.discount_amount %}<p>diff --git a/tests/conftest.py b/tests/conftest.pyindex d43eaf1729..7b3cde191c 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -440,6 +440,7 @@ def order_with_lines(order, product_type, default_category, shipping_method):order.shipping_address = order.billing_address.get_copy()order.shipping_method_name = shipping_method.namemethod = shipping_method.price_per_country.get()+ order.shipping_method = methodorder.shipping_price = method.get_total_price()order.save()diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.pyindex da7b4d89d3..37ddf74477 100644--- a/tests/dashboard/test_order.py+++ b/tests/dashboard/test_order.py@@ -2,11 +2,13 @@ from decimal import Decimalfrom unittest.mock import patchimport pytest+from django.conf import settingsfrom django.urls import reversefrom payments import PaymentStatusfrom prices import Money, TaxedMoneyfrom tests.utils import get_form_errors, get_redirect_location+from saleor.core.utils import ZERO_TAXED_MONEYfrom saleor.dashboard.order.forms import ChangeQuantityForm, OrderNoteFormfrom saleor.dashboard.order.utils import fulfill_order_linefrom saleor.order import OrderStatus@@ -933,6 +935,27 @@ def test_view_confirm_draft_order_no_shipping_address(assert 'Shipping address is required to handle shipping' in errors+def test_view_confirm_draft_order_shipping_method_not_valid(+ admin_client, draft_order, shipping_method):+ method = shipping_method.price_per_country.create(+ country_code='DE', price=10)+ draft_order.shipping_method = method+ draft_order.save()+ url = reverse(+ 'dashboard:draft-order-confirm', kwargs={'order_pk': draft_order.pk})+ data = {'csrfmiddlewaretoken': 'hello'}++ response = admin_client.post(url, data)++ assert response.status_code == 400+ draft_order.refresh_from_db()+ assert draft_order.status == OrderStatus.DRAFT+ errors = get_form_errors(response)+ error = 'Shipping method is not valid for chosen shipping address'+ assert error in errors++@pytest.mark.django_dbdef test_view_confirm_draft_order_no_shipping_address_shipping_not_required(admin_client, order, product_without_shipping):@@ -1048,6 +1071,53 @@ def test_view_order_customer_edit_not_valid(admin_client, customer_user):@pytest.mark.django_db-def test_view_order_shipping_edit(admin_client):- order = Order.objects.create()- pass+def test_view_order_shipping_edit(admin_client, draft_order, shipping_method):+ method = shipping_method.price_per_country.create(+ price=Money(5, settings.DEFAULT_CURRENCY), country_code='PL')+ url = reverse(+ 'dashboard:order-shipping-edit', kwargs={'order_pk': draft_order.pk})+ data = {'shipping_method': method.pk}++ response = admin_client.post(url, data)++ assert response.status_code == 302+ redirect_url = reverse(+ 'dashboard:order-details', kwargs={'order_pk': draft_order.pk})+ assert get_redirect_location(response) == redirect_url+ draft_order.refresh_from_db()+ assert draft_order.shipping_method_name == shipping_method.name+ assert draft_order.shipping_price == method.get_total_price()+ assert draft_order.shipping_method == method+++def test_view_order_shipping_edit_not_draft_order(+ admin_client, order_with_lines, shipping_method):+ method = shipping_method.price_per_country.create(+ price=5, country_code='PL')+ url = reverse(+ 'dashboard:order-shipping-edit',+ kwargs={'order_pk': order_with_lines.pk})+ data = {'shipping_method': method.pk}++ response = admin_client.post(url, data)++ assert response.status_code == 404+++def test_view_order_shipping_edit_remove_shipping(admin_client, draft_order):+ url = reverse(+ 'dashboard:order-shipping-edit', kwargs={'order_pk': draft_order.pk})+ data = {'shipping_method': ''}++ response = admin_client.post(url, data)++ assert response.status_code == 302+ redirect_url = reverse(+ 'dashboard:order-details', kwargs={'order_pk': draft_order.pk})+ assert get_redirect_location(response) == redirect_url+ draft_order.refresh_from_db()+ assert not draft_order.shipping_method+ assert not draft_order.shipping_method_name+ assert draft_order.shipping_price == ZERO_TAXED_MONEY