Skip to content

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

Improve docstrings, add validation for some of the mutaitons

Pacu21bd39dc7f190
diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.py
index 77d2e495e6..64eb7776d7 100644
--- a/saleor/checkout/forms.py
+++ b/saleor/checkout/forms.py
@@ -16,7 +16,6 @@ from ..discount.models import NotApplicable, Voucher
from ..shipping.models import ShippingMethod, ShippingZone
from ..shipping.utils import get_shipping_price_estimate
from .models import Cart
-from ..payment.models import PaymentMethod
class QuantityField(forms.IntegerField):
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 4610aa1652..a73afabaf6 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -846,9 +846,7 @@ def _fill_order_with_cart_data(order, cart, discounts, taxes):
add_variant_to_order(
order, line.variant, line.quantity, discounts, taxes)
- for payment_method in cart.payment_methods.all():
- payment_method.order = order
- payment_method.save(update_fields=['order'])
+ cart.payment_methods.update(order=order)
if cart.note:
order.customer_note = cart.note
@@ -897,10 +895,11 @@ def ready_to_place_order(cart: Cart):
if cart.is_shipping_required:
if not cart.shipping_method:
return False, pgettext_lazy(
- 'order placement_error','Shipping method is not set')
+ 'order placement_error', 'Shipping method is not set')
if not cart.shipping_address:
return False, pgettext_lazy(
'order placement error', 'Shipping address is not set')
+ # FIXME Check if shipping method is valid for the shipping address
if not is_fully_paid(cart):
return False, pgettext_lazy(
'order placement error', 'Checkout is not fully paid')
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index 1eccaf2a64..3234222f9d 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -72,13 +72,15 @@ class Query(ProductQueries):
AddressValidationData,
input=graphene.Argument(AddressValidationInput, required=True))
checkout = graphene.Field(
- Checkout, description='Single checkout',
+ Checkout, description='Single checkout.',
token=graphene.Argument(graphene.UUID))
checkouts = DjangoFilterConnectionField(
- Checkout, description='List of checkouts')
+ Checkout, description='List of checkouts.')
checkout_lines = DjangoFilterConnectionField(
CheckoutLine, description='List of checkout lines')
- checkout_line = graphene.Field(CheckoutLine, id=graphene.Argument(graphene.ID))
+ checkout_line = graphene.Field(
+ CheckoutLine, id=graphene.Argument(graphene.ID),
+ description='Single checkout line.')
menu = graphene.Field(
Menu, id=graphene.Argument(graphene.ID),
name=graphene.Argument(graphene.String, description="Menu name."),
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 36957e15b3..50c6e0f371 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -1,23 +1,55 @@
import graphene
from django.db import transaction
-from django.utils.translation import pgettext_lazy
from ...account.models import Address
from ...checkout import models
from ...checkout.utils import (
add_variant_to_cart, change_shipping_address_in_cart, create_order,
- ready_to_place_order)
+ get_taxes_for_cart, ready_to_place_order)
from ...core import analytics
from ...core.exceptions import InsufficientStock
+from ...shipping.models import ShippingMethod as ShippingMethodModel
from ..account.types import AddressInput, User
from ..core.mutations import BaseMutation, ModelMutation
+from ..core.types.common import Error
from ..order.types import Order
from ..product.types import ProductVariant
from ..shipping.types import ShippingMethod
-from ..utils import get_nodes
from .types import Checkout, CheckoutLine
+def clean_shipping_method(
+ checkout, method, errors, discounts, taxes, country_code=None):
+ if not method:
+ return errors
+ if not checkout.shipping_address:
+ errors.append(
+ Error(
+ field='checkout',
+ message=(
+ 'Cannot choose a shipping method for a '
+ 'checkout without the shipping address.')))
+ return errors
+ if not checkout.is_shipping_required():
+ errors.append(
+ Error(
+ field='checkout',
+ message='This checkout does not requires shipping.'))
+ valid_methods = (
+ ShippingMethodModel.objects.applicable_shipping_methods(
+ price=checkout.get_subtotal(discounts, taxes).gross.amount,
+ weight=checkout.get_total_weight(),
+ country_code=country_code or checkout.shipping_address.country.code
+ ))
+ valid_methods = valid_methods.values_list('id', flat=True)
+ if method.pk not in valid_methods:
+ errors.append(
+ Error(
+ field='shippingMethod',
+ message='Shipping method cannot be used with this checkout.'))
+ return errors
+
+
def check_lines_quantity(variants, quantities):
"""Check if stock is sufficient for each line in the list of dicts.
Return list of errors.
@@ -28,7 +60,7 @@ def check_lines_quantity(variants, quantities):
try:
variant.check_quantity(quantity)
except InsufficientStock as e:
- message = pgettext_lazy(
+ message = (
'Add line mutation error',
'Could not add item. Only %(remaining)d remaining in stock.' %
{'remaining': e.item.quantity_available})
@@ -37,23 +69,30 @@ def check_lines_quantity(variants, quantities):
class CheckoutLineInput(graphene.InputObjectType):
- quantity = graphene.Int(description='quantity')
- variant_id = graphene.ID(description='ID of product variant')
+ quantity = graphene.Int(
+ description='The number of items purchased.')
+ variant_id = graphene.ID(description='ID of the ProductVariant.')
class CheckoutCreateInput(graphene.InputObjectType):
- lines = graphene.List(CheckoutLineInput, description='Checkout lines')
- email = graphene.String(description='Customer email')
- shipping_address = AddressInput(description='Shipping address')
+ lines = graphene.List(
+ CheckoutLineInput,
+ description=(
+ 'A list of checkout lines, each containing information about '
+ 'an item in the checkout.'))
+ email = graphene.String(description='The customer\'s email address.')
+ shipping_address = AddressInput(
+ description=(
+ 'The mailling address to where the checkout will be shipped.'))
class CheckoutCreate(ModelMutation):
class Arguments:
input = CheckoutCreateInput(
- required=True, description='Fields required to create Checkout')
+ required=True, description='Fields required to create a Checkout.')
class Meta:
- description = 'Create a new Checkout'
+ description = 'Create a new Checkout.'
model = models.Cart
return_field_name = 'checkout'
@@ -64,7 +103,9 @@ class CheckoutCreate(ModelMutation):
lines = input.pop('lines', None)
if lines:
variant_ids = [line.get('variant_id') for line in lines]
- variants = get_nodes(variant_ids, ProductVariant)
+ variants = cls.get_nodes_or_error(
+ ids=variant_ids, errors=errors, field='variant_id',
+ only_type=ProductVariant)
quantities = [line.get('quantity') for line in lines]
line_errors = check_lines_quantity(variants, quantities)
if line_errors:
@@ -96,15 +137,20 @@ class CheckoutCreate(ModelMutation):
class CheckoutLinesAdd(BaseMutation):
- checkout = graphene.Field(Checkout, description='An updated checkout')
+ checkout = graphene.Field(Checkout, description='An updated Checkout.')
class Arguments:
- checkout_id = graphene.ID(description='Checkout ID', required=True)
+ checkout_id = graphene.ID(
+ description='The ID of the Checkout.', required=True)
lines = graphene.List(
- CheckoutLineInput, description='Checkout lines', required=True)
+ CheckoutLineInput,
+ required=True,
+ description=(
+ 'A list of checkout lines, each containing information about '
+ 'an item in the checkout.'))
class Meta:
- description = 'Adds a checkout line to existing checkout'
+ description = 'Adds a checkout line to existing checkout.'
@classmethod
def mutate(cls, root, info, checkout_id, lines, replace=False):
@@ -131,10 +177,10 @@ class CheckoutLinesAdd(BaseMutation):
class CheckoutLinesUpdate(CheckoutLinesAdd):
- checkout = graphene.Field(Checkout, description='An updated checkout')
+ checkout = graphene.Field(Checkout, description='An updated Checkout.')
class Meta:
- description = 'Updates checkout line in existing checkout'
+ description = 'Updates CheckoutLine in the existing Checkout.'
@classmethod
def mutate(cls, root, info, checkout_id, lines):
@@ -142,14 +188,16 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):
class CheckoutLineDelete(BaseMutation):
- checkout = graphene.Field(Checkout, description='An updated checkout')
+ checkout = graphene.Field(Checkout, description='An updated checkout.')
class Arguments:
- checkout_id = graphene.ID(description='Checkout ID', required=True)
- line_id = graphene.ID(description='Checkout line ID')
+ checkout_id = graphene.ID(
+ description='The ID of the Checkout.', required=True)
+ line_id = graphene.ID(
+ description='ID of the CheckoutLine to delete.')
class Meta:
- description = 'Deletes a checkout line'
+ description = 'Deletes a CheckoutLine.'
@classmethod
def mutate(cls, root, info, checkout_id, line_id):
@@ -164,11 +212,16 @@ class CheckoutLineDelete(BaseMutation):
class CheckoutCustomerAttach(BaseMutation):
- checkout = graphene.Field(Checkout, description='An updated checkout')
+ checkout = graphene.Field(Checkout, description='An updated checkout.')
class Arguments:
- checkout_id = graphene.ID(description='Checkout ID', required=True)
- customer_id = graphene.ID(description='Customer ID', required=True)
+ checkout_id = graphene.ID(
+ required=True, description='ID of the Checkout.')
+ customer_id = graphene.ID(
+ required=True, description='The ID of the customer.')
+
+ class Meta:
+ description = 'Sets the customer as the owner of the Checkout.'
@classmethod
def mutate(cls, root, info, checkout_id, customer_id):
@@ -189,10 +242,20 @@ class CheckoutCustomerDetach(BaseMutation):
class Arguments:
checkout_id = graphene.ID(description='Checkout ID', required=True)
+ class Meta:
+ description = 'Update shipping address in existing Checkout object'
+
@classmethod
def mutate(cls, root, info, checkout_id):
+ errors = []
checkout = graphene.Node.get_node_from_global_id(
info, checkout_id, Checkout)
+ if not checkout.user:
+ cls.add_error(
+ errors,
+ field=None,
+ message='There\'s no customer assigned to this Checkout.')
+ return CheckoutCustomerDetach(errors=errors)
if checkout:
checkout.user = None
checkout.save(update_fields=['user'])
@@ -203,18 +266,22 @@ class CheckoutShippingAddressUpdate(BaseMutation):
checkout = graphene.Field(Checkout, description='An updated checkout')
class Arguments:
- checkout_id = graphene.ID(description='Checkout ID')
- shipping_address = AddressInput(description='Shipping address')
+ checkout_id = graphene.ID(description='ID of the Checkout.')
+ shipping_address = AddressInput(
+ description=(
+ 'The mailling address to where the checkout will be shipped.'))
class Meta:
- description = 'Update shipping address in existing Checkout object'
+ description = 'Update shipping address in the existing Checkout.'
@classmethod
def mutate(cls, root, info, checkout_id, shipping_address):
- errors = {}
+ errors = []
checkout = cls.get_node_or_error(
info, checkout_id, errors, 'checkout_id', only_type=Checkout)
shipping_address = Address(**shipping_address)
+ # FIXME validate if shipping method is still valid after changing
+ # shipping address
if checkout and shipping_address:
with transaction.atomic():
shipping_address.save()
@@ -230,7 +297,7 @@ class CheckoutEmailUpdate(BaseMutation):
email = graphene.String(required=True, description='email')
class Meta:
- description = 'Update email address in existing Checkout object'
+ description = 'Updates email address in the existing Checkout object.'
@classmethod
def mutate(cls, root, info, checkout_id, email):
@@ -260,9 +327,15 @@ class CheckoutShippingMethodUpdate(BaseMutation):
shipping_method = cls.get_node_or_error(
info, shipping_method_id, errors, 'shipping_method_id',
only_type=ShippingMethod)
- if checkout:
- checkout.shipping_method = shipping_method
- checkout.save(update_fields=['shipping_method'])
+
+ clean_shipping_method(
+ checkout, shipping_method, errors, info.context.discounts,
+ info.context.taxes)
+ if errors:
+ return CheckoutShippingMethodUpdate(errors=errors)
+
+ checkout.shipping_method = shipping_method
+ checkout.save(update_fields=['shipping_method'])
return CheckoutShippingMethodUpdate(checkout=checkout, errors=errors)
@@ -277,7 +350,6 @@ class CheckoutComplete(BaseMutation):
errors = []
checkout = cls.get_node_or_error(
info, checkout_id, errors, 'checkout_id', only_type=Checkout)
- # Check if checkout is ready
if not checkout:
return CheckoutComplete(errors=errors)
ready, checkout_error = ready_to_place_order(checkout)
@@ -289,13 +361,11 @@ class CheckoutComplete(BaseMutation):
order = create_order(
cart=checkout,
tracking_code=analytics.get_client_id(info.context),
- # discounts=request.discounts, # FIXME
- # taxes=get_taxes_for_cart(cart, request.taxes) # FIXME
- taxes=None,
- discounts=None)
+ discounts=info.context.discounts,
+ taxes=get_taxes_for_cart(checkout, info.context.taxes))
except InsufficientStock:
order = None
cls.add_error(
- field=None, message='Insufficient product stock',
+ field=None, message='Insufficient product stock.',
errors=errors)
return CheckoutComplete(order=order, errors=errors)
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 939a6a1ce0..49e689163c 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -1,18 +1,22 @@
import graphene
from ...checkout import models
+from ...core.utils.taxes import get_taxes_for_address
from ..core.types.common import CountableDjangoObjectType
from ..core.types.money import TaxedMoney
-from ...core.utils.taxes import get_taxes_for_address
class CheckoutLine(CountableDjangoObjectType):
- total_price = graphene.Field(TaxedMoney, description='Total price')
- requires_shipping = graphene.Boolean(description='Line requires shipping')
+ total_price = graphene.Field(
+ TaxedMoney,
+ description=(
+ 'The sum of the checkout line price, taxes and discounts.'))
+ requires_shipping = graphene.Boolean(
+ description='Indicates whether the item need to be delivered.')
class Meta:
exclude_fields = ['cart', 'data']
- description = 'Represents user address data.'
+ description = 'Represents an item in the checkout.'
interfaces = [graphene.relay.Node]
model = models.CartLine
filter_fields = ['id']
@@ -26,10 +30,22 @@ class CheckoutLine(CountableDjangoObjectType):
class Checkout(CountableDjangoObjectType):
- total_price = graphene.Field(TaxedMoney, description='Total price')
+ total_price = graphene.Field(
+ TaxedMoney,
+ description=(
+ 'The sum of the the checkout line prices, with all the taxes,'
+ 'shipping costs, and discounts included.'))
subtotal_price = graphene.Field(
- TaxedMoney, description='Total without shipping')
- shipping_price = graphene.Field(TaxedMoney, description='Shipping price')
+ TaxedMoney,
+ description=(
+ 'The price of the checkout before shipping, with taxes included.'))
+ shipping_price = graphene.Field(
+ TaxedMoney,
+ description='The price of the shipping, with all the taxes included.')
+ lines = graphene.List(
+ CheckoutLine, description=(
+ 'A list of checkout lines, each containing information about '
+ 'an item in the checkout.'))
class Meta:
description = 'Checkout object'
@@ -48,3 +64,6 @@ class Checkout(CountableDjangoObjectType):
def resolve_shipping_price(self, info):
taxes = get_taxes_for_address(self.shipping_address)
return self.get_shipping_price(taxes=taxes)
+
+ def resolve_lines(self, info):
+ return self.lines.prefetch_related('variant')
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index da1e0f3f7a..2b5cd973a8 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -137,12 +137,8 @@ class OrderUpdate(DraftOrderUpdate):
def save(cls, info, instance, cleaned_input):
super().save(info, instance, cleaned_input)
if instance.user_email:
- try:
- user = User.objects.get(email=instance.user_email)
- except User.DoesNotExist:
- instance.user = None
- else:
- instance.user = user
+ user = User.objects.filter(email=instance.user_email).first()
+ instance.user = user
instance.save()
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index a33c47b72a..e7c3625cd1 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -9,7 +9,7 @@ PaymentGatewayEnum = graphene.Enum.from_enum(PROVIDERS_ENUM)
class PaymentMethod(CountableDjangoObjectType):
class Meta:
- description = 'Payment method'
+ description = 'Represents a payment method of a given type.'
interfaces = [relay.Node]
model = models.PaymentMethod
filter_fields = ['id']
@@ -17,7 +17,7 @@ class PaymentMethod(CountableDjangoObjectType):
class Transaction(CountableDjangoObjectType):
class Meta:
- description = 'Single payment transaction'
+ description = 'An object representing a single payment.'
interfaces = [relay.Node]
model = models.Transaction
filter_fields = ['id']
diff --git a/saleor/order/views.py b/saleor/order/views.py
index 5552f7b3da..a84589071a 100644
--- a/saleor/order/views.py
+++ b/saleor/order/views.py
@@ -10,7 +10,7 @@ from django.template.response import TemplateResponse
from django.urls import reverse
from django.utils.translation import pgettext_lazy
from django.views.decorators.csrf import csrf_exempt
-from payments import PaymentStatus, RedirectNeeded
+from payments import PaymentStatus
from . import FulfillmentStatus
from ..account.forms import LoginForm
@@ -30,7 +30,7 @@ def details(request, token):
note_form = None
orders = Order.objects.confirmed().prefetch_related(
'lines__variant__images', 'lines__variant__product__images',
- 'fulfillments__lines', 'fulfillments__lines__order_line')
+ 'fulfillments__lines__order_line')
orders = orders.select_related(
'billing_address', 'shipping_address', 'user')
order = get_object_or_404(orders, token=token)
@@ -109,7 +109,7 @@ def start_payment(request, order, variant):
raise Http404('%r is not a valid payment variant' % (variant,))
with transaction.atomic():
# FIXME: temporary solution, should be adapted to new API
- payment_method, dummy_created = PaymentMethod.objects.get_or_create(
+ payment_method, _ = PaymentMethod.objects.get_or_create(
variant=variant, is_active=True, order=order, defaults=defaults)
form = PaymentMethodForm(
data=request.POST or None, instance=payment_method)
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 81bf487437..4e463bc894 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -33,7 +33,7 @@ class PaymentMethod(models.Model):
extra_data = models.TextField(blank=True, default='')
token = models.CharField(max_length=36, blank=True, default='')
- # refactor to MoneyField
+ # FIXME refactor to MoneyField
total = models.DecimalField(
max_digits=9, decimal_places=2, default=Decimal('0.0'))
currency = models.CharField(max_length=10)
@@ -47,7 +47,7 @@ class PaymentMethod(models.Model):
on_delete=models.SET_NULL)
order = models.ForeignKey(
Order, null=True, related_name='payment_methods',
- on_delete=models.CASCADE)
+ on_delete=models.PROTECT)
def _get_money(self, amount):
return Money(amount=amount, currency=self.currency)
@@ -67,33 +67,34 @@ class PaymentMethod(models.Model):
return txn
def authorize(self, client_token):
- # FIXME
+ # FIXME Used for backwards compatibility, remove after moving to
+ # dashboard 2.0
from . import utils
return utils.gateway_authorize(
payment_method=self, transaction_token=client_token)
def void(self):
- # FIXME
+ # FIXME Used for backwards compatibility, remove after moving to
+ # dashboard 2.0
from . import utils
-
return utils.gateway_void(payment_method=self)
def charge(self, amount=None):
- # FIXME
+ # FIXME Used for backwards compatibility, remove after moving to
+ # dashboard 2.0
from . import utils
-
return utils.gateway_charge(payment_method=self, amount=amount)
def refund(self, amount=None):
- # FIXME
+ # FIXME Used for backwards compatibility, remove after moving to
+ # dashboard 2.0
from . import utils
-
return utils.gateway_refund(payment_method=self, amount=amount)
class Transaction(models.Model):
payment_method = models.ForeignKey(
- PaymentMethod, related_name='transactions', on_delete=models.CASCADE)
+ PaymentMethod, related_name='transactions', on_delete=models.PROTECT)
token = models.CharField(max_length=64, blank=True, default='')
transaction_type = models.CharField(
max_length=10, choices=TransactionType.CHOICES)
diff --git a/saleor/payment/providers/braintree/__init__.py b/saleor/payment/providers/braintree/__init__.py
index d1e378bd8c..b39d433016 100644
--- a/saleor/payment/providers/braintree/__init__.py
+++ b/saleor/payment/providers/braintree/__init__.py
@@ -1,23 +1,20 @@
-import uuid
from typing import Dict
import braintree as braintree_sdk
-from django.db import transaction
from django.utils.translation import pgettext_lazy
-from ... import PaymentMethodChargeStatus, TransactionType
-from ...models import Transaction
+from ... import TransactionType
from ...utils import create_transaction
-#FIXME: Move to SiteSettings
+# FIXME: Move to SiteSettings
AUTO_CHARGE = False
THREE_D_SECURE_REQUIRED = False
+
def get_error_for_client(errors):
- """
- Filters all error messages and decides which one is visible for the
- client side
+ """Filters all error messages and decides which one is visible for the
+ client side.
"""
if not errors:
return ''
@@ -25,7 +22,8 @@ def get_error_for_client(errors):
default_msg = pgettext_lazy(
'payment error',
'Unable to process transaction. Please try again in a moment')
- error_codes_whitelist = [] #FIXME: Provide list of visible errors and messages translations
+ # FIXME: Provide list of visible errors and messages translations
+ error_codes_whitelist = []
for error in errors:
if error['code'] in error_codes_whitelist:
return error['message']
@@ -33,27 +31,24 @@ def get_error_for_client(errors):
def extract_gateway_response(braintree_result) -> Dict:
- """
- Extract data from Braintree response that will be stored locally
- """
- errors = {}
+ """Extract data from Braintree response that will be stored locally."""
+ errors = []
if not braintree_result.is_success:
- errors = [{
- 'code': error.code,
- 'message': error.message}
- for error in braintree_result.errors.deep_errors]
+ errors = [
+ {'code': error.code, 'message': error.message}
+ for error in braintree_result.errors.deep_errors]
- transaction = braintree_result.transaction
+ bt_transaction = braintree_result.transaction
gateway_response = {
- 'credit_card': braintree_result.transaction.credit_card,
- 'additional_processor_response': transaction.additional_processor_response,
- 'gateway_rejection_reason': transaction.gateway_rejection_reason,
- 'processor_response_code': transaction.processor_response_code,
- 'processor_response_text': transaction.processor_response_text,
- 'processor_settlement_response_code': transaction.processor_settlement_response_code,
- 'processor_settlement_response_text': transaction.processor_settlement_response_text,
- 'risk_data': transaction.risk_data,
- 'status': transaction.status,
+ 'credit_card': bt_transaction.credit_card,
+ 'additional_processor_response': bt_transaction.additional_processor_response, # noqa
+ 'gateway_rejection_reason': bt_transaction.gateway_rejection_reason,
+ 'processor_response_code': bt_transaction.processor_response_code,
+ 'processor_response_text': bt_transaction.processor_response_text,
+ 'processor_settlement_response_code': bt_transaction.processor_settlement_response_code, # noqa
+ 'processor_settlement_response_text': bt_transaction.processor_settlement_response_text, # noqa
+ 'risk_data': bt_transaction.risk_data,
+ 'status': bt_transaction.status,
'errors': errors}
return gateway_response
@@ -87,8 +82,7 @@ def authorize(payment_method, transaction_token, **client_kwargs):
transaction_token,
'options': {
'submit_for_settlement': AUTO_CHARGE,
- 'three_d_secure': {
- 'required': THREE_D_SECURE_REQUIRED}}})
+ 'three_d_secure': {'required': THREE_D_SECURE_REQUIRED}}})
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response['errors'])
txn = create_transaction(
diff --git a/saleor/payment/providers/dummy/__init__.py b/saleor/payment/providers/dummy/__init__.py
index 58eaf87254..c869555190 100644
--- a/saleor/payment/providers/dummy/__init__.py
+++ b/saleor/payment/providers/dummy/__init__.py
@@ -1,9 +1,6 @@
import uuid
-from django.db import transaction
-from django.utils.translation import pgettext_lazy
-
-from ... import PaymentMethodChargeStatus, TransactionType
+from ... import TransactionType
from ...utils import create_transaction
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 806c4913db..c3da4775c1 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -55,13 +55,13 @@ def gateway_authorize(payment_method, transaction_token) -> Transaction:
def gateway_charge(payment_method, amount) -> Transaction:
if not payment_method.is_active:
raise PaymentError('This payment method is no longer active')
- if not payment_method.charge_status in {
+ if payment_method.charge_status not in {
PaymentMethodChargeStatus.CHARGED,
PaymentMethodChargeStatus.NOT_CHARGED}:
raise PaymentError('This payment method cannot be charged')
if amount > payment_method.total or amount > (
payment_method.total - payment_method.captured_amount):
- raise PaymentError('Unable to charge more than authozied amount')
+ raise PaymentError('Unable to charge more than authorized amount')
provider, provider_params = get_provider(payment_method.variant)
with transaction.atomic():
txn, error = provider.charge(
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index 34159f715d..044ee7fa48 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -78,13 +78,9 @@ def test_checkout_lines_add(user_api_client, cart_with_item, variant):
checkout {
token
lines {
- edges {
- node {
- quantity
- variant {
- id
- }
- }
+ quantity
+ variant {
+ id
}
}
}
@@ -125,13 +121,9 @@ def test_checkout_lines_update(user_api_client, cart_with_item):
checkout {
token
lines {
- edges {
- node {
- quantity
- variant {
- id
- }
- }
+ quantity
+ variant {
+ id
}
}
}
@@ -173,13 +165,9 @@ def test_checkout_line_delete(user_api_client, cart_with_item):
checkout {
token
lines {
- edges {
- node {
- quantity
- variant {
- id
- }
- }
+ quantity
+ variant {
+ id
}
}
}
@@ -407,15 +395,11 @@ def test_fetch_checkout_by_token(user_api_client, cart_with_item):
checkout(token: $token) {
token,
lines {
- edges {
- node {
- variant {
- product {
- name
- }
- }
- }
- }
+ variant {
+ product {
+ name
+ }
+ }
}
}
}
@@ -432,18 +416,7 @@ def test_fetch_checkout_invalid_token(user_api_client):
query = """
query getCheckout($token: UUID!) {
checkout(token: $token) {
- token,
- lines {
- edges {
- node {
- variant {
- product {
- name
- }
- }
- }
- }
- }
+ token
}
}
"""
@@ -472,16 +445,12 @@ def test_checkout_prices(user_api_client, cart_with_item):
}
}
lines {
- edges {
- node {
- totalPrice {
- currency
- gross {
- amount
- }
- }
- }
- }
+ totalPrice {
+ currency
+ gross {
+ amount
+ }
+ }
}
}
}
diff --git a/tests/conftest.py b/tests/conftest.py
index f2ef16ec47..762bf93a91 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -111,6 +111,7 @@ def graphql_address_data():
'city': 'New York',
'countryArea': ''}
+
@pytest.fixture
def customer_user(address): # pylint: disable=W0613
default_address = address.get_copy()
@@ -481,6 +482,7 @@ def payment_preauth(order_with_lines):
total=order_with_lines.total.gross.amount,
tax=order_with_lines.total.tax.amount)
+
@pytest.fixture()
def payment_method_txn_preauth(order_with_lines, payment_method_dummy):
order = order_with_lines
@@ -496,6 +498,7 @@ def payment_method_txn_preauth(order_with_lines, payment_method_dummy):
is_success=True)
return payment
+
@pytest.fixture()
def payment_method_txn_charged(order_with_lines, payment_method_dummy):
order = order_with_lines
@@ -513,6 +516,7 @@ def payment_method_txn_charged(order_with_lines, payment_method_dummy):
is_success=True)
return payment
+
@pytest.fixture()
def payment_method_txn_refunded(order_with_lines, payment_method_dummy):
order = order_with_lines
@@ -531,6 +535,7 @@ def payment_method_txn_refunded(order_with_lines, payment_method_dummy):
is_success=True)
return payment
+
@pytest.fixture()
def payment_confirmed(order_with_lines):
order_amount = order_with_lines.total_gross.amount
@@ -776,6 +781,7 @@ def product_translation_fr(product):
language_code='fr', product=product, name='French name',
description='French description')
+
@pytest.fixture
def payment_method_dummy(db):
return PaymentMethod.objects.create(
diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.py
index 53d31d515a..e412cbb592 100644
--- a/tests/dashboard/test_order.py
+++ b/tests/dashboard/test_order.py
@@ -98,20 +98,20 @@ def test_view_capture_order_invalid_payment_confirmed_status(
assert order.payment_methods.last().charge_status == PaymentMethodChargeStatus.CHARGED
-# @pytest.mark.integration
-# def test_view_capture_order_invalid_payment_rejected_status(
-# admin_client, order_with_lines, payment_rejected):
-# order = order_with_lines
-# url = reverse(
-# 'dashboard:capture-payment', kwargs={
-# 'order_pk': order.pk, 'payment_pk': payment_rejected.pk})
-# response = admin_client.get(url)
-# assert response.status_code == 200
-
-# response = admin_client.post(
-# url, {'csrfmiddlewaretoken': 'hello', 'amount': '20.00'})
-# assert response.status_code == 400
-# assert order.payments.last().status == PaymentStatus.REJECTED
+def test_view_capture_order_invalid_payment_rejected_status(
+ admin_client, order_with_lines, payment_rejected):
+ order = order_with_lines
+ url = reverse(
+ 'dashboard:capture-payment', kwargs={
+ 'order_pk': order.pk, 'payment_pk': payment_rejected.pk})
+ response = admin_client.get(url)
+ assert response.status_code == 200
+
+ response = admin_client.post(
+ url, {'csrfmiddlewaretoken': 'hello', 'amount': '20.00'})
+ assert response.status_code == 400
+ assert order.payments.last().status == PaymentStatus.REJECTED
@pytest.mark.integration