Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
WIP
Pacu2f46d645f137f
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex a73afabaf6..8b6e8b26b3 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -887,7 +887,7 @@ def create_order(cart, tracking_code, discounts, taxes):def is_fully_paid(cart: Cart):payment_methods = cart.payment_methods.all()- total_paid = sum([p.total for p in payment_methods])+ total_paid = sum([p.get_captured_money() for p in payment_methods])return total_paid == cart.get_total().gross.amountdiff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex d36025c16d..f01a2df093 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -4,7 +4,6 @@ from django.core.validators import MinValueValidatorfrom django.urls import reverse, reverse_lazyfrom django.utils.translation import npgettext_lazy, pgettext_lazyfrom django_prices.forms import MoneyField-from payments import PaymentErrorfrom ...account.i18n import (AddressForm as StorefrontAddressForm, PossiblePhoneNumberFormField)@@ -19,7 +18,7 @@ from ...order.models import Fulfillment, FulfillmentLine, Order, OrderLinefrom ...order.utils import (add_variant_to_order, cancel_fulfillment, cancel_order,change_order_line_quantity, recalculate_order)-from ...payment import PaymentMethodChargeStatus+from ...payment import PaymentMethodChargeStatus, PaymentErrorfrom ...payment.models import PaymentMethodfrom ...product.models import Product, ProductVariantfrom ...product.utils import allocate_stock, deallocate_stockdiff --git a/saleor/order/forms.py b/saleor/order/forms.pyindex 6841e4c70a..2699a43c9b 100644--- a/saleor/order/forms.py+++ b/saleor/order/forms.py@@ -1,10 +1,11 @@from django import formsfrom django.conf import settingsfrom django.utils.translation import pgettext_lazy-from payments import PaymentStatusfrom ..account.forms import SignupForm-from .models import Order, Payment+from ..payment import PaymentMethodChargeStatus, can_be_voided+from ..payment.models import PaymentMethod+from .models import Orderclass PaymentMethodsForm(forms.Form):@@ -24,23 +25,24 @@ class PaymentDeleteForm(forms.Form):def clean(self):cleaned_data = super().clean()payment_id = cleaned_data.get('payment_id')- waiting_payments = self.order.payments.filter(- status=PaymentStatus.WAITING)- try:- payment = waiting_payments.get(id=payment_id)- except Payment.DoesNotExist:+ payment = PaymentMethod.objects.filter(is_active=True).first(+ id=payment_id)+ if not payment:+ self._errors['number'] = self.error_class([+ pgettext_lazy(+ 'Payment delete form error', 'Payment does not exist')])+ elif not can_be_voided(payment):self._errors['number'] = self.error_class([pgettext_lazy('Payment delete form error',- 'Payment does not exist')])+ 'Payment cannot be cancelled.')])else:cleaned_data['payment'] = paymentreturn cleaned_datadef save(self):payment = self.cleaned_data['payment']- payment.status = PaymentStatus.REJECTED- payment.save()+ payment.void()class PasswordForm(SignupForm):diff --git a/saleor/order/models.py b/saleor/order/models.pyindex fe12c30da1..ec515d8d03 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -163,14 +163,14 @@ class Order(models.Model):def get_last_payment_status(self):last_payment = self.get_last_payment()if last_payment:- return last_payment.status+ return last_payment.charge_statusreturn Nonedef get_last_payment_status_display(self):last_payment = max(- self.payments.all(), default=None, key=attrgetter('pk'))+ self.payment_methods.all(), default=None, key=attrgetter('pk'))if last_payment:- return last_payment.get_status_display()+ return last_payment.get_charge_status_display()return Nonedef is_pre_authorized(self):diff --git a/saleor/order/views.py b/saleor/order/views.pyindex 1d886fc015..240c811569 100644--- a/saleor/order/views.py+++ b/saleor/order/views.py@@ -10,7 +10,6 @@ from django.template.response import TemplateResponsefrom django.urls import reversefrom django.utils.translation import pgettext_lazyfrom django.views.decorators.csrf import csrf_exempt-from payments import PaymentStatusfrom . import FulfillmentStatusfrom ..account.forms import LoginForm@@ -18,6 +17,7 @@ from ..account.models import Userfrom ..core.utils import get_client_ipfrom ..payment.forms import PaymentMethodFormfrom ..payment.models import PaymentMethod+from ..payment import PaymentMethodChargeStatusfrom .forms import (CustomerNoteForm, PasswordForm, PaymentDeleteForm, PaymentMethodsForm)from .models import Order, Payment@@ -57,7 +57,9 @@ def payment(request, token):payments = order.payments.all()form_data = request.POST or Nonetry:- waiting_payment = order.payments.get(status=PaymentStatus.WAITING)+ waiting_payment = order.payments.filter(+ is_active=True,+ charge_status=PaymentMethodChargeStatus.NOT_CHARGED)except Payment.DoesNotExist:waiting_payment = Nonewaiting_payment_form = Nonediff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex e2e94051ad..ce3056cf0d 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -45,7 +45,6 @@ class PaymentMethodChargeStatus:FULLY_REFUNDED = 'fully-refunded'# FIXME# We should probably support other statuses, like:- # pending# partially charged# partially refunded@@ -72,3 +71,7 @@ def get_provider(provider_name):provider_params = settings.PAYMENT_PROVIDERS[provider_name]['connection_params']return provider_module, provider_params+++def can_be_voided(payment):+ return payment.charge_status == PaymentMethodChargeStatus.NOT_CHARGEDdiff --git a/saleor/payment/providers/braintree/__init__.py b/saleor/payment/providers/braintree/__init__.pyindex 3c7068f09a..1ee895e0a5 100644--- a/saleor/payment/providers/braintree/__init__.py+++ b/saleor/payment/providers/braintree/__init__.py@@ -1,6 +1,7 @@from typing import Dictimport braintree as braintree_sdk+from django.core.exceptions import ImproperlyConfiguredfrom django.utils.translation import pgettext_lazyfrom ... import TransactionType@@ -54,6 +55,17 @@ def extract_gateway_response(braintree_result) -> Dict:def get_gateway(sandbox_mode, merchant_id, public_key, private_key):+ if not all([merchant_id, private_key, public_key]):+ missing = []+ if not merchant_id:+ missing.append('Merchant ID')+ if not public_key:+ missing.append('Public Key')+ if not private_key:+ missing.append('Private Key')+ raise ImproperlyConfigured(+ 'Incorrectly configured Braintree gateway.'+ ' Missing: %s' % ', '.join(missing))environment = braintree_sdk.Environment.Sandboxif not sandbox_mode:environment = braintree_sdk.Environment.Productiondiff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex d6df5760bb..6a4a741350 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -4,7 +4,8 @@ from typing import Dict, Optionalfrom django.db import transaction-from . import PaymentError, PaymentMethodChargeStatus, get_provider+from . import (+ PaymentError, PaymentMethodChargeStatus, can_be_voided, get_provider)from .models import PaymentMethod, Transaction@@ -92,7 +93,7 @@ def gateway_capture(payment_method, amount) -> Transaction:@validate_payment_methoddef gateway_void(payment_method) -> Transaction:- if not payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED:+ if not can_be_voided(payment_method):raise PaymentError('Only pre-authorized transactions can be void.')provider, provider_params = get_provider(payment_method.variant)with transaction.atomic():diff --git a/saleor/settings.py b/saleor/settings.pyindex 636f6a18a2..dd48ab0856 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -563,5 +563,4 @@ PAYMENT_PROVIDERS = {'private_key': os.environ.get('BRAINTREE_PRIVATE_KEY')}}-}diff --git a/templates/dashboard/order/detail.html b/templates/dashboard/order/detail.htmlindex 435275dac1..084528d8a7 100644--- a/templates/dashboard/order/detail.html+++ b/templates/dashboard/order/detail.html@@ -579,9 +579,6 @@<th>{% trans "Payment status" context "Payment history table header" %}</th>- <th>- {% trans "Fraud status" context "Payment history table header" %}- </th><th>{% trans "Amount" context "Payment history table header" %}</th>@@ -599,14 +596,7 @@{{ payment.created }}</td><td>- {% render_status payment.charget_status payment.get_charge_status_display %}- </td>- <td>- {% if payment.fraud_status %}- {% render_status payment.fraud_status payment.get_fraud_status_display %}- {% else %}- -- {% endif %}+ {% render_status payment.charge_status payment.get_charge_status_display %}</td><td>{{ payment.total|currencyfmt:payment.currency }}diff --git a/tests/test_order.py b/tests/test_order.pyindex 98c88c1060..93fbef3a20 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -1,12 +1,10 @@from decimal import Decimalimport pytest+from django.urls import reversefrom django_countries.fields import Country-from payments import FraudStatus, PaymentStatusfrom prices import Money, TaxedMoney-from tests.utils import get_redirect_location-from saleor.account.models import Userfrom saleor.checkout.utils import create_orderfrom saleor.core.exceptions import InsufficientStock@@ -18,6 +16,8 @@ from saleor.order.utils import (add_variant_to_order, cancel_fulfillment, cancel_order, recalculate_order,restock_fulfillment_lines, restock_order_lines, update_order_prices,update_order_status)+from saleor.payment import PaymentMethodChargeStatus+from tests.utils import get_redirect_locationdef test_total_setter():@@ -367,8 +367,8 @@ def test_order_queryset_to_ship():]for order in orders_to_ship:order.payments.create(- variant='default', status=PaymentStatus.CONFIRMED, currency='USD',- total=order.total_gross.amount,+ variant='default', status=PaymentMethodChargeStatus.CHARGED,+ currency='USD', total=order.total_gross.amount,captured_amount=order.total_gross.amount)orders_not_to_ship = [@@ -454,12 +454,6 @@ def test_order_payment_flow(assert response.request['PATH_INFO'] == redirect_url# Go to payment details page, enter payment data- data = {- 'status': PaymentStatus.PREAUTH,- 'fraud_status': FraudStatus.UNKNOWN,- 'gateway_response': '3ds-disabled',- 'verification_result': 'waiting'}-data = {'variant': 'dummy','is_active': True,@@ -481,6 +475,7 @@ def test_order_payment_flow(assert payment.transactions.count() == 1assert payment.transactions.first().transaction_type == 'auth'+def test_create_user_after_order(order, client):order.user_email = '[email protected]'order.save()