Skip to content

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

Transfrom Payment's and Transaction's MoneyFields into immutable Decimal fields

Pacu2c62998843b3f
diff --git a/docs/guides/payments.rst b/docs/guides/payments.rst
index dc3b481f1b..27d5708650 100644
--- a/docs/guides/payments.rst
+++ b/docs/guides/payments.rst
@@ -4,7 +4,7 @@ Payments
========
Integrating a new Payment Gateway into Saleor
--------------------------------------------
+---------------------------------------------
We are using a universal flow, that each provider should fulfill, there are
several methods that should be implemented.
@@ -33,8 +33,8 @@ Example
.. code-block:: python
def get_transaction_token(**connection_params: Dict) -> str:
- gateway - get_gateway(**connection_params)
- transaction_token - gateway.transaction_token.generate()
+ gateway = get_gateway(**connection_params)
+ transaction_token = gateway.transaction_token.generate()
return transaction_token
authorize(payment, transaction_token, **connection_params)
@@ -54,15 +54,16 @@ Example
**connection_params: Dict) -> Tuple[Transaction, str]:
# Handle connecting to the gateway and sending the auth request here
- response - gateway.auth(token-transaction_token)
-
- txn - Transaction.objects.create(
- payment-payment,
- transaction_type-TransactionType.AUTH,
- amount-payment.total.amount,
- gateway_response-get_gateway_response(response),
- token-response.transaction.id,
- is_success-response.is_success)
+ response = gateway.auth(token=transaction_token)
+
+ txn = Transaction.objects.create(
+ payment=payment,
+ transaction_type=TransactionType.AUTH,
+ amount=payment.total,
+ currency=payment.currency,
+ gateway_response=get_gateway_response(response),
+ token=response.transaction.id,
+ is_success=response.is_success)
return txn, response['error']
@@ -82,20 +83,21 @@ Example
**connection_params: Dict) -> Tuple[Transaction, str]:
# Please note that token from the last AUTH transaction should be used
- capture_txn - payment.transactions.filter(
- transaction_type-TransactionType.CAPTURE).first()
- transaction_token - capture_txn.token
+ capture_txn = payment.transactions.filter(
+ transaction_type=TransactionType.CAPTURE).first()
+ transaction_token = capture_txn.token
# Handle connecting to the gateway and sending the refund request here
- response - gateway.refund(token-transaction_token)
-
- txn - create_transaction(
- payment-payment,
- transaction_type-TransactionType.REFUND,
- amount-amount,
- token-response.transaction.id,
- is_success-response.is_success,
- gateway_response-get_gateway_response(response))
+ response = gateway.refund(token=transaction_token)
+
+ txn = create_transaction(
+ payment=payment,
+ transaction_type=TransactionType.REFUND,
+ amount=amount,
+ currency=payment.currency,
+ token=response.transaction.id,
+ is_success=response.is_success,
+ gateway_response=get_gateway_response(response))
return txn, response['error']
capture(payment, amount, **connection_params)
@@ -114,20 +116,21 @@ Example
**connection_params: Dict) -> Tuple[Transaction, str]:
# Please note that token from the last AUTH transaction should be used
- auth_transaction - payment.transactions.filter(
- transaction_type-TransactionType.AUTH).first()
- transaction_token - auth_transaction.token
+ auth_transaction = payment.transactions.filter(
+ transaction_type=TransactionType.AUTH).first()
+ transaction_token = auth_transaction.token
# Handle connecting to the gateway and sending the capture request here
- response - gateway.capture(token-transaction_token)
-
- txn - create_transaction(
- payment-payment,
- transaction_type-TransactionType.CAPTURE,
- amount-amount,
- token-response.transaction.id,
- is_success-response.is_success,
- gateway_response-get_gateway_response(response))
+ response = gateway.capture(token=transaction_token)
+
+ txn = create_transaction(
+ payment=payment,
+ transaction_type=TransactionType.CAPTURE,
+ amount=amount,
+ currency=payment.currency,
+ token=response.transaction.id,
+ is_success=response.is_success,
+ gateway_response=get_gateway_response(response))
return txn, response['error']
void(payment, **connection_params)
@@ -145,20 +148,21 @@ Example
**connection_params: Dict) -> Tuple[Transaction, str]:
# Please note that token from the last AUTH transaction should be used
- auth_transaction - payment.transactions.filter(
- transaction_type-TransactionType.AUTH).first()
- transaction_token - auth_transaction.token
+ auth_transaction = payment.transactions.filter(
+ transaction_type=TransactionType.AUTH).first()
+ transaction_token = auth_transaction.token
# Handle connecting to the gateway and sending the void request here
- response - gateway.void(token-transaction_token)
-
- txn - create_transaction(
- payment-payment,
- transaction_type-TransactionType.VOID,
- amount-payment.total.amount,
- gateway_response-get_gateway_response(response),
- token-response.transaction.id,
- is_success-response.is_success)
+ response = gateway.void(token=transaction_token)
+
+ txn = create_transaction(
+ payment=payment,
+ transaction_type=TransactionType.VOID,
+ amount=payment.total,
+ currency=payment.currency,
+ gateway_response=get_gateway_response(response),
+ token=response.transaction.id,
+ is_success=response.is_success)
return txn, response['error']
Parameters
@@ -192,7 +196,7 @@ Adding new payment provider in the settings
.. code-block:: python
- PAYMENT_PROVIDERS - {
+ PAYMENT_PROVIDERS = {
'braintree': {
'module': 'saleor.payment.providers.braintree',
'connection_params': {
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index def1ca1df2..245e2b2419 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -888,7 +888,7 @@ def create_order(cart, tracking_code, discounts, taxes):
def is_fully_paid(cart: Cart):
payments = cart.payments.filter(is_active=True)
total_paid = sum(
- [p.total.amount for p in payments])
+ [p.total for p in payments])
return total_paid >= cart.get_total().gross.amount
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 4e961ae08c..e2fe2904c9 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -28,17 +28,8 @@ from ...order.models import Fulfillment, Order
from ...order.utils import update_order_status
from ...page.models import Page
from ...payment import ChargeStatus, TransactionType
-<<<<<<< HEAD
-<<<<<<< HEAD
-from ...payment.models import PaymentMethod
-=======
-from ...payment.utils import get_billing_data
-from ...payment.models import Payment
->>>>>>> Rename PaymentMethod to Payment
-=======
from ...payment.models import Payment
from ...payment.utils import get_billing_data
->>>>>>> Add documentation on adding new payment gateway, fix style and inconsistencies in naming
from ...product.models import (
Attribute, AttributeValue, Category, Collection, Product, ProductImage,
ProductType, ProductVariant)
@@ -423,12 +414,27 @@ def create_payment(order):
customer_ip_address=fake.ipv4(),
is_active=True,
order=order,
- total=order.total.gross,
+ total=order.total.gross.amount,
+ currency=order.total.gross.currency,
**get_billing_data(order))
- if status == ChargeStatus.CHARGED:
- payment.captured_amount = payment.total
- payment.save()
- create_transactions(payment)
+
+ provider, provider_params = get_provider(payment.variant)
+ transaction_token = provider.get_transaction_token(**provider_params)
+
+ # Create authorization transaction
+ gateway_authorize(payment, transaction_token, **provider_params)
+ # 20% chance to void the transaction at this stage
+ if random.choice([0, 0, 0, 0, 1]):
+ gateway_void(payment, **provider_params)
+ return payment
+ # 25% to end the payment at the authorization stage
+ if not random.choice([1, 1, 1, 0]):
+ return payment
+ # Create capture transaction
+ gateway_capture(payment, payment.total, **provider_params)
+ # 25% to refund the payment
+ if random.choice([0, 0, 0, 1]):
+ gateway_refund(payment, payment.total, **provider_params)
return payment
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 78bb2e8093..bdbaa52181 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -252,12 +252,11 @@ class OrderNoteForm(forms.Form):
class ManagePaymentForm(forms.Form):
- amount = MoneyField(
+ amount = forms.DecimalField(
label=pgettext_lazy(
'Payment management form (capture, refund, void)', 'Amount'),
max_digits=settings.DEFAULT_MAX_DIGITS,
- decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- currency=settings.DEFAULT_CURRENCY)
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES)
def __init__(self, *args, **kwargs):
self.payment = kwargs.pop('payment')
@@ -273,9 +272,9 @@ class ManagePaymentForm(forms.Form):
'Payment form error', 'Payment gateway error: %s') % message)
def try_payment_action(self, action):
- money = self.cleaned_data['amount']
+ amount = self.cleaned_data['amount']
try:
- action(money.amount)
+ action(amount)
except (PaymentError, ValueError) as e:
self.payment_error(str(e))
return False
@@ -355,8 +354,9 @@ class OrderMarkAsPaidForm(forms.Form):
def save(self):
# FIXME add more fields to the payment method
defaults = {
- 'total': self.order.total.gross,
- 'captured_amount': self.order.total.gross,
+ 'total': self.order.total.gross.amount,
+ 'captured_amount': self.order.total.gross.amount,
+ 'currency': self.order.total.gross.currency,
**get_billing_data(self.order)}
Payment.objects.get_or_create(
variant=CustomPaymentChoices.MANUAL,
diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.py
index 7fd186db51..9caf8b229a 100644
--- a/saleor/dashboard/order/views.py
+++ b/saleor/dashboard/order/views.py
@@ -158,11 +158,11 @@ def capture_payment(request, order_pk, payment_pk):
orders = Order.objects.confirmed().prefetch_related('payments')
order = get_object_or_404(orders, pk=order_pk)
payment = get_object_or_404(order.payments, pk=payment_pk)
- amount = order.total.quantize('0.01').gross
+ amount = order.total.gross
form = CapturePaymentForm(
- request.POST or None, payment=payment, initial={'amount': amount})
+ request.POST or None, payment=payment,
+ initial={'amount': amount.amount})
if form.is_valid() and form.capture():
- amount = form.cleaned_data['amount']
msg = pgettext_lazy(
'Dashboard message related to a payment',
'Captured %(amount)s') % {'amount': prices_i18n.amount(amount)}
@@ -174,7 +174,7 @@ def capture_payment(request, order_pk, payment_pk):
return redirect('dashboard:order-details', order_pk=order.pk)
status = 400 if form.errors else 200
ctx = {
- 'captured': payment.captured_amount,
+ 'captured': amount,
'form': form,
'order': order,
'payment': payment}
@@ -195,7 +195,8 @@ def refund_payment(request, order_pk, payment_pk):
amount = form.cleaned_data['amount']
msg = pgettext_lazy(
'Dashboard message related to a payment',
- 'Refunded %(amount)s') % {'amount': prices_i18n.amount(amount)}
+ 'Refunded %(amount)s') % {
+ 'amount': prices_i18n.amount(payment.get_captured_amount())}
order.events.create(
parameters={'amount': amount},
user=request.user,
@@ -204,7 +205,7 @@ def refund_payment(request, order_pk, payment_pk):
return redirect('dashboard:order-details', order_pk=order.pk)
status = 400 if form.errors else 200
ctx = {
- 'captured': payment.captured_amount,
+ 'captured': payment.get_captured_amount(),
'form': form,
'order': order,
'payment': payment}
@@ -228,8 +229,7 @@ def void_payment(request, order_pk, payment_pk):
return redirect('dashboard:order-details', order_pk=order.pk)
status = 400 if form.errors else 200
ctx = {
- 'captured': payment.captured_amount, 'form': form, 'order': order,
- 'payment': payment}
+ 'form': form, 'order': order, 'payment': payment}
return TemplateResponse(request, 'dashboard/order/modal/void.html', ctx,
status=status)
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index d68f49c8ee..4433ffe24d 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -438,7 +438,7 @@ class CheckoutComplete(BaseMutation):
return CheckoutComplete(order=order, errors=errors)
# capture payment
try:
- gateway_capture(payment, payment.total.amount)
+ gateway_capture(payment, payment.total)
except PaymentError as exc:
msg = str(exc)
cls.add_error(field=None, message=msg, errors=errors)
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index a856e0fd69..2f21cf4c8c 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -42,9 +42,9 @@ def clean_order_update_shipping(order, method, errors):
return errors
-def try_payment_action(action, money, errors):
+def try_payment_action(action, amount, errors):
try:
- action(money)
+ action(amount)
except (PaymentError, ValueError) as e:
errors.append(Error(field='payment', message=str(e)))
@@ -292,7 +292,9 @@ class OrderMarkAsPaid(BaseMutation):
return OrderMarkAsPaid(errors=errors)
# FIXME add more fields to the payment method
defaults = {
- 'total': order.total.gross, 'captured_amount': order.total.gross,
+ 'total': order.total.gross.amount,
+ 'captured_amount': order.total.gross.amount,
+ 'currency': order.total.gross.currency,
**get_billing_data(order)}
Payment.objects.get_or_create(
variant=CustomPaymentChoices.MANUAL,
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 0c010dbd2b..a2161060b1 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -134,8 +134,8 @@ class OrderLine(CountableDjangoObjectType):
return info.context.build_absolute_uri(url)
@staticmethod
- def resolve_unit_price(obj, info):
- return obj.unit_price
+ def resolve_unit_price(self, info):
+ return self.unit_price
class OrderAction(graphene.Enum):
@@ -218,98 +218,94 @@ class Order(CountableDjangoObjectType):
'total_net']
@staticmethod
- def resolve_shipping_price(obj, info):
- return obj.shipping_price
+ def resolve_shipping_price(self, info):
+ return self.shipping_price
- def resolve_actions(obj, info):
+ def resolve_actions(self, info):
actions = []
- payment = obj.get_last_payment()
- if obj.can_capture(payment):
+ payment = self.get_last_payment()
+ if self.can_capture(payment):
actions.append(OrderAction.CAPTURE)
- if obj.can_mark_as_paid():
+ if self.can_mark_as_paid():
actions.append(OrderAction.MARK_AS_PAID)
- if obj.can_refund(payment):
+ if self.can_refund(payment):
actions.append(OrderAction.REFUND)
- if obj.can_void(payment):
+ if self.can_void(payment):
actions.append(OrderAction.VOID)
return actions
@staticmethod
- def resolve_subtotal(obj, info):
- return obj.get_subtotal()
+ def resolve_subtotal(self, info):
+ return self.get_subtotal()
@staticmethod
- def resolve_total(obj, info):
- return obj.total
+ def resolve_total(self, info):
+ return self.total
@staticmethod
@gql_optimizer.resolver_hints(prefetch_related='payments')
- def resolve_total_authorized(obj, info):
+ def resolve_total_authorized(self, info):
# FIXME adjust to multiple payments in the future
- payment = obj.get_last_payment()
- if payment:
- return payment.total
+ return self.total_authorized
@staticmethod
@gql_optimizer.resolver_hints(prefetch_related='payments')
- def resolve_total_captured(obj, info):
+ def resolve_total_captured(self, info):
# FIXME adjust to multiple payments in the future
- payment = obj.get_last_payment()
- if payment:
- return payment.captured_amount
+ return self.total_captured
@staticmethod
- def resolve_total_balance(obj, info):
- return obj.total_balance
+ def resolve_total_balance(self, info):
+ return self.total_balance
@staticmethod
- def resolve_fulfillments(obj, info):
- return obj.fulfillments.all()
+ def resolve_fulfillments(self, info):
+ return self.fulfillments.all()
@staticmethod
- def resolve_lines(obj, info):
- return obj.lines.all()
+ def resolve_lines(self, info):
+ return self.lines.all()
@staticmethod
- def resolve_events(obj, info):
- return obj.events.all()
+ def resolve_events(self, info):
+ return self.events.all()
@staticmethod
@gql_optimizer.resolver_hints(prefetch_related='payments')
- def resolve_is_paid(obj, info):
- return obj.is_fully_paid()
+ def resolve_is_paid(self, info):
+ return self.is_fully_paid()
@staticmethod
- def resolve_number(obj, info):
- return str(obj.pk)
+ def resolve_number(self, info):
+ return str(self.pk)
@staticmethod
@gql_optimizer.resolver_hints(prefetch_related='payments')
- def resolve_payment_status(obj, info):
- return obj.get_last_payment_status()
+ def resolve_payment_status(self, info):
+ return self.get_last_payment_status()
@staticmethod
@gql_optimizer.resolver_hints(prefetch_related='payments')
- def resolve_payment_status_display(obj, info):
- return obj.get_last_payment_status_display()
+ def resolve_payment_status_display(self, info):
+ return self.get_last_payment_status_display()
@staticmethod
- def resolve_status_display(obj, info):
- return obj.get_status_display()
+ def resolve_status_display(self, info):
+ return self.get_status_display()
@staticmethod
- def resolve_user_email(obj, info):
- if obj.user_email:
- return obj.user_email
- if obj.user_id:
- return obj.user.email
+ def resolve_user_email(self, info):
+ if self.user_email:
+ return self.user_email
+ if self.user_id:
+ return self.user.email
return None
@staticmethod
- def resolve_available_shipping_methods(obj, info):
+ def resolve_available_shipping_methods(self, info):
from .resolvers import resolve_shipping_methods
return resolve_shipping_methods(
- obj, info, obj.get_subtotal().gross.amount)
+ self, info, self.get_subtotal().gross.amount)
def resolve_is_shipping_required(self, info):
return self.is_shipping_required()
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index fc17e54835..f7f2ba488a 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -57,11 +57,11 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
return CheckoutPaymentCreate(errors=errors)
billing_data = cls.clean_billing_address(billing_address)
extra_data = cls.get_extra_info(info)
- gross = Money(input['amount'], currency=settings.DEFAULT_CURRENCY)
# FIXME as we allow only one payment make sure that amount
# is same as checkout's total
payment = create_payment(
- total=gross,
+ total=input['amount'],
+ currency=settings.DEFAULT_CURRENCY,
variant=input['gateway'],
billing_email=checkout.email,
is_active=True,
diff --git a/saleor/order/migrations/0065_auto_20181017_1346.py b/saleor/order/migrations/0065_auto_20181017_1346.py
index 5193e7be64..f8137bbb72 100644
--- a/saleor/order/migrations/0065_auto_20181017_1346.py
+++ b/saleor/order/migrations/0065_auto_20181017_1346.py
@@ -3,6 +3,8 @@
from django.db import migrations, models
import django_prices.models
import saleor.core
+from decimal import Decimal
+
class Migration(migrations.Migration):
@@ -39,4 +41,9 @@ class Migration(migrations.Migration):
name='type',
field=models.CharField(choices=[('PLACED', 'placed'), ('PLACED_FROM_DRAFT', 'draft_placed'), ('OVERSOLD_ITEMS', 'oversold_items'), ('ORDER_MARKED_AS_PAID', 'marked_as_paid'), ('CANCELED', 'canceled'), ('ORDER_FULLY_PAID', 'order_paid'), ('UPDATED', 'updated'), ('EMAIL_SENT', 'email_sent'), ('PAYMENT_CAPTURED', 'captured'), ('PAYMENT_REFUNDED', 'refunded'), ('PAYMENT_VOIDED', 'voided'), ('FULFILLMENT_CANCELED', 'fulfillment_canceled'), ('FULFILLMENT_RESTOCKED_ITEMS', 'restocked_items'), ('FULFILLMENT_FULFILLED_ITEMS', 'fulfilled_items'), ('TRACKING_UPDATED', 'tracking_updated'), ('NOTE_ADDED', 'note_added'), ('OTHER', 'other')], max_length=255),
),
+ migrations.AlterField(
+ model_name='orderline',
+ name='tax_rate',
+ field=models.DecimalField(decimal_places=2, default=Decimal('0.0'), max_digits=5),
+ ),
]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 294a833793..adc0299efc 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -1,3 +1,4 @@
+from decimal import Decimal
from operator import attrgetter
from uuid import uuid4
@@ -12,6 +13,7 @@ from django.utils.translation import pgettext_lazy
from django_measurement.models import MeasurementField
from django_prices.models import MoneyField, TaxedMoneyField
from measurement.measures import Weight
+from prices import Money
from . import (
CustomPaymentChoices, FulfillmentStatus, OrderEvents, OrderStatus,
@@ -140,7 +142,8 @@ class Order(models.Model):
def is_fully_paid(self):
payments = self.payments.filter(
charge_status=ChargeStatus.CHARGED)
- total_captured = [payment.captured_amount for payment in payments]
+ total_captured = [
+ payment.get_captured_amount() for payment in payments]
total_paid = sum(total_captured, ZERO_TAXED_MONEY)
return total_paid.gross >= self.total.gross
@@ -247,22 +250,22 @@ class Order(models.Model):
return len(self.payments.all()) == 0
@property
- def authorized_amount(self):
+ def total_authorized(self):
payment = self.get_last_payment()
if payment:
- return payment.total
+ return Money(payment.total, payment.currency)
return zero_money()
@property
- def captured_amount(self):
+ def total_captured(self):
payment = self.get_last_payment()
if payment and payment.charge_status == ChargeStatus.CHARGED:
- return payment.captured_amount
+ return Money(payment.captured_amount, payment.currency)
return zero_money()
@property
def total_balance(self):
- return self.captured_amount - self.total.gross
+ return self.total_captured - self.total.gross
def get_total_weight(self):
# Cannot use `sum` as it parses an empty Weight to an int
@@ -298,7 +301,7 @@ class OrderLine(models.Model):
unit_price = TaxedMoneyField(
net_field='unit_price_net', gross_field='unit_price_gross')
tax_rate = models.DecimalField(
- max_digits=5, decimal_places=2, default='0.0')
+ max_digits=5, decimal_places=2, default=Decimal('0.0'))
def __str__(self):
return self.product_name
diff --git a/saleor/order/views.py b/saleor/order/views.py
index 7189bf12fc..5b14c6df29 100644
--- a/saleor/order/views.py
+++ b/saleor/order/views.py
@@ -88,7 +88,6 @@ def payment(request, token):
@check_order_status
def start_payment(request, order, variant):
defaults = {
- 'total': order.total.gross,
'customer_ip_address': get_client_ip(request),
**get_billing_data(order)}
if variant not in settings.CHECKOUT_PAYMENT_CHOICES:
@@ -96,7 +95,7 @@ def start_payment(request, order, variant):
with transaction.atomic():
payment, _ = Payment.objects.get_or_create(
variant=variant, is_active=True, order=order, defaults=defaults,
- total=order.total.gross)
+ total=order.total.gross.amount, currency=order.total.gross.currency)
if (
order.is_fully_paid()
or payment.charge_status == ChargeStatus.FULLY_REFUNDED):
diff --git a/saleor/payment/forms.py b/saleor/payment/forms.py
index fbc2e49662..10ac22e6ac 100644
--- a/saleor/payment/forms.py
+++ b/saleor/payment/forms.py
@@ -53,7 +53,7 @@ class BraintreePaymentForm(forms.Form):
def __init__(self, instance, *args, **kwargs):
self.instance = instance
super().__init__(*args, **kwargs)
- self.fields['amount'].initial = self.instance.total.amount
+ self.fields['amount'].initial = self.instance.total
#FIXME if environment is Sandbox, we could provide couple of predefined
# nounces for easier testing
@@ -64,7 +64,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.amount:
+ if amount and amount != self.instance.total:
msg = pgettext_lazy(
'payment error',
'Unable to process transaction. Please try again in a moment')
@@ -75,7 +75,7 @@ class BraintreePaymentForm(forms.Form):
# FIXME add tests
self.instance.authorize(self.cleaned_data['payment_method_nonce'])
try:
- self.instance.capture(self.instance.total.amount)
+ self.instance.capture(self.instance.total)
except PaymentError as exc:
# Void authorization if the capture failed
self.instance.void()
diff --git a/saleor/payment/migrations/0001_initial.py b/saleor/payment/migrations/0001_initial.py
index 0576d1c90f..8288bad4eb 100644
--- a/saleor/payment/migrations/0001_initial.py
+++ b/saleor/payment/migrations/0001_initial.py
@@ -5,6 +5,7 @@ from django.db import migrations, models
import django.db.models.deletion
import django_prices.models
import saleor.core
+from decimal import Decimal
class Migration(migrations.Migration):
@@ -39,8 +40,9 @@ class Migration(migrations.Migration):
('customer_ip_address', models.GenericIPAddressField(blank=True, null=True)),
('extra_data', models.TextField(blank=True, default='')),
('token', models.CharField(blank=True, default='', max_length=36)),
- ('total', django_prices.models.MoneyField(currency='USD', decimal_places=2, default=saleor.core.zero_money, max_digits=12)),
- ('captured_amount', django_prices.models.MoneyField(currency='USD', decimal_places=2, default=saleor.core.zero_money, max_digits=12)),
+ ('currency', models.CharField(max_length=10)),
+ ('total', models.DecimalField(decimal_places=2, default=Decimal('0.0'), max_digits=12)),
+ ('captured_amount', models.DecimalField(decimal_places=2, default=Decimal('0.0'), max_digits=12)),
('checkout', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='payment_methods', to='checkout.Cart')),
('order', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='payment_methods', to='order.Order')),
],
@@ -53,7 +55,8 @@ class Migration(migrations.Migration):
('token', models.CharField(blank=True, default='', max_length=64)),
('transaction_type', models.CharField(choices=[('auth', 'Authorization'), ('capture', 'Charge'), ('refund', 'Refund'), ('capture', 'Capture'), ('void', 'Void')], max_length=10)),
('is_success', models.BooleanField(default=False)),
- ('amount', django_prices.models.MoneyField(currency='USD', decimal_places=2, default=saleor.core.zero_money, max_digits=12)),
+ ('currency', models.CharField(max_length=10)),
+ ('amount', models.DecimalField(decimal_places=2, default=Decimal('0.0'), max_digits=12)),
('gateway_response', django.contrib.postgres.fields.jsonb.JSONField()),
('payment_method', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transactions', to='payment.PaymentMethod')),
],
diff --git a/saleor/payment/migrations/0002_transfer_payment_to_payment_method.py b/saleor/payment/migrations/0002_transfer_payment_to_payment_method.py
index 2925f46131..79432c60a5 100644
--- a/saleor/payment/migrations/0002_transfer_payment_to_payment_method.py
+++ b/saleor/payment/migrations/0002_transfer_payment_to_payment_method.py
@@ -54,28 +54,31 @@ def create_transactions(method, payment):
return
# Other payments needed to be authorized first
- amount = Money(payment.total, payment.currency)
created = payment.created
create_transaction(
method=method, transaction_type=TransactionType.AUTH,
- created=created, amount=amount, is_success=True)
+ created=created, amount=payment.total, currency=payment.currency,
+ is_success=True, token=payment.transaction_id)
# This kind of payment needs an unsuccessful capture transaction
if payment.status in [PaymentStatus.ERROR, PaymentStatus.REJECTED]:
create_transaction(
method=method, transaction_type=TransactionType.CAPTURE,
- created=created, amount=amount, is_success=False)
+ created=created, amount=payment.total, currency=payment.currency,
+ is_success=False, token=payment.transaction_id)
return
# Two other payments left - CONFIRMED and REFUNDED needs to be captured
create_transaction(
method=method, transaction_type=TransactionType.CAPTURE,
- created=created, amount=amount, is_success=True)
+ created=created, amount=payment.total, currency=payment.currency,
+ is_success=True, token=payment.transaction_id)
# If payment was refunded, we need to create a refund transaction for it
if payment.status == PaymentStatus.REFUNDED:
create_transaction(
method=method, transaction_type=TransactionType.REFUND,
- created=created, amount=amount, is_success=True)
+ created=created, amount=payment.total, currency=payment.currency,
+ is_success=True, token=payment.transaction_id)
def transfer_payments_to_payment_methods(apps, schema_editor):
@@ -109,8 +112,9 @@ def transfer_payments_to_payment_methods(apps, schema_editor):
customer_ip_address=pay.customer_ip_address,
extra_data=extra_data,
token=pay.token,
- captured_amount=Money(pay.captured_amount, pay.currency or settings.DEFAULT_CURRENCY),
- total=Money(pay.total, pay.currency or settings.DEFAULT_CURRENCY),
+ captured_amount=pay.captured_amount,
+ total=pay.total,
+ currency=pay.currency or settings.DEFAULT_CURRENCY,
is_active=get_is_active(pay.status, pay),
charge_status=get_charge_status(pay))
create_transactions(payment_method, pay)
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 303ae1a0bf..b122a6c117 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -4,11 +4,13 @@ from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.db import models
from django_prices.models import MoneyField
+from prices import Money
from . import ChargeStatus, TransactionType
from ..checkout.models import Cart
from ..core import zero_money
from ..order.models import Order
+from decimal import Decimal
class Payment(models.Model):
@@ -57,11 +59,11 @@ class Payment(models.Model):
total = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default='0.0')
+ default=Decimal('0.0'))
captured_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default='0.0')
+ default=Decimal('0.0'))
checkout = models.ForeignKey(
Cart, null=True, related_name='payments', on_delete=models.SET_NULL)
@@ -75,6 +77,13 @@ class Payment(models.Model):
def __iter__(self):
return iter(self.transactions.all())
+ def get_total(self):
+ return Money(self.total, self.currency or settings.DEFAULT_CURRENCY)
+
+ def get_captured_amount(self):
+ return Money(
+ self.captured_amount, self.currency or settings.DEFAULT_CURRENCY)
+
def get_last_transaction(self):
return max(self.transactions.all(), default=None, key=attrgetter('pk'))
@@ -95,13 +104,13 @@ class Payment(models.Model):
def capture(self, amount=None):
from . import utils
if amount is None:
- amount = self.total.amount
+ amount = self.total
return utils.gateway_capture(payment=self, amount=amount)
def refund(self, amount=None):
from . import utils
if amount is None:
- amount = self.total.amount
+ amount = self.total
return utils.gateway_refund(payment=self, amount=amount)
@@ -124,7 +133,7 @@ class Transaction(models.Model):
amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default='0.0')
+ default=Decimal('0.0'))
gateway_response = JSONField()
diff --git a/saleor/payment/providers/braintree/__init__.py b/saleor/payment/providers/braintree/__init__.py
index 602d705440..9264efd7d1 100644
--- a/saleor/payment/providers/braintree/__init__.py
+++ b/saleor/payment/providers/braintree/__init__.py
@@ -22,7 +22,7 @@ THREE_D_SECURE_REQUIRED = False
# FIXME: Provide list of visible errors and messages translations
# FIXME: We should also store universal visible errors for all payment
-# gateways, and parse gateway-specific errors to this unified version
+# gateways, and parse gateway-specific errors to the unified version
# Error codes whitelist should be a dict of code: error_msg_override
# if no error_msg_override is provided,
@@ -73,12 +73,11 @@ def transaction_and_incorrect_token_error(
token: str,
type: TransactionType,
amount: Decimal = None) -> Tuple[Transaction, str]:
- amount = (
- payment.total
- if amount is None else Money(amount, settings.DEFAULT_CURRENCY))
+ amount = amount or payment.total
txn = create_transaction(
payment=payment,
transaction_type=type,
+ currency=payment.currency,
amount=amount,
gateway_response={},
token=token,
@@ -105,8 +104,8 @@ def extract_gateway_response(braintree_result) -> Dict:
# FIXME we should have a predefined list of fields that will be supported
# in the API
gateway_response = {
- 'currency_iso_code': bt_transaction.currency_iso_code,
- 'amount': str(bt_transaction.amount), # Decimal type
+ 'currency': bt_transaction.currency_iso_code,
+ 'amount': bt_transaction.amount, # Decimal type
'created_at': str(bt_transaction.created_at), # datetime type
'credit_card': bt_transaction.credit_card,
'additional_processor_response': bt_transaction.additional_processor_response, # noqa
@@ -150,7 +149,7 @@ def authorize(
gateway = get_gateway(**connection_params)
try:
result = gateway.transaction.sale({
- 'amount': str(payment.total.amount),
+ 'amount': str(payment.total),
'payment_method_nonce': transaction_token,
'options': {
'submit_for_settlement': CONFIRM_MANUALLY,
@@ -165,7 +164,8 @@ def authorize(
txn = create_transaction(
payment=payment,
transaction_type=TransactionType.AUTH,
- amount=payment.total,
+ amount=gateway_response.pop('amount', payment.total),
+ currency=gateway_response.pop('currency', payment.currency),
gateway_response=gateway_response,
token=getattr(result.transaction, 'id', ''),
is_success=result.is_success)
@@ -195,7 +195,8 @@ def capture(
txn = create_transaction(
payment=payment,
transaction_type=TransactionType.CAPTURE,
- amount=Money(amount, settings.DEFAULT_CURRENCY),
+ amount=gateway_response.pop('amount', amount),
+ currency=gateway_response.pop('currency', payment.currency),
token=getattr(result.transaction, 'id', ''),
is_success=result.is_success,
gateway_response=gateway_response)
@@ -220,7 +221,8 @@ def void(
txn = create_transaction(
payment=payment,
transaction_type=TransactionType.VOID,
- amount=payment.total,
+ amount=gateway_response.pop('amount', payment.total),
+ currency=gateway_response.pop('currency', payment.currency),
gateway_response=gateway_response,
token=getattr(result.transaction, 'id', ''),
is_success=result.is_success)
@@ -248,7 +250,8 @@ def refund(
txn = create_transaction(
payment=payment,
transaction_type=TransactionType.REFUND,
- amount=Money(amount, settings.DEFAULT_CURRENCY),
+ amount=gateway_response.pop('amount', amount),
+ currency=gateway_response.pop('currency', payment.currency),
token=getattr(result.transaction, 'id', ''),
is_success=result.is_success,
gateway_response=gateway_response)
diff --git a/saleor/payment/providers/dummy/__init__.py b/saleor/payment/providers/dummy/__init__.py
index 8c79555b0f..33fd1b6b50 100644
--- a/saleor/payment/providers/dummy/__init__.py
+++ b/saleor/payment/providers/dummy/__init__.py
@@ -27,6 +27,7 @@ def authorize(payment: Payment, transaction_token: str, **connection_params):
payment=payment,
transaction_type=TransactionType.AUTH,
amount=payment.total,
+ currency=payment.currency,
gateway_response={},
token=str(uuid.uuid4()),
is_success=success)
@@ -42,6 +43,7 @@ def void(payment: Payment, **connection_params: Dict):
payment=payment,
transaction_type=TransactionType.VOID,
amount=payment.total,
+ currency=payment.currency,
gateway_response={},
token=str(uuid.uuid4()),
is_success=success)
@@ -56,7 +58,8 @@ def capture(payment: Payment, amount: Decimal):
txn = create_transaction(
payment=payment,
transaction_type=TransactionType.CAPTURE,
- amount=Money(amount, settings.DEFAULT_CURRENCY),
+ amount=amount,
+ currency=payment.currency,
token=str(uuid.uuid4()),
is_success=success)
return txn, error
@@ -70,7 +73,8 @@ def refund(payment: Payment, amount: Decimal):
txn = create_transaction(
payment=payment,
transaction_type=TransactionType.REFUND,
- amount=Money(amount, settings.DEFAULT_CURRENCY),
+ amount=amount,
+ currency=payment.currency,
token=str(uuid.uuid4()),
is_success=success)
return txn, error
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 980b968e19..2b64141d4e 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -55,11 +55,10 @@ def validate_payment(view):
"""
@wraps(view)
- def func(payment, *args, **kwargs):
+ def func(payment: Payment, *args, **kwargs):
if not payment.is_active:
raise PaymentError('This payment is no longer active.')
return view(payment, *args, **kwargs)
-
return func
@@ -73,7 +72,8 @@ def create_transaction(
token: str,
transaction_type: str,
is_success: bool,
- amount: Money,
+ amount: Decimal,
+ currency: str,
gateway_response: Optional[Dict] = None) -> Transaction:
if not gateway_response:
gateway_response = {}
@@ -83,6 +83,7 @@ def create_transaction(
transaction_type=transaction_type,
is_success=is_success,
amount=amount,
+ currency=currency,
gateway_response=gateway_response)
return txn
@@ -115,8 +116,8 @@ def gateway_capture(payment: Payment, amount: Decimal) -> Transaction:
if payment.charge_status not in {ChargeStatus.CHARGED,
ChargeStatus.NOT_CHARGED}:
raise PaymentError('This payment cannot be captured.')
- if amount > payment.total.amount or amount > (
- payment.total.amount - payment.captured_amount.amount):
+ if amount > payment.total or amount > (
+ payment.total - payment.captured_amount):
raise PaymentError('Unable to capture more than authorized amount.')
provider, provider_params = get_provider(payment.variant)
@@ -156,7 +157,7 @@ def gateway_void(payment) -> Transaction:
def gateway_refund(payment, amount: Decimal) -> Transaction:
if amount <= 0:
raise PaymentError('Amount should be a positive number.')
- if amount > payment.captured_amount.amount:
+ if amount > payment.captured_amount:
raise PaymentError('Cannot refund more than captured')
if not payment.charge_status == ChargeStatus.CHARGED:
raise PaymentError(
diff --git a/templates/dashboard/index.html b/templates/dashboard/index.html
index 14be0872cd..1a8d97c6f4 100644
--- a/templates/dashboard/index.html
+++ b/templates/dashboard/index.html
@@ -48,7 +48,7 @@
{{ payment.order.user|default:_("Guest") }}
</td>
<td class="right-align">
- {% price payment.total %}
+ {% price payment.get_total %}
</td>
</tr>
{% endfor %}
diff --git a/templates/dashboard/order/detail.html b/templates/dashboard/order/detail.html
index 5777182a5e..6fa45f0880 100644
--- a/templates/dashboard/order/detail.html
+++ b/templates/dashboard/order/detail.html
@@ -137,8 +137,8 @@
{% trans "Preauthorized amount" context "Order summary card header" %}
</td>
<td class="right-align">
- {% if order.authorized_amount %}
- {% price order.authorized_amount %}
+ {% if order.total_authorized %}
+ {% price order.total_authorized %}
{% else %}
{% trans "N/A" context "Preauthorized amount not available" %}
{% endif %}
@@ -149,7 +149,7 @@
{% trans "Captured amount" context "Order summary card header" %}
</td>
<td class="right-align">
- {% price order.captured_amount %}
+ {% price order.total_captured %}
</td>
</tr>
</tbody>
@@ -599,7 +599,7 @@
{% render_status payment.charge_status payment.get_charge_status_display %}
</td>
<td>
- {% price payment.total %}
+ {% price payment.get_total %}
</td>
</tr>
{% endfor %}
diff --git a/templates/order/payment/braintree.html b/templates/order/payment/braintree.html
index f2582aa050..301f107678 100644
--- a/templates/order/payment/braintree.html
+++ b/templates/order/payment/braintree.html
@@ -20,7 +20,7 @@
</div>
<input type="hidden" id="nonce" name="payment_method_nonce"/>
- <input type="hidden" id="amount" name="amount" value="{{ payment.total.amount }}"/>
+ <input type="hidden" id="amount" name="amount" value="{{ payment.total }}"/>
<button type="submit" class="btn primary">
{% trans "Make payment" context "Payment form primary action" %}
</button>
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index 67d6110cc0..acb3cd606c 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -369,7 +369,8 @@ def test_checkout_complete(
payment = payment_dummy
payment.is_active = True
payment.order = None
- payment.total = total.gross
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
payment.checkout = checkout
payment.save()
checkout_id = graphene.Node.to_global_id('Checkout', checkout.pk)
diff --git a/tests/api/test_order.py b/tests/api/test_order.py
index af69fab58b..1f4af0d0b0 100644
--- a/tests/api/test_order.py
+++ b/tests/api/test_order.py
@@ -916,7 +916,7 @@ def test_order_capture(
}
"""
order_id = graphene.Node.to_global_id('Order', order.id)
- amount = float(payment_txn_preauth.total.amount)
+ amount = float(payment_txn_preauth.total)
variables = {'id': order_id, 'amount': amount}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_orders])
@@ -1042,7 +1042,7 @@ def test_order_refund(
}
"""
order_id = graphene.Node.to_global_id('Order', order.id)
- amount = float(payment_txn_captured.total.amount)
+ amount = float(payment_txn_captured.total)
variables = {'id': order_id, 'amount': amount}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_orders])
diff --git a/tests/api/test_payment.py b/tests/api/test_payment.py
index 6064f504ee..b465e9161c 100644
--- a/tests/api/test_payment.py
+++ b/tests/api/test_payment.py
@@ -111,7 +111,9 @@ def test_checkout_add_payment(
assert payment.checkout == cart
assert payment.is_active
assert payment.token == 'sample-token'
- assert payment.total == cart.get_total().gross
+ total = cart.get_total().gross
+ assert payment.total == total.amount
+ assert payment.currency == total.currency
assert payment.charge_status == ChargeStatus.NOT_CHARGED
@@ -140,7 +142,7 @@ def test_payment_charge_success(
variables = {
'paymentId': payment_id,
- 'amount': str(payment_dummy.total.amount)}
+ 'amount': str(payment_dummy.total)}
response = staff_api_client.post_graphql(
CHARGE_QUERY, variables, permissions=[permission_manage_orders])
content = get_graphql_content(response)
@@ -162,7 +164,7 @@ def test_payment_charge_gateway_error(
'Payment', payment_dummy.pk)
variables = {
'paymentId': payment_id,
- 'amount': str(payment_dummy.total.amount)}
+ 'amount': str(payment_dummy.total)}
monkeypatch.setattr(
'saleor.payment.providers.dummy.dummy_success', lambda: False)
response = staff_api_client.post_graphql(
@@ -208,7 +210,7 @@ def test_payment_refund_success(
variables = {
'paymentId': payment_id,
- 'amount': str(payment_dummy.total.amount)}
+ 'amount': str(payment_dummy.total)}
response = staff_api_client.post_graphql(
REFUND_QUERY, variables, permissions=[permission_manage_orders])
content = get_graphql_content(response)
@@ -232,7 +234,7 @@ def test_payment_refund_error(
'Payment', payment_dummy.pk)
variables = {
'paymentId': payment_id,
- 'amount': str(payment.total.amount)}
+ 'amount': str(payment.total)}
monkeypatch.setattr(
'saleor.payment.providers.dummy.dummy_success', lambda: False)
response = staff_api_client.post_graphql(
diff --git a/tests/conftest.py b/tests/conftest.py
index 9746381c1d..d1a37e4172 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -733,7 +733,8 @@ def payment_dummy(db, order_with_lines):
variant='dummy',
order=order_with_lines,
is_active=True,
- total=order_with_lines.total.gross,
+ total=order_with_lines.total.gross.amount,
+ currency=order_with_lines.total.gross.currency,
billing_first_name=order_with_lines.billing_address.first_name,
billing_last_name=order_with_lines.billing_address.last_name,
billing_company_name=order_with_lines.billing_address.company_name,
diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.py
index 240d208a44..8ed7aaa9aa 100644
--- a/tests/dashboard/test_order.py
+++ b/tests/dashboard/test_order.py
@@ -1,4 +1,5 @@
import json
+from decimal import Decimal
import pytest
from django.conf import settings
@@ -79,7 +80,8 @@ def test_view_capture_order_payment_preauth(
assert response.status_code == 302
payment = order.payments.last()
assert payment.charge_status == ChargeStatus.CHARGED
- assert payment.captured_amount == order.total.gross
+ assert payment.captured_amount == order.total.gross.amount
+ assert payment.currency == order.total.gross.currency
@pytest.mark.integration
@@ -148,11 +150,11 @@ def test_view_refund_order_payment_confirmed(
response = admin_client.post(
url, {
'csrfmiddlewaretoken': 'hello',
- 'amount': str(payment_confirmed.captured_amount.amount)})
+ 'amount': str(payment_confirmed.captured_amount)})
assert response.status_code == 302
payment = order.payments.last()
assert payment.charge_status == ChargeStatus.FULLY_REFUNDED
- assert payment.captured_amount == Money(0, 'USD')
+ assert payment.captured_amount == Decimal('0.00')
@pytest.mark.integration
@@ -210,7 +212,7 @@ def test_view_void_order_payment_preauth(
last_transaction = order_payment.transactions.latest('pk')
assert last_transaction.transaction_type == TransactionType.VOID
- assert order_payment.captured_amount == Money(0, 'USD')
+ assert order_payment.captured_amount == Decimal('0.00')
@@ -230,7 +232,9 @@ def test_view_void_order_invalid_payment_confirmed_status(
assert response.status_code == 400
order_payment = order.payments.last()
assert order_payment.charge_status == ChargeStatus.CHARGED
- assert order_payment.captured_amount == order.total.gross
+ assert order_payment.captured_amount == order.total.gross.amount
+ assert order_payment.total == order.total.gross.amount
+ assert order_payment.currency == order.total.gross.currency
@pytest.mark.integration
@@ -249,7 +253,7 @@ def test_view_void_order_invalid_payment_refunded_status(
assert response.status_code == 400
payment = order.payments.last()
assert payment.charge_status == ChargeStatus.FULLY_REFUNDED
- assert payment.captured_amount == Money(0, 'USD')
+ assert payment.captured_amount == Decimal('0.00')
@pytest.mark.integration
diff --git a/tests/test_order.py b/tests/test_order.py
index b4058a28d1..b36b85a576 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -370,7 +370,9 @@ def test_order_queryset_to_ship():
for order in orders_to_ship:
order.payments.create(
variant=settings.DUMMY, charge_status=ChargeStatus.CHARGED,
- total=order.total.gross, captured_amount=order.total_gross)
+ total=order.total.gross.amount,
+ captured_amount=order.total.gross.amount,
+ currency=order.total.gross.currency)
orders_not_to_ship = [
Order.objects.create(status=OrderStatus.DRAFT, total=total),
@@ -459,10 +461,11 @@ def test_order_payment_flow(
# Go to payment details page, enter payment data
data = {
- 'variant': 'dummy',
+ 'variant': settings.DUMMY,
'is_active': True,
- 'total': order.total.gross,
- 'charge_status': 'not-charged'}
+ 'total': order.total.gross.amount,
+ 'currency': order.total.gross.currency,
+ 'charge_status': ChargeStatus.NOT_CHARGED}
response = client.post(redirect_url, data)
assert response.status_code == 302
@@ -472,7 +475,8 @@ def test_order_payment_flow(
# Assert that payment object was created and contains correct data
payment = order.payments.all()[0]
- assert payment.total == order.total_gross
+ assert payment.total == order.total.gross.amount
+ assert payment.currency == order.total.gross.currency
assert payment.transactions.count() == 1
assert payment.transactions.first().transaction_type == 'auth'
diff --git a/tests/test_payment.py b/tests/test_payment.py
index d38981941b..b7938c163d 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -18,13 +18,14 @@ EXAMPLE_ERROR = 'Example dummy error'
@pytest.fixture
-def transaction_data(payment_dummy):
+def transaction_data(payment_dummy, settings):
return {
'payment': payment_dummy,
'token': 'token',
'transaction_type': TransactionType.CAPTURE,
'is_success': True,
'amount': Decimal('10.00'),
+ 'currency': settings.DEFAULT_CURRENCY,
'gateway_response': {
'credit_cart': '4321'}}
@@ -230,7 +231,7 @@ def test_gateway_capture(
txn = payment_txn_preauth.transactions.first()
payment = payment_txn_preauth
assert not payment.captured_amount
- amount = payment.total.amount
+ amount = payment.total
mock_capture = Mock(return_value=(txn, ''))
mock_get_provider.return_value = (
@@ -253,9 +254,10 @@ def test_gateway_capture_partial_capture(
mock_get_provider, mock_handle_fully_paid_order, payment_txn_preauth,
provider_params, settings):
payment = payment_txn_preauth
- amount = payment.total.amount * Decimal('0.5')
+ amount = payment.total * Decimal('0.5')
txn = payment.transactions.first()
- txn.amount = Money(amount, settings.DEFAULT_CURRENCY)
+ txn.amount = amount
+ txn.currency = settings.DEFAULT_CURRENCY
mock_capture = Mock(return_value=(txn, ''))
mock_get_provider.return_value = (
@@ -265,7 +267,8 @@ def test_gateway_capture_partial_capture(
payment.refresh_from_db()
assert payment.charge_status == ChargeStatus.CHARGED
- assert payment.captured_amount == Money(amount, settings.DEFAULT_CURRENCY)
+ assert payment.captured_amount == amount
+ assert payment.currency == settings.DEFAULT_CURRENCY
assert not mock_handle_fully_paid_order.called
@@ -278,7 +281,7 @@ def test_gateway_capture_failed(
txn.is_success = False
payment = payment_txn_preauth
- amount = payment.total.amount
+ amount = payment.total
mock_capture = Mock(return_value=(txn, EXAMPLE_ERROR))
mock_get_provider.return_value = (
@@ -355,7 +358,7 @@ def test_gateway_refund(
mock_get_provider, payment_txn_captured, provider_params):
txn = payment_txn_captured.transactions.first()
payment = payment_txn_captured
- amount = payment.total.amount
+ amount = payment.total
mock_refund = Mock(return_value=(txn, ''))
mock_get_provider.return_value = (
@@ -374,9 +377,10 @@ def test_gateway_refund(
def test_gateway_refund_partial_refund(
mock_get_provider, payment_txn_captured, provider_params, settings):
payment = payment_txn_captured
- amount = payment.total.amount * Decimal('0.5')
+ amount = payment.total * Decimal('0.5')
txn = payment_txn_captured.transactions.first()
- txn.amount = Money(amount, settings.DEFAULT_CURRENCY)
+ txn.amount = amount
+ txn.currency = settings.DEFAULT_CURRENCY
mock_refund = Mock(return_value=(txn, ''))
mock_get_provider.return_value = (
@@ -386,8 +390,7 @@ def test_gateway_refund_partial_refund(
payment.refresh_from_db()
assert payment.charge_status == ChargeStatus.CHARGED
- assert payment.captured_amount == payment.total - Money(
- amount, settings.DEFAULT_CURRENCY)
+ assert payment.captured_amount == payment.total - amount
@patch('saleor.payment.utils.get_provider')
diff --git a/tests/test_payment_braintree.py b/tests/test_payment_braintree.py
index 3ddf95b695..8e63e33b2a 100644
--- a/tests/test_payment_braintree.py
+++ b/tests/test_payment_braintree.py
@@ -31,7 +31,7 @@ def braintree_success_response():
transaction=Mock(
id='1x02131',
spec=Transaction,
- amount='0.20',
+ amount=Decimal('0.20'),
created_at='2018-10-20 18:34:22',
credit_card={
'token': None,
@@ -85,6 +85,12 @@ def gateway_config():
'private_key': '789'}
+def success_gateway_response(gateway_response):
+ data = extract_gateway_response(gateway_response)
+ data.pop('currency')
+ data.pop('amount')
+ return data
+
def test_get_customer_data(payment_dummy):
payment = payment_dummy
result = get_customer_data(payment)
@@ -132,8 +138,8 @@ def test_extract_gateway_response(braintree_success_response):
result = extract_gateway_response(braintree_success_response)
t = braintree_success_response.transaction
expected_result = {
- 'currency_iso_code': t.currency_iso_code,
- 'amount': str(t.amount),
+ 'currency': t.currency_iso_code,
+ 'amount': t.amount,
'created_at': str(t.created_at),
'credit_card': t.credit_card,
'additional_processor_response': t.additional_processor_response,
@@ -205,6 +211,8 @@ def test_authorize_error_response(
assert txn.gateway_response == extract_gateway_response(
braintree_error_response)
assert not txn.is_success
+ assert txn.amount == payment.total
+ assert txn.currency == payment.currency
assert error == DEFAULT_ERROR
@@ -239,14 +247,15 @@ def test_authorize(
assert txn.payment == payment
assert txn.transaction_type == TransactionType.AUTH
- assert txn.amount == payment.total
- assert txn.gateway_response == extract_gateway_response(
+ assert txn.amount == braintree_success_response.transaction.amount
+ assert txn.currency == braintree_success_response.transaction.currency_iso_code
+ assert txn.gateway_response == success_gateway_response(
braintree_success_response)
assert txn.token == braintree_success_response.transaction.id
assert txn.is_success == braintree_success_response.is_success
mock_response.assert_called_once_with({
- 'amount': str(payment.total.amount),
+ 'amount': str(payment.total),
'payment_method_nonce': 'transaction-token',
'options': {
'submit_for_settlement': CONFIRM_MANUALLY,
@@ -269,8 +278,9 @@ def test_refund(
assert txn.payment == payment
assert txn.transaction_type == TransactionType.REFUND
- assert txn.amount == Money(amount, settings.DEFAULT_CURRENCY)
- assert txn.gateway_response == extract_gateway_response(
+ assert txn.amount == braintree_success_response.transaction.amount
+ assert txn.currency == braintree_success_response.transaction.currency_iso_code
+ assert txn.gateway_response == success_gateway_response(
braintree_success_response)
assert txn.token == braintree_success_response.transaction.id
assert txn.is_success == braintree_success_response.is_success
@@ -315,6 +325,8 @@ def test_refund_error_response(
assert txn.gateway_response == extract_gateway_response(
braintree_error_response)
assert not txn.is_success
+ assert txn.amount == amount
+ assert txn.currency == payment.currency
assert error == DEFAULT_ERROR
@@ -334,8 +346,9 @@ def test_capture(
assert txn.payment == payment
assert txn.transaction_type == TransactionType.CAPTURE
- assert txn.amount == Money(amount, settings.DEFAULT_CURRENCY)
- assert txn.gateway_response == extract_gateway_response(
+ assert txn.amount == braintree_success_response.transaction.amount
+ assert txn.currency == braintree_success_response.transaction.currency_iso_code
+ assert txn.gateway_response == success_gateway_response(
braintree_success_response)
assert txn.token == braintree_success_response.transaction.id
assert txn.is_success == braintree_success_response.is_success
@@ -383,6 +396,8 @@ def test_capture_error_response(
assert txn.gateway_response == extract_gateway_response(
braintree_error_response)
assert not txn.is_success
+ assert txn.amount == amount
+ assert txn.currency == payment.currency
assert error == DEFAULT_ERROR
@@ -399,8 +414,9 @@ def test_void(
assert txn.payment == payment
assert txn.transaction_type == TransactionType.VOID
- assert txn.amount == payment.total
- assert txn.gateway_response == extract_gateway_response(
+ assert txn.amount == braintree_success_response.transaction.amount
+ assert txn.currency == braintree_success_response.transaction.currency_iso_code
+ assert txn.gateway_response == success_gateway_response(
braintree_success_response)
assert txn.token == braintree_success_response.transaction.id
assert txn.is_success == braintree_success_response.is_success
@@ -441,6 +457,8 @@ def test_void_error_response(
assert txn.gateway_response == extract_gateway_response(
braintree_error_response)
assert not txn.is_success
+ assert txn.amount == payment.total
+ assert txn.currency == payment.currency
assert error == DEFAULT_ERROR
@@ -453,7 +471,8 @@ def test_transaction_and_incorrect_token_error_helper(payment_dummy, settings):
assert txn.transaction_type == TransactionType.AUTH
assert txn.token == 'example-token'
assert not txn.gateway_response
- assert txn.amount == Money(amount, settings.DEFAULT_CURRENCY)
+ assert txn.amount == amount
+ assert txn.currency == settings.DEFAULT_CURRENCY
def test_transaction_and_incorrect_token_error_helper_no_amount(payment_dummy):
diff --git a/tests/test_payment_dummy.py b/tests/test_payment_dummy.py
index a912175a3f..ca5ad7120c 100644
--- a/tests/test_payment_dummy.py
+++ b/tests/test_payment_dummy.py
@@ -1,9 +1,9 @@
+from decimal import Decimal
+
import pytest
from saleor.payment import ChargeStatus, PaymentError, TransactionType
-from .utils import money
-
def test_authorize(payment_dummy):
txn = payment_dummy.authorize(transaction_token='Fake')
@@ -74,10 +74,10 @@ def test_charge_success(amount, payment_dummy):
@pytest.mark.parametrize(
'amount, captured_amount, charge_status, is_active', [
- (80, money(0), ChargeStatus.NOT_CHARGED, False),
- (80, money(0), ChargeStatus.FULLY_REFUNDED, True),
- (80, money(80), ChargeStatus.CHARGED, True),
- (120, money(0), ChargeStatus.NOT_CHARGED, True), ])
+ (80, 0, ChargeStatus.NOT_CHARGED, False),
+ (80, 0, ChargeStatus.FULLY_REFUNDED, True),
+ (80, 80, ChargeStatus.CHARGED, True),
+ (120, 0, ChargeStatus.NOT_CHARGED, True), ])
def test_charge_failed(
amount, captured_amount, charge_status, is_active,
payment_dummy):
@@ -104,8 +104,8 @@ def test_charge_gateway_error(payment_dummy, monkeypatch):
@pytest.mark.parametrize(
'initial_captured_amount, refund_amount, final_captured_amount, final_charge_status, active_after',
[
- (money(80), 80, money(0), ChargeStatus.FULLY_REFUNDED, False),
- (money(80), 10, money(70), ChargeStatus.CHARGED, True), ])
+ (80, 80, 0, ChargeStatus.FULLY_REFUNDED, False),
+ (80, 10, 70, ChargeStatus.CHARGED, True), ])
def test_refund_success(
initial_captured_amount, refund_amount, final_captured_amount,
final_charge_status, active_after, payment_dummy):
@@ -124,15 +124,15 @@ def test_refund_success(
@pytest.mark.parametrize(
'initial_captured_amount, refund_amount, initial_charge_status', [
- (money(80), 0, ChargeStatus.FULLY_REFUNDED),
- (money(0), 10, ChargeStatus.NOT_CHARGED),
- (money(10), 20, ChargeStatus.CHARGED), ])
+ (80, 0, ChargeStatus.FULLY_REFUNDED),
+ (0, 10, ChargeStatus.NOT_CHARGED),
+ (10, 20, ChargeStatus.CHARGED), ])
def test_refund_failed(
initial_captured_amount, refund_amount, initial_charge_status,
payment_dummy):
payment = payment_dummy
payment.charge_status = initial_charge_status
- payment.captured_amount = initial_captured_amount
+ payment.captured_amount = Decimal(initial_captured_amount)
payment.save()
with pytest.raises(PaymentError):
txn = payment.refund(refund_amount)
@@ -144,13 +144,15 @@ def test_refund_gateway_error(payment_dummy, monkeypatch):
'saleor.payment.providers.dummy.dummy_success', lambda: False)
payment = payment_dummy
payment.charge_status = ChargeStatus.CHARGED
- payment.captured_amount = money(80)
+ payment.captured_amount = Decimal('80.00')
payment.save()
with pytest.raises(PaymentError):
- txn = payment.refund(80)
- payment.refresh_from_db()
- assert txn.transaction_type == TransactionType.REFUND
- assert not txn.is_success
- assert txn.payment == payment
- assert payment.charge_status == ChargeStatus.CHARGED
- assert payment.captured_amount == money(80)
+ payment.refund(Decimal('80.00'))
+
+ payment.refresh_from_db()
+ txn = payment.transactions.first()
+ assert txn.transaction_type == TransactionType.REFUND
+ assert not txn.is_success
+ assert txn.payment == payment
+ assert payment.charge_status == ChargeStatus.CHARGED
+ assert payment.captured_amount == Decimal('80.00')