Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Drop Order signals, fix tests
Pacu26c07d086b889
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex dbb514ae8e..4a15f0001e 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -889,7 +889,6 @@ def is_fully_paid(cart: Cart):payment_methods = cart.payment_methods.filter(is_active=True)total_paid = sum([p.captured_amount.amount for p in payment_methods])- import pdb; pdb.set_trace()return total_paid >= cart.get_total().gross.amountdiff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex d0edf8ef92..e68ce25379 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -378,28 +378,30 @@ def create_fake_user():def create_transactions(payment):- #FIXME Add tests+ # FIXME Add tests for this functionpayment.transactions.create(transaction_type=TransactionType.AUTH,- is_success=True, amount=payment.total)+ is_success=True, amount=payment.total.gross, gateway_response={})if payment.charge_status == ChargeStatus.NOT_CHARGED:if random.randint(0, 1):payment.transactions.create(transaction_type=TransactionType.VOID,- is_success=True, amount=payment.total)+ is_success=True, amount=payment.total.gross,+ gateway_response={})returnpayment.transactions.create(transaction_type=TransactionType.CAPTURE,- is_success=True, amount=payment.total)+ is_success=True, amount=payment.total.gross, gateway_response={})if payment.charge_status == ChargeStatus.FULLY_REFUNDED:payment.transactions.create(transaction_type=TransactionType.REFUND,- is_success=True, amount=payment.total)+ is_success=True, amount=payment.total.gross,+ gateway_response={})return paymentdef create_payment(order):- #FIXME Add tests+ # FIXME Add tests for this functionstatus = random.choice([ChargeStatus.FULLY_REFUNDED,@@ -409,7 +411,6 @@ def create_payment(order):order=order,charge_status=status,variant='default',- transaction_id=str(fake.random_int(1, 100000)),total=order.total,customer_ip_address=fake.ipv4(),billing_first_name=order.billing_address.first_name,@@ -420,7 +421,7 @@ def create_payment(order):billing_postal_code=order.billing_address.postal_code,billing_country_code=order.billing_address.country,billing_country_area=order.billing_address.country_area)- if status == ChargeStatus.CONFIRMED:+ if status == ChargeStatus.CHARGED:payment.captured_amount = payment.total.grosspayment.save()create_transactions(payment)diff --git a/saleor/order/__init__.py b/saleor/order/__init__.pyindex 870166bcc0..0c86da372a 100644--- a/saleor/order/__init__.py+++ b/saleor/order/__init__.py@@ -1,22 +1,11 @@from enum import Enum-from django.apps import AppConfigfrom django.conf import settingsfrom django.utils.translation import npgettext_lazy, pgettext_lazyfrom django_prices.templatetags import prices_i18nfrom prices import Money-class OrderAppConfig(AppConfig):- name = 'saleor.order'-- def ready(self):- #FIXME should work with new dashboard- from payments.signals import status_changed- from .signals import order_status_change- status_changed.connect(order_status_change)--class OrderStatus:DRAFT = 'draft'UNFULFILLED = 'unfulfilled'diff --git a/saleor/order/models.py b/saleor/order/models.pyindex b88eeac272..8c5b066382 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -45,9 +45,9 @@ class OrderQueryset(models.QuerySet):fulfilled)."""statuses = {OrderStatus.UNFULFILLED, OrderStatus.PARTIALLY_FULFILLED}- return self.filter(status__in=statuses).annotate(- amount_paid=Sum('payments__captured_amount')).filter(- total_gross__lte=F('amount_paid'))+ qs = self.filter(status__in=statuses, payment_methods__is_active=True)+ qs = qs.annotate(amount_paid=Sum('payment_methods__captured_amount'))+ return qs.filter(total_gross__lte=F('amount_paid'))def ready_to_capture(self):"""Return orders with payments to capture.diff --git a/saleor/order/signals.py b/saleor/order/signals.pydeleted file mode 100644index bb9d86ec89..0000000000--- a/saleor/order/signals.py+++ /dev/null@@ -1,26 +0,0 @@-import logging--from . import OrderEvents, OrderEventsEmails-from ..core import analytics-from .emails import send_payment_confirmation--logger = logging.getLogger(__name__)---def order_status_change(sender, instance, **kwargs):- """Handle payment status change and set suitable order status."""- order = instance.order- if order.is_fully_paid():- order.events.create(type=OrderEvents.ORDER_FULLY_PAID.value)- if order.get_user_current_email():- send_payment_confirmation.delay(order.pk)- order.events.create(- type=OrderEvents.EMAIL_SENT.value,- parameters={- 'email': order.get_user_current_email(),- 'email_type': OrderEventsEmails.PAYMENT.value})- try:- analytics.report_order(order.tracking_client_id, order)- except Exception:- # Analytics failing should not abort the checkout flow- logger.exception('Recording order in analytics failed')diff --git a/saleor/payment/forms.py b/saleor/payment/forms.pyindex be5862bbb3..93a1786098 100644--- a/saleor/payment/forms.py+++ b/saleor/payment/forms.py@@ -11,5 +11,6 @@ class PaymentMethodForm(forms.ModelForm):def authorize_payment(self):self.instance.transactions.create(- amount=self.instance.total, transaction_type=TransactionType.AUTH,+ amount=self.instance.total.gross,+ transaction_type=TransactionType.AUTH,gateway_response={}, is_success=True)diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex cb4a0874f3..717368a343 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -1,3 +1,4 @@+import loggingfrom decimal import Decimalfrom functools import wrapsfrom typing import Dict, Optional@@ -7,8 +8,29 @@ from django.db import transactionfrom prices import Moneyfrom . import ChargeStatus, PaymentError, can_be_voided, get_provider+from ..core import analytics+from ..order import OrderEvents, OrderEventsEmails+from ..order.emails import send_payment_confirmationfrom .models import PaymentMethod, Transaction+logger = logging.getLogger(__name__)+++def handle_fully_paid_order(order):+ order.events.create(type=OrderEvents.ORDER_FULLY_PAID.value)+ if order.get_user_current_email():+ send_payment_confirmation.delay(order.pk)+ order.events.create(+ type=OrderEvents.EMAIL_SENT.value,+ parameters={+ 'email': order.get_user_current_email(),+ 'email_type': OrderEventsEmails.PAYMENT.value})+ try:+ analytics.report_order(order.tracking_client_id, order)+ except Exception:+ # Analytics failing should not abort the checkout flow+ logger.exception('Recording order in analytics failed')+def validate_payment_method(view):"""Decorate a view to check if payment method is active, so any actions@@ -92,7 +114,9 @@ def gateway_capture(payment_method.captured_amount += txn.amountpayment_method.save(update_fields=['charge_status', 'captured_amount'])-+ order = payment_method.order+ if order and order.is_fully_paid():+ handle_fully_paid_order(order)if not txn.is_success:# TODO: Handle gateway response here somehowraise PaymentError(error)diff --git a/saleor/settings.py b/saleor/settings.pyindex dd48ab0856..bfd807617b 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -207,7 +207,7 @@ INSTALLED_APPS = ['saleor.core','saleor.graphql','saleor.menu',- 'saleor.order.OrderAppConfig',+ 'saleor.order','saleor.dashboard','saleor.seo','saleor.shipping',diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.pyindex 0a70680e9c..75ea124202 100644--- a/tests/api/test_checkout.py+++ b/tests/api/test_checkout.py@@ -388,6 +388,7 @@ def test_checkout_complete(total = checkout.get_total()payment_method = payment_method_dummypayment_method.is_active = True+ payment_method.order = Nonepayment_method.total = totalpayment_method.captured_amount = total.grosspayment_method.checkout = checkout@@ -421,7 +422,7 @@ def test_checkout_complete(assert not data['errors']order_token = data['order']['token']assert Order.objects.count() == orders_count + 1- order = Order.objects.last()+ order = Order.objects.first()assert order.token == order_tokenassert order.total.gross == total.grosscheckout_line = checkout.lines.first()diff --git a/tests/test_order.py b/tests/test_order.pyindex ae20333ae0..87353e8eb9 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -467,7 +467,7 @@ def test_order_payment_flow(# Assert that payment object was created and contains correct datapayment = order.payment_methods.all()[0]- assert payment.total == order.total.gross+ assert payment.total == order.totalassert payment.transactions.count() == 1assert payment.transactions.first().transaction_type == 'auth'