Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Code improvements after review
Anna Siwik12d18a2a0332
diff --git a/docs/architecture/orders.rst b/docs/architecture/orders.rstindex 56b2a93302..1abd8a59ff 100644--- a/docs/architecture/orders.rst+++ b/docs/architecture/orders.rst@@ -35,4 +35,4 @@ There are four possible order statuses, based on statuses of its fulfillments:- ``CANCELED``Order has been canceled. Every fulfillment (if there is any) has ``CANCELED`` status. Order doesn't require further actions by a shop operator.-There is also ``DRAFT`` status, used for orders created from dashboard.+There is also ``DRAFT`` status, used for orders newly created from dashboard and not yet published.diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex d2e105b97e..54d2d1a7b5 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -43,12 +43,12 @@ def _get_product_or_category_voucher_discount_for_checkout(voucher, checkout):"""Calculate discount value for a voucher of product or category type."""if voucher.type == VoucherType.PRODUCT:prices = [- item[1] for item in get_product_variants_and_prices(- checkout.cart, voucher.product)]+ variant_price for _, variant_price in+ get_product_variants_and_prices(checkout.cart, voucher.product)]else:prices = [- item[1] for item in get_category_variants_and_prices(- checkout.cart, voucher.category)]+ variant_price for _, variant_price in+ get_category_variants_and_prices(checkout.cart, voucher.category)]if not prices:msg = pgettext('Voucher not applicable',diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex a9d22d0516..6c18eafaba 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -29,11 +29,11 @@ from ..forms import AjaxSelect2ChoiceFieldfrom ..widgets import PhonePrefixWidgetfrom .utils import (fulfill_order_line, get_voucher_discount_for_order,- update_order_with_user_addresses)+ remove_customer_from_order, update_order_with_user_addresses)class CreateOrderFromDraftForm(forms.ModelForm):- """Save draft order as a ready to fulfill."""+ """Mark draft order as ready to fulfill."""notify_customer = forms.BooleanField(label=pgettext_lazy('Send email to customer about order created by staff users',@@ -59,11 +59,11 @@ class CreateOrderFromDraftForm(forms.ModelForm):if self.instance.is_shipping_required():method = self.instance.shipping_methodshipping_address = self.instance.shipping_address- if (+ shipping_not_valid = (method and shipping_address andmethod.country_code != ANY_COUNTRY and- shipping_address.country.code != method.country_code- ):+ shipping_address.country.code != method.country_code)+ if shipping_not_valid:errors.append(forms.ValidationError(pgettext_lazy('Create draft order form error','Shipping method is not valid for chosen shipping '@@ -137,28 +137,8 @@ class OrderRemoveCustomerForm(forms.ModelForm):model = Orderfields = []- def __init__(self, *args, **kwargs):- super().__init__(*args, **kwargs)-def save(self):- customer = self.instance.user- self.instance.user = None- self.instance.user_email = ''- super().save()-- if customer:- if (- customer.default_billing_address ==- self.instance.billing_address- ):- self.instance.billing_address.delete()-- if (- customer.default_shipping_address ==- self.instance.shipping_address- ):- self.instance.shipping_address.delete()-+ remove_customer_from_order(self.instance)return self.instancediff --git a/saleor/dashboard/order/utils.py b/saleor/dashboard/order/utils.pyindex 219936ce4d..8c558e6742 100644--- a/saleor/dashboard/order/utils.py+++ b/saleor/dashboard/order/utils.py@@ -121,12 +121,12 @@ def _get_product_or_category_voucher_discount_for_order(order):"""Calculate discount value for a voucher of product or category type."""if order.voucher.type == VoucherType.PRODUCT:prices = [- item[1] for item in get_product_variants_and_prices(- order, order.voucher.product)]+ variant_price for _, variant_price in+ get_product_variants_and_prices(order, order.voucher.product)]else:prices = [- item[1] for item in get_category_variants_and_prices(- order, order.voucher.category)]+ variant_price for _, variant_price in+ get_category_variants_and_prices(order, order.voucher.category)]if not prices:return Money(0, settings.DEFAULT_CURRENCY)return get_product_or_category_voucher_discount(order.voucher, prices)@@ -162,3 +162,22 @@ def save_address_in_order(order, address, address_type):if not order.shipping_address:order.shipping_address = address.get_copy()order.save(update_fields=['billing_address', 'shipping_address'])+++def remove_customer_from_order(order):+ """Remove related customer and user email from order.++ If billing and shipping addresses are set to related customer's default+ addresses and were not edited, remove them as well.+ """+ customer = order.user+ order.user = None+ order.user_email = ''+ order.save()++ if customer:+ if customer.default_billing_address == order.billing_address:+ order.billing_address.delete()++ if customer.default_shipping_address == order.shipping_address:+ order.shipping_address.delete()diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex 8b443a23e3..b7ad3d23ef 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -134,12 +134,14 @@ def order_details(request, order_pk):balance = captured - order.totalelse:can_capture = can_release = can_refund = False+ can_mark_as_paid = not order.payments.exists()is_many_stock_locations = StockLocation.objects.count() > 1ctx = {'order': order, 'all_payments': all_payments, 'payment': payment,'notes': notes, 'captured': captured, 'balance': balance,'preauthorized': preauthorized, 'can_capture': can_capture,'can_release': can_release, 'can_refund': can_refund,- 'is_many_stock_locations': is_many_stock_locations}+ 'is_many_stock_locations': is_many_stock_locations,+ 'can_mark_as_paid': can_mark_as_paid}return TemplateResponse(request, 'dashboard/order/detail.html', ctx)diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 8e879f44ca..dd155679a1 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -173,9 +173,6 @@ class Order(models.Model):def can_cancel(self):return self.status not in {OrderStatus.CANCELED, OrderStatus.DRAFT}- def can_mark_as_paid(self):- return not self.payments.exists()-class OrderLine(models.Model):order = models.ForeignKey(diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 47644d5d38..5cb7388cff 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -42,9 +42,10 @@ def recalculate_order(order, discount_amount=None):prices = [line.get_total() for line in order]total = sum(prices, order.shipping_price)# discount amount can't be greater than order total- order.discount_amount = min(+ current_discount_amount = (discount_amount or order.discount_amount or- Money(0, settings.DEFAULT_CURRENCY), total.gross)+ Money(0, settings.DEFAULT_CURRENCY))+ order.discount_amount = min(current_discount_amount, total.gross)if order.discount_amount:total -= order.discount_amountorder.total = totaldiff --git a/templates/dashboard/order/detail.html b/templates/dashboard/order/detail.htmlindex 4a42af231f..3f38114ad1 100644--- a/templates/dashboard/order/detail.html+++ b/templates/dashboard/order/detail.html@@ -174,7 +174,7 @@{% trans "Release" context "Order summary card action" %}</a>{% endif %}- {% if order.can_mark_as_paid %}+ {% if can_mark_as_paid %}<a href="#base-modal" data-href="{% url 'dashboard:order-mark-as-paid' order_pk=order.pk %}" class="btn-flat modal-trigger-custom waves-effect">{% trans "Mark as paid" context "Order detail action" %}</a>diff --git a/tests/conftest.py b/tests/conftest.pyindex 83bfc7799d..97303d95d3 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -52,7 +52,7 @@ def cart(db): # pylint: disable=W0613@pytest.fixture-def default_billing_address(db): # pylint: disable=W0613+def address(db): # pylint: disable=W0613return Address.objects.create(first_name='John', last_name='Doe',company_name='Mirumee Software',@@ -64,13 +64,14 @@ def default_billing_address(db): # pylint: disable=W0613@pytest.fixture-def customer_user(db, default_billing_address): # pylint: disable=W0613+def customer_user(db, address): # pylint: disable=W0613+ default_address = address.get_copy()user = User.objects.create_user('password',- default_billing_address=default_billing_address,- default_shipping_address=default_billing_address)- user.addresses.add(default_billing_address)+ default_billing_address=default_address,+ default_shipping_address=default_address)+ user.addresses.add(default_address)return userdiff --git a/tests/test_account.py b/tests/test_account.pyindex 344bf9d0b6..69ccd0f8c1 100644--- a/tests/test_account.py+++ b/tests/test_account.py@@ -126,8 +126,7 @@ def test_order_with_lines_pagination(authorized_client, order_list, settings):assert response.status_code == 200-def test_format_address(default_billing_address):- address = default_billing_address+def test_format_address(address):formatted_address = format_address(address)address_html = '<br>'.join(map(str, formatted_address['address_lines']))context = Context({'address': address})@@ -140,8 +139,7 @@ def test_format_address(default_billing_address):assert str(address.phone) in rendered_html-def test_format_address_all_options(default_billing_address):- address = default_billing_address+def test_format_address_all_options(address):formatted_address = format_address(address, include_phone=False, inline=True, latin=True)address_html = ', '.join(map(str, formatted_address['address_lines']))@@ -156,8 +154,8 @@ def test_format_address_all_options(default_billing_address):assert str(address.phone) not in rendered_html-def test_address_as_data(default_billing_address):- data = default_billing_address.as_data()+def test_address_as_data(address):+ data = address.as_data()assert data == {'first_name': 'John','last_name': 'Doe',@@ -172,26 +170,26 @@ def test_address_as_data(default_billing_address):'phone': '+48713988102'}-def test_copy_address(default_billing_address):- copied_address = default_billing_address.get_copy()- assert copied_address.pk != default_billing_address.pk- assert copied_address == default_billing_address+def test_copy_address(address):+ copied_address = address.get_copy()+ assert copied_address.pk != address.pk+ assert copied_address == address-def test_compare_addresses(default_billing_address):- copied_address = default_billing_address.get_copy()- assert default_billing_address == copied_address+def test_compare_addresses(address):+ copied_address = address.get_copy()+ assert address == copied_address-def test_compare_addresses_with_country_object(default_billing_address):- copied_address = default_billing_address.get_copy()+def test_compare_addresses_with_country_object(address):+ copied_address = address.get_copy()copied_address.country = Country('PL')copied_address.save()- assert default_billing_address == copied_address+ assert address == copied_address-def test_compare_addresses_different_country(default_billing_address):- copied_address = default_billing_address.get_copy()+def test_compare_addresses_different_country(address):+ copied_address = address.get_copy()copied_address.country = Country('FR')copied_address.save()- assert default_billing_address != copied_address+ assert address != copied_addressdiff --git a/tests/test_elasticsearch.py b/tests/test_elasticsearch.pyindex e5939d4efd..16cd209ba8 100644--- a/tests/test_elasticsearch.py+++ b/tests/test_elasticsearch.py@@ -160,13 +160,12 @@ def test_dashboard_search_user_name(db, admin_client, customers):@pytest.fixture-def orders(db, default_billing_address):+def orders(db, address):all_pks = set()for email, pks in ORDERS.items():for pk in pks:Order.objects.create(- billing_address=default_billing_address,- user_email=email, pk=pk)+ billing_address=address, user_email=email, pk=pk)all_pks = all_pks | pksreturn all_pks