Skip to content

Saleor Core: the high performance, composable, headless commerce API.

WIP

Pacu2ce8493175f58
diff --git a/saleor/order/views.py b/saleor/order/views.py
index 88da4f67c2..3dff8aa73e 100644
--- a/saleor/order/views.py
+++ b/saleor/order/views.py
@@ -26,6 +26,8 @@ from .utils import attach_order_to_user, check_order_status
logger = logging.getLogger(__name__)
+PAYMENT_TEMPLATE = 'order/payment/%s.html'
+
def details(request, token):
note_form = None
@@ -103,7 +105,9 @@ def start_payment(request, order, gateway):
payment_gateway, gateway_params = get_payment_gateway(payment.gateway)
client_token = payment_gateway.get_client_token(**gateway_params)
form = get_form_for_payment(payment)
- form = form(data=request.POST or None, instance=payment)
+ form = form(
+ data=request.POST or None, payment=payment,
+ gateway=payment_gateway, gateway_params=gateway_params)
if form.is_valid():
try:
form.process_payment()
@@ -111,7 +115,7 @@ def start_payment(request, order, gateway):
form.add_error(None, exc.message)
else:
return redirect(order.get_absolute_url())
- template = 'order/payment/%s.html' % gateway
+ template = PAYMENT_TEMPLATE % gateway
ctx = {
'form': form, 'payment': payment,
'client_token': client_token, 'order': order}
diff --git a/saleor/payment/forms.py b/saleor/payment/forms.py
index 34a38a1428..af0d3c517b 100644
--- a/saleor/payment/forms.py
+++ b/saleor/payment/forms.py
@@ -3,7 +3,7 @@ from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import pgettext_lazy
-from . import ChargeStatus, Transactions, get_payment_gateway
+from . import ChargeStatus, PaymentError, Transactions, get_payment_gateway
from .models import Payment
from .utils import gateway_authorize, gateway_capture, gateway_refund
@@ -13,35 +13,44 @@ def get_form_for_payment(payment):
return DummyPaymentForm
elif payment.gateway == settings.BRAINTREE:
return BraintreePaymentForm
- raise ValueError('Unknown payment gateway')
+ raise NotImplementedError('Unknown payment gateway')
-class DummyPaymentForm(forms.Form):
+class PaymentForm(forms.Form):
+ """FIXME: DOCS & DOCSTRINGS."""
+
+ def __init__(self, payment, gateway, gateway_params, *args, **kwargs):
+ self.payment = payment
+ self.gateway = gateway
+ self.gateway_params = gateway_params
+ super().__init__(*args, **kwargs)
+
+ def process_payment(self):
+ raise NotImplementedError()
+
+
+class DummyPaymentForm(PaymentForm):
charge_status = forms.ChoiceField(
label=pgettext_lazy('Payment status form field', 'Payment status'),
choices=ChargeStatus.CHOICES, initial=ChargeStatus.NOT_CHARGED,
widget=forms.RadioSelect)
- def __init__(self, instance, *args, **kwargs):
- self.instance = instance
- super().__init__(*args, **kwargs)
def process_payment(self):
# FIXME add tests
- gateway, gateway_params = get_payment_gateway(self.instance.gateway)
- # Dummy provider requires no token
- fake_token = gateway.get_client_token(**gateway_params)
- self.instance.authorize(fake_token)
+ # Dummy provider requires no real token
+ fake_token = self.gateway.get_client_token(**self.gateway_params)
+ self.payment.authorize(fake_token)
charge_status = self.cleaned_data['charge_status']
if charge_status == ChargeStatus.NOT_CHARGED:
return
- self.instance.capture()
+ self.payment.capture()
if charge_status == ChargeStatus.FULLY_REFUNDED:
- self.instance.refund()
- return self.instance
+ self.payment.refund()
+ return self.payment
-class BraintreePaymentForm(forms.Form):
+class BraintreePaymentForm(PaymentForm):
amount = forms.DecimalField()
# Unique transaction identifier returned by Braintree
@@ -51,10 +60,9 @@ class BraintreePaymentForm(forms.Form):
# response
payment_method_nonce = forms.CharField()
- def __init__(self, instance, *args, **kwargs):
- self.instance = instance
+ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- self.fields['amount'].initial = self.instance.total
+ self.fields['amount'].initial = self.payment.total
# FIXME if environment is Sandbox, we could provide couple of predefined
# nounces for easier testing
@@ -65,7 +73,7 @@ class BraintreePaymentForm(forms.Form):
# when manually adjusting the template value as we do not allow
# partial-payments at this moment, error is returned instead.
amount = cleaned_data.get('amount')
- if amount and amount != self.instance.total:
+ if amount and amount != self.payment.total:
msg = pgettext_lazy(
'payment error',
'Unable to process transaction. Please try again in a moment')
@@ -76,14 +84,14 @@ class BraintreePaymentForm(forms.Form):
def process_payment(self):
# FIXME add tests
payment_token = self.cleaned_data['payment_method_nonce']
- self.instance.token = payment_token
- self.instance.save(updated_fields=['token'])
+ self.payment.token = payment_token
+ self.payment.save(updated_fields=['token'])
- self.instance.authorize(payment_token)
+ self.payment.authorize(payment_token)
try:
- self.instance.capture(self.instance.total)
+ self.payment.capture(self.payment.total)
except PaymentError as exc:
# Void authorization if the capture failed
- self.instance.void()
+ self.payment.void()
raise exc
- return self.instance
+ return self.payment
diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.py
index 8e80ccd02d..5adbfa13e2 100644
--- a/saleor/payment/gateways/braintree/__init__.py
+++ b/saleor/payment/gateways/braintree/__init__.py
@@ -72,12 +72,12 @@ def get_error_for_client(errors: List) -> str:
def transaction_and_incorrect_token_error(
payment: Payment,
token: str,
- type: Transactions,
+ kind: Transactions,
amount: Decimal = None) -> Tuple[Transaction, str]:
amount = amount or payment.total
txn = create_transaction(
payment=payment,
- kind=type,
+ kind=kind,
currency=payment.currency,
amount=amount,
gateway_response={},
@@ -150,7 +150,7 @@ def authorize(
**get_customer_data(payment)})
except braintree_sdk.exceptions.NotFoundError:
return transaction_and_incorrect_token_error(
- payment, type=Transactions.AUTH, token=payment_token)
+ payment, kind=Transactions.AUTH, token=payment_token)
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response['errors'])
credit_card_data = gateway_response.pop('credit_cart')
@@ -188,7 +188,7 @@ def capture(
except braintree_sdk.exceptions.NotFoundError:
return transaction_and_incorrect_token_error(
payment,
- type=Transactions.CAPTURE,
+ kind=Transactions.CAPTURE,
token=auth_transaction.token,
amount=amount)
@@ -218,7 +218,7 @@ def void(
transaction_id=auth_transaction.token)
except braintree_sdk.exceptions.NotFoundError:
return transaction_and_incorrect_token_error(
- payment, type=Transactions.VOID, token=auth_transaction.token)
+ payment, kind=Transactions.VOID, token=auth_transaction.token)
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response['errors'])
@@ -247,7 +247,7 @@ def refund(
amount_or_options=str(amount))
except braintree_sdk.exceptions.NotFoundError:
return transaction_and_incorrect_token_error(
- payment, type=Transactions.REFUND, token=capture_txn.token,
+ payment, kind=Transactions.REFUND, token=capture_txn.token,
amount=amount)
gateway_response = extract_gateway_response(result)
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 76335399a5..53255cd1e1 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -163,9 +163,10 @@ class Transaction(models.Model):
error = models.CharField(
choices=[(tag, tag.value) for tag in TransactionError],
max_length=256, null=True)
+ # Parent transaction, from which the transaction_id was used
parent = models.ForeignKey(
- 'payment.Transaction', related_name='+', on_delete=models.PROTECT,
- blank=True, null=True)
+ 'payment.Transaction', related_name='children',
+ on_delete=models.PROTECT, blank=True, null=True)
gateway_response = JSONField()
def __repr__(self):
diff --git a/tests/gateway/test_braintree.py b/tests/gateway/test_braintree.py
index af2eeab7ab..52ca6fdac4 100644
--- a/tests/gateway/test_braintree.py
+++ b/tests/gateway/test_braintree.py
@@ -232,7 +232,7 @@ def test_authorize_incorrect_token(
result = authorize(payment, payment_token)
assert result == expected_result
mock_transaction.assert_called_once_with(
- payment, type=Transactions.AUTH, token=token)
+ payment, type=Transactions.AUTH, token=payment_token)
@pytest.mark.integration
diff --git a/tests/test_payment.py b/tests/test_payment.py
index edc69a0f18..876fb56c6f 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -2,16 +2,18 @@ from decimal import Decimal
from unittest.mock import Mock, patch
import pytest
+from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from prices import Money
from saleor.order import OrderEvents, OrderEventsEmails
+from saleor.order.views import PAYMENT_TEMPLATE
from saleor.payment import (
ChargeStatus, PaymentError, Transactions, get_payment_gateway)
from saleor.payment.utils import (
create_payment, create_transaction, gateway_authorize, gateway_capture,
- gateway_get_client_token, gateway_refund, gateway_void,
- get_billing_data, handle_fully_paid_order, validate_payment)
+ gateway_get_client_token, gateway_refund, gateway_void, get_billing_data,
+ handle_fully_paid_order, validate_payment)
NOT_ACTIVE_PAYMENT_ERROR = 'This payment is no longer active.'
EXAMPLE_ERROR = 'Example dummy error'
@@ -427,10 +429,13 @@ def test_gateway_refund_errors(payment_txn_captured):
payment.charge_status = ChargeStatus.NOT_CHARGED
with pytest.raises(PaymentError) as exc:
gateway_refund(payment, Decimal('1'))
- assert exc.value.message == 'This payment cannot be captured.'
+ assert exc.value.message == 'This payment cannot be refunded.'
-def test_payment_provider_templates_exists(payment_dummy):
- # FIXME test if for each payment provider there's corresponding
- # module and template for the old checkout
- pass
[email protected]('gateway_name', settings.PAYMENT_GATEWAYS.keys())
+def test_payment_provider_templates_exists(gateway_name):
+ """Test if for each payment provider there's a corresponding
+ template for the old checkout.
+ """
+ template = PAYMENT_TEMPLATE % gateway_name
+ django.template.loader.get_template(template)