Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Init for locking checkoutComplete
Maciej Korycinski5bbe330446ba
diff --git a/saleor/checkout/migrations/0028_auto_20200824_1019.py b/saleor/checkout/migrations/0028_auto_20200824_1019.pynew file mode 100644index 0000000000..4c9eb6416b--- /dev/null+++ b/saleor/checkout/migrations/0028_auto_20200824_1019.py@@ -0,0 +1,23 @@+# Generated by Django 3.1 on 2020-08-24 10:19++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("checkout", "0027_auto_20200810_1415"),+ ]++ operations = [+ migrations.AddField(+ model_name="checkout",+ name="redirect_url",+ field=models.URLField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="checkout",+ name="tracking_code",+ field=models.CharField(blank=True, max_length=255, null=True),+ ),+ ]diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex 6bd845be77..388445394c 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -96,6 +96,9 @@ class Checkout(ModelWithMetadata):voucher_code = models.CharField(max_length=12, blank=True, null=True)gift_cards = models.ManyToManyField(GiftCard, blank=True, related_name="checkouts")+ redirect_url = models.URLField(blank=True, null=True)+ tracking_code = models.CharField(max_length=255, blank=True, null=True)+objects = CheckoutQueryset.as_manager()class Meta:diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.pyindex b7fd562647..20f894fa8a 100644--- a/saleor/checkout/tests/test_checkout.py+++ b/saleor/checkout/tests/test_checkout.py@@ -105,19 +105,17 @@ def test_create_order_captured_payment_creates_expected_events(checkout.shipping_address = customer_user.default_shipping_addresscheckout.shipping_method = shipping_methodcheckout.payments.add(payment_txn_captured)+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"checkout.save()# Place checkoutorder = create_order(checkout=checkout,order_data=prepare_order_data(- checkout=checkout,- lines=list(checkout),- tracking_code="tracking_code",- discounts=None,+ checkout=checkout, lines=list(checkout), discounts=None,),user=customer_user,- redirect_url="https://www.example.com",)flush_post_commit_hooks()@@ -228,19 +226,17 @@ def test_create_order_captured_payment_creates_expected_events_anonymous_user(checkout.shipping_address = customer_user.default_shipping_addresscheckout.shipping_method = shipping_methodcheckout.payments.add(payment_txn_captured)+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"checkout.save()# Place checkoutorder = create_order(checkout=checkout,order_data=prepare_order_data(- checkout=checkout,- lines=list(checkout),- tracking_code="tracking_code",- discounts=None,+ checkout=checkout, lines=list(checkout), discounts=None,),user=AnonymousUser(),- redirect_url="https://www.example.com",)flush_post_commit_hooks()@@ -343,19 +339,17 @@ def test_create_order_preauth_payment_creates_expected_events(checkout.shipping_address = customer_user.default_shipping_addresscheckout.shipping_method = shipping_methodcheckout.payments.add(payment_txn_preauth)+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"checkout.save()# Place checkoutorder = create_order(checkout=checkout,order_data=prepare_order_data(- checkout=checkout,- lines=list(checkout),- tracking_code="tracking_code",- discounts=None,+ checkout=checkout, lines=list(checkout), discounts=None,),user=customer_user,- redirect_url="https://www.example.com",)flush_post_commit_hooks()@@ -437,19 +431,17 @@ def test_create_order_preauth_payment_creates_expected_events_anonymous_user(checkout.shipping_address = customer_user.default_shipping_addresscheckout.shipping_method = shipping_methodcheckout.payments.add(payment_txn_preauth)+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"checkout.save()# Place checkoutorder = create_order(checkout=checkout,order_data=prepare_order_data(- checkout=checkout,- lines=list(checkout),- tracking_code="tracking_code",- discounts=None,+ checkout=checkout, lines=list(checkout), discounts=None,),user=AnonymousUser(),- redirect_url="https://www.example.com",)flush_post_commit_hooks()@@ -515,14 +507,12 @@ def test_create_order_insufficient_stock(checkout.user = customer_usercheckout.billing_address = customer_user.default_billing_addresscheckout.shipping_address = customer_user.default_billing_address+ checkout.tracking_code = "tracking_code"checkout.save()with pytest.raises(InsufficientStock):prepare_order_data(- checkout=checkout,- lines=list(checkout),- tracking_code="tracking_code",- discounts=None,+ checkout=checkout, lines=list(checkout), discounts=None,)@@ -534,25 +524,21 @@ def test_create_order_doesnt_duplicate_order(checkout.billing_address = customer_user.default_billing_addresscheckout.shipping_address = customer_user.default_billing_addresscheckout.shipping_method = shipping_method+ checkout.tracking_code = ""+ checkout.redirect_url = "https://www.example.com"checkout.save()order_data = prepare_order_data(- checkout=checkout, lines=list(checkout), tracking_code="", discounts=None+ checkout=checkout, lines=list(checkout), discounts=None)order_1 = create_order(- checkout=checkout,- order_data=order_data,- user=customer_user,- redirect_url="https://www.example.com",+ checkout=checkout, order_data=order_data, user=customer_user,)assert order_1.checkout_token == checkout.tokenorder_2 = create_order(- checkout=checkout,- order_data=order_data,- user=customer_user,- redirect_url="https://www.example.com",+ checkout=checkout, order_data=order_data, user=customer_user,)assert order_1.pk == order_2.pk@@ -567,6 +553,8 @@ def test_create_order_with_gift_card(checkout.billing_address = customer_user.default_billing_addresscheckout.shipping_address = customer_user.default_billing_addresscheckout.shipping_method = shipping_method+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"checkout.save()lines = list(checkout)@@ -581,14 +569,8 @@ def test_create_order_with_gift_card(order = create_order(checkout=checkout,- order_data=prepare_order_data(- checkout=checkout,- lines=lines,- tracking_code="tracking_code",- discounts=None,- ),+ order_data=prepare_order_data(checkout=checkout, lines=lines, discounts=None,),user=customer_user if not is_anonymous_user else AnonymousUser(),- redirect_url="https://www.example.com",)assert order.gift_cards.count() == 1@@ -604,6 +586,8 @@ def test_create_order_with_gift_card_partial_use(checkout.billing_address = customer_user.default_billing_addresscheckout.shipping_address = customer_user.default_billing_addresscheckout.shipping_method = shipping_method+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"checkout.save()price_without_gift_card = calculations.checkout_total(@@ -617,13 +601,9 @@ def test_create_order_with_gift_card_partial_use(order = create_order(checkout=checkout,order_data=prepare_order_data(- checkout=checkout,- lines=list(checkout),- tracking_code="tracking_code",- discounts=None,+ checkout=checkout, lines=list(checkout), discounts=None,),user=customer_user,- redirect_url="https://www.example.com",)gift_card_used.refresh_from_db()@@ -649,6 +629,8 @@ def test_create_order_with_many_gift_cards(checkout.billing_address = customer_user.default_billing_addresscheckout.shipping_address = customer_user.default_billing_addresscheckout.shipping_method = shipping_method+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"checkout.save()price_without_gift_card = calculations.checkout_total(@@ -666,13 +648,9 @@ def test_create_order_with_many_gift_cards(order = create_order(checkout=checkout,order_data=prepare_order_data(- checkout=checkout,- lines=list(checkout),- tracking_code="tracking_code",- discounts=None,+ checkout=checkout, lines=list(checkout), discounts=None,),user=customer_user,- redirect_url="https://www.example.com",)gift_card_created_by_staff.refresh_from_db()@@ -689,17 +667,15 @@ def test_create_order_with_many_gift_cards(def test_note_in_created_order(checkout_with_item, address, customer_user):checkout_with_item.shipping_address = addresscheckout_with_item.note = "test_note"+ checkout_with_item.tracking_code = "tracking_code"+ checkout_with_item.redirect_url = "https://www.example.com"checkout_with_item.save()order = create_order(checkout=checkout_with_item,order_data=prepare_order_data(- checkout=checkout_with_item,- lines=list(checkout_with_item),- tracking_code="tracking_code",- discounts=None,+ checkout=checkout_with_item, lines=list(checkout_with_item), discounts=None,),user=customer_user,- redirect_url="https://www.example.com",)assert order.customer_note == checkout_with_item.notediff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 1b334e45dd..0f8c4769a7 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -2,6 +2,7 @@from datetime import datefrom decimal import Decimalfrom typing import Iterable, List, Optional, Tuple+from uuid import UUIDfrom django.core.exceptions import ValidationErrorfrom django.db import transaction@@ -636,7 +637,7 @@ def create_line_for_order(checkout_line: "CheckoutLine", discounts) -> OrderLinedef prepare_order_data(- *, checkout: Checkout, lines: Iterable[CheckoutLine], tracking_code: str, discounts+ *, checkout: Checkout, lines: Iterable[CheckoutLine], discounts) -> dict:"""Run checks and return all the data from a given checkout to create an order.@@ -660,7 +661,7 @@ def prepare_order_data(order_data.update({"language_code": get_language(),- "tracking_client_id": tracking_code,+ "tracking_client_id": checkout.tracking_code or "","total": taxed_total,})@@ -695,9 +696,17 @@ def abort_order_data(order_data: dict):remove_voucher_usage_by_customer(voucher, order_data["user_email"])+def get_order(checkout_token: UUID) -> Optional[Order]:+ """Get order based on checkout token."""+ order = Order.objects.confirmed().filter(checkout_token=checkout_token).first()+ if order is not None:+ return order+ return None++@transaction.atomicdef create_order(- *, checkout: Checkout, order_data: dict, user: User, redirect_url: str+ *, checkout: Checkout, order_data: dict, user: User # type: ignore) -> Order:"""Create an order from the checkout.@@ -744,10 +753,10 @@ def create_order(# Send the order confirmation emailtransaction.on_commit(- lambda: send_order_confirmation.delay(order.pk, redirect_url, user.pk)+ lambda: send_order_confirmation.delay(order.pk, checkout.redirect_url, user.pk))transaction.on_commit(- lambda: send_staff_order_confirmation.delay(order.pk, redirect_url)+ lambda: send_staff_order_confirmation.delay(order.pk, checkout.redirect_url))return orderdiff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 50150ddc8b..2db033a13d 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -1,12 +1,14 @@-from typing import List, Optional, Tuple+from typing import List, Optional, Tuple, Unionimport graphenefrom django.conf import settings+from django.contrib.auth.models import AnonymousUserfrom django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.db import transactionfrom django.db.models import Prefetchfrom ...account.error_codes import AccountErrorCode+from ...account.models import Userfrom ...checkout import modelsfrom ...checkout.calculations import calculate_checkout_total_with_gift_cardsfrom ...checkout.error_codes import CheckoutErrorCode@@ -17,6 +19,7 @@ from ...checkout.utils import (change_billing_address_in_checkout,change_shipping_address_in_checkout,create_order,+ get_order,get_user_checkout,get_valid_shipping_methods_for_checkout,prepare_order_data,@@ -28,10 +31,10 @@ from ...core.exceptions import InsufficientStock, PermissionDenied, ProductNotPufrom ...core.permissions import OrderPermissionsfrom ...core.taxes import TaxErrorfrom ...core.utils.url import validate_storefront_url-from ...discount import models as voucher_model+from ...discount import DiscountInfo, models as voucher_modelfrom ...graphql.checkout.utils import clean_checkout_payment, clean_checkout_shipping+from ...order import models as order_modelsfrom ...payment import PaymentError, gateway, models as payment_models-from ...payment.interface import AddressDatafrom ...payment.utils import store_customer_idfrom ...product import models as product_modelsfrom ...warehouse.availability import check_stock_quantity, get_available_quantity@@ -789,28 +792,11 @@ class CheckoutComplete(BaseMutation):)@classmethod- def perform_mutation(cls, _root, info, checkout_id, store_source, **data):- checkout = cls.get_node_or_error(- info,- checkout_id,- only_type=Checkout,- field="checkout_id",- qs=models.Checkout.objects.prefetch_related(- "gift_cards",- "lines",- Prefetch(- "payments",- queryset=payment_models.Payment.objects.prefetch_related(- "order", "order__lines"- ),- ),- ).select_related("shipping_method", "shipping_method__shipping_zone"),- )+ @transaction.atomic+ def _prepare_checkout(cls, checkout: models.Checkout, context, redirect_url):lines = list(checkout)- discounts = info.context.discounts- user = info.context.user-+ discounts = context.discountsclean_checkout_shipping(checkout, lines, discounts, CheckoutErrorCode)clean_checkout_payment(checkout, lines, discounts, CheckoutErrorCode)@@ -818,80 +804,144 @@ class CheckoutComplete(BaseMutation):cls.validate_payment_amount(discounts, payment, checkout)- redirect_url = data.get("redirect_url", "")if redirect_url:try:validate_storefront_url(redirect_url)except ValidationError as error:raise ValidationError(- {"redirect_url": error}, code=AccountErrorCode.INVALID+ {"redirect_url": error}, code=AccountErrorCode.INVALID.value)- with transaction.atomic():- try:- order_data = prepare_order_data(- checkout=checkout,- lines=lines,- tracking_code=analytics.get_client_id(info.context),- discounts=discounts,- )- except InsufficientStock as e:- gateway.payment_refund_or_void(payment)- raise ValidationError(- f"Insufficient product stock: {e.item}", code=e.code- )- except voucher_model.NotApplicable:- raise ValidationError(- "Voucher not applicable",- code=CheckoutErrorCode.VOUCHER_NOT_APPLICABLE,- )- except TaxError as tax_error:- raise ValidationError(- "Unable to calculate taxes - %s" % str(tax_error),- code=CheckoutErrorCode.TAX_ERROR,- )+ to_update = []+ if redirect_url and redirect_url != checkout.redirect_url:+ checkout.redirect_url = redirect_url+ to_update.append("redirect_url")- billing_address = order_data["billing_address"]- shipping_address = order_data.get("shipping_address", None)+ tracking_code = analytics.get_client_id(context)+ if tracking_code and tracking_code != checkout.tracking_code:+ checkout.tracking_code = tracking_code+ to_update.append("tracking_code")- billing_address = AddressData(**billing_address.as_data())+ if to_update:+ checkout.save()- if shipping_address is not None:- shipping_address = AddressData(**shipping_address.as_data())+ @classmethod+ @transaction.atomic+ def _convert_checkout_to_order(+ cls,+ checkout: models.Checkout,+ order_data: dict,+ user: Union[User, AnonymousUser],+ ) -> order_models.Order:+ order = create_order(+ checkout=checkout, order_data=order_data, user=user # type: ignore+ )+ # remove checkout after order is successfully created+ checkout.delete()+ return order++ @classmethod+ def _get_order_data(+ cls, checkout: models.Checkout, discounts: List[DiscountInfo]+ ) -> dict:+ try:+ with transaction.atomic():+ order_data = prepare_order_data(+ checkout=checkout, lines=list(checkout), discounts=discounts,+ )+ except InsufficientStock as e:+ raise ValidationError(f"Insufficient product stock: {e.item}", code=e.code)+ except voucher_model.NotApplicable:+ raise ValidationError(+ "Voucher not applicable",+ code=CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.value,+ )+ except TaxError as tax_error:+ raise ValidationError(+ "Unable to calculate taxes - %s" % str(tax_error),+ code=CheckoutErrorCode.TAX_ERROR.value,+ )+ return order_data+ @classmethod+ def _process_payment(+ cls,+ payment: payment_models.Payment,+ store_source: bool,+ payment_data: Optional[dict],+ order_data: dict,+ ) -> payment_models.Transaction:payment_confirmation = payment.to_confirmtry:if payment_confirmation:- txn = gateway.confirm(payment, additional_data=data.get("payment_data"))+ txn = gateway.confirm(payment, additional_data=payment_data)else:txn = gateway.process_payment(payment=payment,token=payment.token,store_source=store_source,- additional_data=data.get("payment_data"),+ additional_data=payment_data,)if not txn.is_success:raise PaymentError(txn.error)-except PaymentError as e:abort_order_data(order_data)- raise ValidationError(str(e), code=CheckoutErrorCode.PAYMENT_ERROR)+ raise ValidationError(str(e), code=CheckoutErrorCode.PAYMENT_ERROR.value)+ return txn- if txn.customer_id and user.is_authenticated:- store_customer_id(user, payment.gateway, txn.customer_id)+ @classmethod+ def complete_checkout(cls, checkout: models.Checkout, context, data, store_source):+ order = get_order(checkout.token)+ if order:+ return CheckoutComplete(+ order=order, confirmation_needed=False, confirmation_data={},+ )+ cls._prepare_checkout(+ checkout=checkout,+ context=context,+ redirect_url=data.get("redirect_url", ""),+ )++ payment = checkout.get_last_active_payment() # type: ignore- order = None+ try:+ order_data = cls._get_order_data(checkout, context.discounts)+ except ValidationError as error:+ gateway.payment_refund_or_void(payment)+ raise error++ txn = cls._process_payment(+ payment=payment, # type: ignore+ store_source=store_source,+ payment_data=data.get("payment_data"),+ order_data=order_data,+ )++ user = context.user+ if txn.customer_id and user.is_authenticated:+ store_customer_id(user, payment.gateway, txn.customer_id) # type: ignoreif not txn.action_required:- order = create_order(- checkout=checkout,- order_data=order_data,- user=user,- redirect_url=redirect_url,- )+ try:+ with transaction.atomic():+ order = get_order(checkout.token)+ if order:+ # Order was created asynchronously, we can release the lock made+ # on order_data+ abort_order_data(order_data)+ else:+ order = cls._convert_checkout_to_order(+ checkout=checkout, order_data=order_data, user=user+ )+ except InsufficientStock as e:+ abort_order_data(order_data)+ gateway.payment_refund_or_void(payment)+ raise ValidationError(+ f"Insufficient product stock: {e.item}", code=e.code+ )- # remove checkout after order is successfully paid- checkout.delete()+ if not order:+ abort_order_data(order_data)# If gateway returns information that additional steps are required we need# to inform the frontend and pass all required data@@ -901,6 +951,40 @@ class CheckoutComplete(BaseMutation):confirmation_data=txn.action_required_data if txn.action_required else {},)+ @classmethod+ def perform_mutation(cls, _root, info, checkout_id, store_source, **data):+ checkout_token = from_global_id_strict_type(+ checkout_id, Checkout, field="checkout_id"+ )+ order = get_order(checkout_token)+ if order:+ # The order is already created. We return it as a success checkoutComplete+ # response. Order is anonymized for not logged in user+ return CheckoutComplete(+ order=order, confirmation_needed=False, confirmation_data={}+ )++ with transaction.atomic():+ checkout = cls.get_node_or_error(+ info,+ checkout_id,+ only_type=Checkout,+ field="checkout_id",+ qs=models.Checkout.objects.select_for_update(of=("self",))+ .prefetch_related(+ "gift_cards",+ "lines",+ Prefetch(+ "payments",+ queryset=payment_models.Payment.objects.prefetch_related(+ "order", "order__lines"+ ),+ ),+ )+ .select_related("shipping_method", "shipping_method__shipping_zone"),+ )+ return cls.complete_checkout(checkout, info.context, data, store_source)+class CheckoutAddPromoCode(BaseMutation):checkout = graphene.Field(diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 0b1a759ea3..fa049c3967 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -15,15 +15,11 @@ from ....checkout.error_codes import CheckoutErrorCodefrom ....checkout.models import Checkoutfrom ....checkout.utils import add_variant_to_checkoutfrom ....core.payments import PaymentInterface-from ....core.taxes import zero_money-from ....order.models import Order-from ....payment import ChargeStatus, TransactionKind-from ....payment.gateways.dummy_credit_card import TOKEN_VALIDATION_MAPPING+from ....payment import TransactionKindfrom ....payment.interface import GatewayResponsefrom ....plugins.manager import PluginsManagerfrom ....plugins.tests.sample_plugins import ActiveDummyPaymentGatewayfrom ....warehouse.models import Stock-from ....warehouse.tests.utils import get_available_quantity_for_stockfrom ...tests.utils import assert_no_permission, get_graphql_contentfrom ..mutations import (clean_shipping_method,@@ -1665,302 +1661,6 @@ def test_checkout_email_update_validation(user_api_client, checkout_with_item):assert checkout_errors[0]["code"] == CheckoutErrorCode.REQUIRED.name-MUTATION_CHECKOUT_COMPLETE = """- mutation checkoutComplete($checkoutId: ID!, $redirectUrl: String) {- checkoutComplete(checkoutId: $checkoutId, redirectUrl: $redirectUrl) {- order {- id,- token- },- checkoutErrors {- field,- message,- code- }- confirmationNeeded- confirmationData- }- }- """---def test_checkout_complete(- user_api_client,- checkout_with_gift_card,- gift_card,- payment_dummy,- address,- shipping_method,-):-- assert not gift_card.last_used_on-- checkout = checkout_with_gift_card- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.billing_address = address- checkout.store_value_in_metadata(items={"accepted": "true"})- checkout.store_value_in_private_metadata(items={"accepted": "false"})- checkout.save()-- checkout_line = checkout.lines.first()- checkout_line_quantity = checkout_line.quantity- checkout_line_variant = checkout_line.variant-- total = calculations.calculate_checkout_total_with_gift_cards(checkout=checkout)- payment = payment_dummy- payment.is_active = True- payment.order = None- payment.total = total.gross.amount- payment.currency = total.gross.currency- payment.checkout = checkout- payment.save()- assert not payment.transactions.exists()-- orders_count = Order.objects.count()- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)- variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)-- content = get_graphql_content(response)- data = content["data"]["checkoutComplete"]- assert not data["checkoutErrors"]-- order_token = data["order"]["token"]- assert Order.objects.count() == orders_count + 1- order = Order.objects.first()- assert order.token == order_token- assert order.total.gross == total.gross- assert order.metadata == checkout.metadata- assert order.private_metadata == checkout.private_metadata-- order_line = order.lines.first()- assert checkout_line_quantity == order_line.quantity- assert checkout_line_variant == order_line.variant- assert order.shipping_address == address- assert order.shipping_method == checkout.shipping_method- assert order.payments.exists()- order_payment = order.payments.first()- assert order_payment == payment- assert payment.transactions.count() == 1-- gift_card.refresh_from_db()- assert gift_card.current_balance == zero_money()- assert gift_card.last_used_on-- assert not Checkout.objects.filter(- pk=checkout.pk- ).exists(), "Checkout should have been deleted"---def test_checkout_with_voucher_complete(- user_api_client,- checkout_with_voucher_percentage,- voucher_percentage,- payment_dummy,- address,- shipping_method,-):- voucher_used_count = voucher_percentage.used-- checkout = checkout_with_voucher_percentage- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.billing_address = address- checkout.store_value_in_metadata(items={"accepted": "true"})- checkout.store_value_in_private_metadata(items={"accepted": "false"})- checkout.save()-- checkout_line = checkout.lines.first()- checkout_line_quantity = checkout_line.quantity- checkout_line_variant = checkout_line.variant-- total = calculations.checkout_total(checkout=checkout, lines=list(checkout))- payment = payment_dummy- payment.is_active = True- payment.order = None- payment.total = total.gross.amount- payment.currency = total.gross.currency- payment.checkout = checkout- payment.save()- assert not payment.transactions.exists()-- orders_count = Order.objects.count()- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)- variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)-- content = get_graphql_content(response)- data = content["data"]["checkoutComplete"]- assert not data["checkoutErrors"]-- order_token = data["order"]["token"]- assert Order.objects.count() == orders_count + 1- order = Order.objects.first()- assert order.token == order_token- assert order.metadata == checkout.metadata- assert order.private_metadata == checkout.private_metadata-- order_line = order.lines.first()- assert checkout_line_quantity == order_line.quantity- assert checkout_line_variant == order_line.variant- assert order.shipping_address == address- assert order.shipping_method == checkout.shipping_method- assert order.payments.exists()- order_payment = order.payments.first()- assert order_payment == payment- assert payment.transactions.count() == 1-- voucher_percentage.refresh_from_db()- assert voucher_percentage.used == voucher_used_count + 1-- assert not Checkout.objects.filter(- pk=checkout.pk- ).exists(), "Checkout should have been deleted"---def test_checkout_complete_without_inventory_tracking(- user_api_client,- checkout_with_variant_without_inventory_tracking,- payment_dummy,- address,- shipping_method,-):- checkout = checkout_with_variant_without_inventory_tracking- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.billing_address = address- checkout.store_value_in_metadata(items={"accepted": "true"})- checkout.store_value_in_private_metadata(items={"accepted": "false"})- checkout.save()-- checkout_line = checkout.lines.first()- checkout_line_quantity = checkout_line.quantity- checkout_line_variant = checkout_line.variant-- total = calculations.checkout_total(checkout=checkout, lines=list(checkout))- payment = payment_dummy- payment.is_active = True- payment.order = None- payment.total = total.gross.amount- payment.currency = total.gross.currency- payment.checkout = checkout- payment.save()- assert not payment.transactions.exists()-- orders_count = Order.objects.count()- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)- variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)-- content = get_graphql_content(response)- data = content["data"]["checkoutComplete"]- assert not data["checkoutErrors"]-- order_token = data["order"]["token"]- assert Order.objects.count() == orders_count + 1- order = Order.objects.first()- assert order.token == order_token- assert order.total.gross == total.gross- assert order.metadata == checkout.metadata- assert order.private_metadata == checkout.private_metadata-- order_line = order.lines.first()- assert checkout_line_quantity == order_line.quantity- assert checkout_line_variant == order_line.variant- assert not order_line.allocations.all()- assert order.shipping_address == address- assert order.shipping_method == checkout.shipping_method- assert order.payments.exists()- order_payment = order.payments.first()- assert order_payment == payment- assert payment.transactions.count() == 1-- assert not Checkout.objects.filter(- pk=checkout.pk- ).exists(), "Checkout should have been deleted"--[email protected]("token, error", list(TOKEN_VALIDATION_MAPPING.items()))-@patch(- "saleor.payment.gateways.dummy_credit_card.plugin."- "DummyCreditCardGatewayPlugin.DEFAULT_ACTIVE",- True,-)-def test_checkout_complete_error_in_gateway_response_for_dummy_credit_card(- token,- error,- user_api_client,- checkout_with_gift_card,- gift_card,- payment_dummy_credit_card,- address,- shipping_method,-):- assert not gift_card.last_used_on-- checkout = checkout_with_gift_card- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.billing_address = address- checkout.store_value_in_metadata(items={"accepted": "true"})- checkout.store_value_in_private_metadata(items={"accepted": "false"})- checkout.save()-- total = calculations.calculate_checkout_total_with_gift_cards(checkout=checkout)- payment = payment_dummy_credit_card- payment.is_active = True- payment.order = None- payment.total = total.gross.amount- payment.currency = total.gross.currency- payment.checkout = checkout- payment.token = token- payment.save()- assert not payment.transactions.exists()-- orders_count = Order.objects.count()- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)- variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)-- content = get_graphql_content(response)- data = content["data"]["checkoutComplete"]- assert len(data["checkoutErrors"])- assert data["checkoutErrors"][0]["message"] == error- assert payment.transactions.count() == 1- assert Order.objects.count() == orders_count---ERROR_GATEWAY_RESPONSE = GatewayResponse(- is_success=False,- action_required=False,- kind=TransactionKind.CAPTURE,- amount=Decimal(0),- currency="usd",- transaction_id="1234",- error="ERROR",-)---def _process_payment_transaction_returns_error(*args, **kwards):- return ERROR_GATEWAY_RESPONSE---def _process_payment_raise_error(*args, **kwargs):- raise Exception("Oops! Something went wrong.")--- params=[_process_payment_raise_error, _process_payment_transaction_returns_error]-)-def error_side_effect(request):- return request.param--@pytest.fixturedef fake_manager(mocker):return mocker.Mock(spec=PaymentInterface)@@ -1977,112 +1677,6 @@ def mock_get_manager(mocker, fake_manager):manager.assert_called_once()-def test_checkout_complete_does_not_delete_checkout_after_unsuccessful_payment(- mock_get_manager,- error_side_effect,- user_api_client,- checkout_with_voucher,- voucher,- payment_dummy,- address,- shipping_method,-):- mock_get_manager.process_payment.side_effect = error_side_effect- expected_voucher_usage_count = voucher.used- checkout = checkout_with_voucher- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.billing_address = address- checkout.save()-- taxed_total = calculations.checkout_total(checkout=checkout, lines=list(checkout))- payment = payment_dummy- payment.is_active = True- payment.order = None- payment.total = taxed_total.gross.amount- payment.currency = taxed_total.gross.currency- payment.checkout = checkout- payment.save()- assert not payment.transactions.exists()-- orders_count = Order.objects.count()- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)- variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)- get_graphql_content(response)-- assert Order.objects.count() == orders_count-- payment.refresh_from_db(fields=["order"])- transaction = payment.transactions.get()- assert transaction.error- assert payment.order is None-- # ensure the voucher usage count was not incremented- voucher.refresh_from_db(fields=["used"])- assert voucher.used == expected_voucher_usage_count-- assert Checkout.objects.filter(- pk=checkout.pk- ).exists(), "Checkout should not have been deleted"---def test_checkout_complete_invalid_checkout_id(user_api_client):- checkout_id = "invalidId"- variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}- orders_count = Order.objects.count()- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutComplete"]- assert (- data["checkoutErrors"][0]["message"] == "Couldn't resolve to a node: invalidId"- )- assert data["checkoutErrors"][0]["field"] == "checkoutId"- assert orders_count == Order.objects.count()---def test_checkout_complete_no_payment(- user_api_client, checkout_with_item, address, shipping_method-):- checkout = checkout_with_item- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.billing_address = address- checkout.save()- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)- variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}- orders_count = Order.objects.count()- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutComplete"]- assert data["checkoutErrors"][0]["message"] == (- "Provided payment methods can not cover the checkout's total amount"- )- assert orders_count == Order.objects.count()---ACTION_REQUIRED_GATEWAY_RESPONSE = GatewayResponse(- is_success=True,- action_required=True,- action_required_data={- "paymentData": "test",- "paymentMethodType": "scheme",- "url": "https://test.adyen.com/hpp/3d/validate.shtml",- "data": {- "MD": "md-test-data",- "PaReq": "PaReq-test-data",- "TermUrl": "http://127.0.0.1:3000/",- },- "method": "POST",- "type": "redirect",- },- kind=TransactionKind.CAPTURE,- amount=Decimal(3.0),- currency="usd",- transaction_id="1234",- error=None,-)-TRANSACTION_CONFIRM_GATEWAY_RESPONSE = GatewayResponse(is_success=False,action_required=False,@@ -2094,336 +1688,6 @@ TRANSACTION_CONFIRM_GATEWAY_RESPONSE = GatewayResponse()-def test_checkout_complete_confirmation_needed(- mock_get_manager,- user_api_client,- checkout_with_item,- address,- payment_dummy,- shipping_method,-):- mock_get_manager.process_payment.return_value = ACTION_REQUIRED_GATEWAY_RESPONSE- checkout = checkout_with_item- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.billing_address = address- checkout.save()-- total = calculations.checkout_total(checkout=checkout, lines=list(checkout))- payment = payment_dummy- payment.is_active = True- payment.order = None- 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)- variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}- orders_count = Order.objects.count()-- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutComplete"]- assert not data["checkoutErrors"]- assert data["confirmationNeeded"] is True- assert data["confirmationData"]-- new_orders_count = Order.objects.count()- assert new_orders_count == orders_count- checkout.refresh_from_db()- payment_dummy.refresh_from_db()- assert payment_dummy.is_active- assert payment_dummy.to_confirm---def test_checkout_confirm(- user_api_client,- mock_get_manager,- checkout_with_item,- payment_txn_to_confirm,- address,- shipping_method,-):- mock_get_manager.confirm_payment.return_value = ACTION_REQUIRED_GATEWAY_RESPONSE-- checkout = checkout_with_item- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.billing_address = address- checkout.save()-- total = calculations.checkout_total(checkout=checkout, lines=list(checkout))- payment = payment_txn_to_confirm- payment.is_active = True- payment.order = None- 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)- orders_count = Order.objects.count()-- variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutComplete"]-- assert not data["checkoutErrors"]- assert not data["confirmationNeeded"]-- mock_get_manager.confirm_payment.assert_called_once()-- new_orders_count = Order.objects.count()- assert new_orders_count == orders_count + 1---def test_checkout_complete_insufficient_stock(- user_api_client, checkout_with_item, address, payment_dummy, shipping_method-):- checkout = checkout_with_item- checkout_line = checkout.lines.first()- stock = Stock.objects.get(product_variant=checkout_line.variant)- quantity_available = get_available_quantity_for_stock(stock)- checkout_line.quantity = quantity_available + 1- checkout_line.save()- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.billing_address = address- checkout.save()- total = calculations.checkout_total(checkout=checkout, lines=list(checkout))- payment = payment_dummy- payment.is_active = True- payment.order = None- 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)- variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}- orders_count = Order.objects.count()- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutComplete"]- assert data["checkoutErrors"][0]["message"] == "Insufficient product stock: 123"- assert orders_count == Order.objects.count()---@patch("saleor.graphql.checkout.mutations.gateway.refund")-def test_checkout_complete_insufficient_stock_payment_refunded(- gateway_refund_mock,- checkout_with_item,- address,- shipping_method,- payment_dummy,- user_api_client,-):- # given- checkout = checkout_with_item- checkout_line = checkout.lines.first()- stock = Stock.objects.get(product_variant=checkout_line.variant)- quantity_available = get_available_quantity_for_stock(stock)- checkout_line.quantity = quantity_available + 1- checkout_line.save()-- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.billing_address = address- checkout.save()-- total = calculations.checkout_total(checkout=checkout, lines=list(checkout))-- payment = payment_dummy- payment.is_active = True- payment.order = None- payment.total = total.gross.amount- payment.currency = total.gross.currency- payment.checkout = checkout- payment.charge_status = ChargeStatus.FULLY_CHARGED- payment.save()-- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)- variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}- orders_count = Order.objects.count()-- # when- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)-- # then- content = get_graphql_content(response)- data = content["data"]["checkoutComplete"]-- assert data["checkoutErrors"][0]["message"] == "Insufficient product stock: 123"- assert orders_count == Order.objects.count()-- gateway_refund_mock.assert_called_once_with(payment)---@patch("saleor.graphql.checkout.mutations.gateway.void")-def test_checkout_complete_insufficient_stock_payment_voided(- gateway_void_mock,- checkout_with_item,- address,- shipping_method,- payment_txn_preauth,- user_api_client,-):- # given- checkout = checkout_with_item- checkout_line = checkout.lines.first()- stock = Stock.objects.get(product_variant=checkout_line.variant)- quantity_available = get_available_quantity_for_stock(stock)- checkout_line.quantity = quantity_available + 1- checkout_line.save()-- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.billing_address = address- checkout.save()-- total = calculations.checkout_total(checkout=checkout, lines=list(checkout))-- payment = payment_txn_preauth- payment.is_active = True- payment.order = None- payment.total = total.gross.amount- payment.currency = total.gross.currency- payment.checkout = checkout- payment.charge_status = ChargeStatus.NOT_CHARGED- payment.save()-- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)- variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}- orders_count = Order.objects.count()-- # when- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)-- # then- content = get_graphql_content(response)- data = content["data"]["checkoutComplete"]-- assert data["checkoutErrors"][0]["message"] == "Insufficient product stock: 123"- assert orders_count == Order.objects.count()-- gateway_void_mock.assert_called_once_with(payment)---def test_checkout_complete_without_redirect_url(- user_api_client,- checkout_with_gift_card,- gift_card,- payment_dummy,- address,- shipping_method,-):-- assert not gift_card.last_used_on-- checkout = checkout_with_gift_card- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.billing_address = address- checkout.save()-- checkout_line = checkout.lines.first()- checkout_line_quantity = checkout_line.quantity- checkout_line_variant = checkout_line.variant-- total = calculations.calculate_checkout_total_with_gift_cards(checkout=checkout)- payment = payment_dummy- payment.is_active = True- payment.order = None- payment.total = total.gross.amount- payment.currency = total.gross.currency- payment.checkout = checkout- payment.save()- assert not payment.transactions.exists()-- orders_count = Order.objects.count()- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)- variables = {"checkoutId": checkout_id}- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)-- content = get_graphql_content(response)- data = content["data"]["checkoutComplete"]- assert not data["checkoutErrors"]-- order_token = data["order"]["token"]- assert Order.objects.count() == orders_count + 1- order = Order.objects.first()- assert order.token == order_token- assert order.total.gross == total.gross-- order_line = order.lines.first()- assert checkout_line_quantity == order_line.quantity- assert checkout_line_variant == order_line.variant- assert order.shipping_address == address- assert order.shipping_method == checkout.shipping_method- assert order.payments.exists()- order_payment = order.payments.first()- assert order_payment == payment- assert payment.transactions.count() == 1-- gift_card.refresh_from_db()- assert gift_card.current_balance == zero_money()- assert gift_card.last_used_on-- assert not Checkout.objects.filter(- pk=checkout.pk- ).exists(), "Checkout should have been deleted"---@patch("saleor.graphql.checkout.mutations.gateway.payment_refund_or_void")-def test_checkout_complete_payment_payment_total_different_than_checkout(- gateway_refund_or_void_mock,- checkout_with_item,- address,- shipping_method,- payment_dummy,- user_api_client,-):- # given- checkout = checkout_with_item- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.billing_address = address- checkout.store_value_in_metadata(items={"accepted": "true"})- checkout.store_value_in_private_metadata(items={"accepted": "false"})- checkout.save()-- total = calculations.checkout_total(checkout=checkout, lines=list(checkout))- payment = payment_dummy- payment.is_active = True- payment.order = None- payment.total = total.gross.amount + Decimal(10)- payment.currency = total.gross.currency- payment.checkout = checkout- payment.save()- assert not payment.transactions.exists()-- orders_count = Order.objects.count()- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)- variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)-- # when- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)-- # then- content = get_graphql_content(response)- data = content["data"]["checkoutComplete"]-- assert (- data["checkoutErrors"][0]["code"]- == CheckoutErrorCode.CHECKOUT_NOT_FULLY_PAID.name- )- assert orders_count == Order.objects.count()-- gateway_refund_or_void_mock.assert_called_with(payment)--def test_fetch_checkout_by_token(user_api_client, checkout_with_item):query = """query getCheckout($token: UUID!) {diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.pynew file mode 100644index 0000000000..c06bdb230d--- /dev/null+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py@@ -0,0 +1,790 @@+from decimal import Decimal+from unittest.mock import patch++import graphene+import pytest++from ....checkout import calculations+from ....checkout.error_codes import CheckoutErrorCode+from ....checkout.models import Checkout+from ....core.exceptions import InsufficientStock+from ....core.taxes import zero_money+from ....order.models import Order+from ....payment import ChargeStatus, PaymentError, TransactionKind+from ....payment.gateways.dummy_credit_card import TOKEN_VALIDATION_MAPPING+from ....payment.interface import GatewayResponse+from ....warehouse.models import Stock+from ....warehouse.tests.utils import get_available_quantity_for_stock+from ...tests.utils import get_graphql_content++MUTATION_CHECKOUT_COMPLETE = """+ mutation checkoutComplete($checkoutId: ID!, $redirectUrl: String) {+ checkoutComplete(checkoutId: $checkoutId, redirectUrl: $redirectUrl) {+ order {+ id,+ token+ },+ checkoutErrors {+ field,+ message,+ code+ }+ confirmationNeeded+ confirmationData+ }+ }+ """+++ACTION_REQUIRED_GATEWAY_RESPONSE = GatewayResponse(+ is_success=True,+ action_required=True,+ action_required_data={+ "paymentData": "test",+ "paymentMethodType": "scheme",+ "url": "https://test.adyen.com/hpp/3d/validate.shtml",+ "data": {+ "MD": "md-test-data",+ "PaReq": "PaReq-test-data",+ "TermUrl": "http://127.0.0.1:3000/",+ },+ "method": "POST",+ "type": "redirect",+ },+ kind=TransactionKind.CAPTURE,+ amount=Decimal(3.0),+ currency="usd",+ transaction_id="1234",+ error=None,+)+++def test_checkout_complete(+ user_api_client,+ checkout_with_gift_card,+ gift_card,+ payment_dummy,+ address,+ shipping_method,+):++ assert not gift_card.last_used_on++ checkout = checkout_with_gift_card+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.store_value_in_metadata(items={"accepted": "true"})+ checkout.store_value_in_private_metadata(items={"accepted": "false"})+ checkout.save()++ checkout_line = checkout.lines.first()+ checkout_line_quantity = checkout_line.quantity+ checkout_line_variant = checkout_line.variant++ total = calculations.calculate_checkout_total_with_gift_cards(checkout=checkout)+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()+ assert not payment.transactions.exists()++ orders_count = Order.objects.count()+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert not data["checkoutErrors"]++ order_token = data["order"]["token"]+ assert Order.objects.count() == orders_count + 1+ order = Order.objects.first()+ assert order.token == order_token+ assert order.total.gross == total.gross+ assert order.metadata == checkout.metadata+ assert order.private_metadata == checkout.private_metadata++ order_line = order.lines.first()+ assert checkout_line_quantity == order_line.quantity+ assert checkout_line_variant == order_line.variant+ assert order.shipping_address == address+ assert order.shipping_method == checkout.shipping_method+ assert order.payments.exists()+ order_payment = order.payments.first()+ assert order_payment == payment+ assert payment.transactions.count() == 1++ gift_card.refresh_from_db()+ assert gift_card.current_balance == zero_money()+ assert gift_card.last_used_on++ assert not Checkout.objects.filter(+ pk=checkout.pk+ ).exists(), "Checkout should have been deleted"+++def test_checkout_with_voucher_complete(+ user_api_client,+ checkout_with_voucher_percentage,+ voucher_percentage,+ payment_dummy,+ address,+ shipping_method,+):+ voucher_used_count = voucher_percentage.used++ checkout = checkout_with_voucher_percentage+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.store_value_in_metadata(items={"accepted": "true"})+ checkout.store_value_in_private_metadata(items={"accepted": "false"})+ checkout.save()++ checkout_line = checkout.lines.first()+ checkout_line_quantity = checkout_line.quantity+ checkout_line_variant = checkout_line.variant++ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()+ assert not payment.transactions.exists()++ orders_count = Order.objects.count()+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert not data["checkoutErrors"]++ order_token = data["order"]["token"]+ assert Order.objects.count() == orders_count + 1+ order = Order.objects.first()+ assert order.token == order_token+ assert order.metadata == checkout.metadata+ assert order.private_metadata == checkout.private_metadata++ order_line = order.lines.first()+ assert checkout_line_quantity == order_line.quantity+ assert checkout_line_variant == order_line.variant+ assert order.shipping_address == address+ assert order.shipping_method == checkout.shipping_method+ assert order.payments.exists()+ order_payment = order.payments.first()+ assert order_payment == payment+ assert payment.transactions.count() == 1++ voucher_percentage.refresh_from_db()+ assert voucher_percentage.used == voucher_used_count + 1++ assert not Checkout.objects.filter(+ pk=checkout.pk+ ).exists(), "Checkout should have been deleted"+++def test_checkout_complete_without_inventory_tracking(+ user_api_client,+ checkout_with_variant_without_inventory_tracking,+ payment_dummy,+ address,+ shipping_method,+):+ checkout = checkout_with_variant_without_inventory_tracking+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.store_value_in_metadata(items={"accepted": "true"})+ checkout.store_value_in_private_metadata(items={"accepted": "false"})+ checkout.save()++ checkout_line = checkout.lines.first()+ checkout_line_quantity = checkout_line.quantity+ checkout_line_variant = checkout_line.variant++ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()+ assert not payment.transactions.exists()++ orders_count = Order.objects.count()+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert not data["checkoutErrors"]++ order_token = data["order"]["token"]+ assert Order.objects.count() == orders_count + 1+ order = Order.objects.first()+ assert order.token == order_token+ assert order.total.gross == total.gross+ assert order.metadata == checkout.metadata+ assert order.private_metadata == checkout.private_metadata++ order_line = order.lines.first()+ assert checkout_line_quantity == order_line.quantity+ assert checkout_line_variant == order_line.variant+ assert not order_line.allocations.all()+ assert order.shipping_address == address+ assert order.shipping_method == checkout.shipping_method+ assert order.payments.exists()+ order_payment = order.payments.first()+ assert order_payment == payment+ assert payment.transactions.count() == 1++ assert not Checkout.objects.filter(+ pk=checkout.pk+ ).exists(), "Checkout should have been deleted"++[email protected]("token, error", list(TOKEN_VALIDATION_MAPPING.items()))+@patch(+ "saleor.payment.gateways.dummy_credit_card.plugin."+ "DummyCreditCardGatewayPlugin.DEFAULT_ACTIVE",+ True,+)+def test_checkout_complete_error_in_gateway_response_for_dummy_credit_card(+ token,+ error,+ user_api_client,+ checkout_with_gift_card,+ gift_card,+ payment_dummy_credit_card,+ address,+ shipping_method,+):+ assert not gift_card.last_used_on++ checkout = checkout_with_gift_card+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.store_value_in_metadata(items={"accepted": "true"})+ checkout.store_value_in_private_metadata(items={"accepted": "false"})+ checkout.save()++ total = calculations.calculate_checkout_total_with_gift_cards(checkout=checkout)+ payment = payment_dummy_credit_card+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.token = token+ payment.save()+ assert not payment.transactions.exists()++ orders_count = Order.objects.count()+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert len(data["checkoutErrors"])+ assert data["checkoutErrors"][0]["message"] == error+ assert payment.transactions.count() == 1+ assert Order.objects.count() == orders_count+++ERROR_GATEWAY_RESPONSE = GatewayResponse(+ is_success=False,+ action_required=False,+ kind=TransactionKind.CAPTURE,+ amount=Decimal(0),+ currency="usd",+ transaction_id="1234",+ error="ERROR",+)+++def _process_payment_transaction_returns_error(*args, **kwards):+ return ERROR_GATEWAY_RESPONSE+++def _process_payment_raise_error(*args, **kwargs):+ raise PaymentError("Oops! Something went wrong.")+++ params=[_process_payment_raise_error, _process_payment_transaction_returns_error]+)+def error_side_effect(request):+ return request.param+++def test_checkout_complete_does_not_delete_checkout_after_unsuccessful_payment(+ mock_get_manager,+ error_side_effect,+ user_api_client,+ checkout_with_voucher,+ voucher,+ payment_dummy,+ address,+ shipping_method,+):+ mock_get_manager.process_payment.side_effect = error_side_effect+ expected_voucher_usage_count = voucher.used+ checkout = checkout_with_voucher+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ taxed_total = calculations.checkout_total(checkout=checkout, lines=list(checkout))+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = taxed_total.gross.amount+ payment.currency = taxed_total.gross.currency+ payment.checkout = checkout+ payment.save()+ assert not payment.transactions.exists()++ orders_count = Order.objects.count()+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)+ get_graphql_content(response)++ assert Order.objects.count() == orders_count++ payment.refresh_from_db(fields=["order"])+ transaction = payment.transactions.get()+ assert transaction.error+ assert payment.order is None++ # ensure the voucher usage count was not incremented+ voucher.refresh_from_db(fields=["used"])+ assert voucher.used == expected_voucher_usage_count++ assert Checkout.objects.filter(+ pk=checkout.pk+ ).exists(), "Checkout should not have been deleted"+++def test_checkout_complete_invalid_checkout_id(user_api_client):+ checkout_id = "invalidId"+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ orders_count = Order.objects.count()+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert (+ data["checkoutErrors"][0]["message"] == "Couldn't resolve to a node: invalidId"+ )+ assert data["checkoutErrors"][0]["field"] == "checkoutId"+ assert orders_count == Order.objects.count()+++def test_checkout_complete_no_payment(+ user_api_client, checkout_with_item, address, shipping_method+):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ orders_count = Order.objects.count()+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert data["checkoutErrors"][0]["message"] == (+ "Provided payment methods can not cover the checkout's total amount"+ )+ assert orders_count == Order.objects.count()+++def test_checkout_complete_confirmation_needed(+ mock_get_manager,+ user_api_client,+ checkout_with_item,+ address,+ payment_dummy,+ shipping_method,+):+ mock_get_manager.process_payment.return_value = ACTION_REQUIRED_GATEWAY_RESPONSE+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ 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)+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ orders_count = Order.objects.count()++ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert not data["checkoutErrors"]+ assert data["confirmationNeeded"] is True+ assert data["confirmationData"]++ new_orders_count = Order.objects.count()+ assert new_orders_count == orders_count+ checkout.refresh_from_db()+ payment_dummy.refresh_from_db()+ assert payment_dummy.is_active+ assert payment_dummy.to_confirm+++def test_checkout_confirm(+ user_api_client,+ mock_get_manager,+ checkout_with_item,+ payment_txn_to_confirm,+ address,+ shipping_method,+):+ mock_get_manager.confirm_payment.return_value = ACTION_REQUIRED_GATEWAY_RESPONSE++ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))+ payment = payment_txn_to_confirm+ payment.is_active = True+ payment.order = None+ 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)+ orders_count = Order.objects.count()++ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]++ assert not data["checkoutErrors"]+ assert not data["confirmationNeeded"]++ mock_get_manager.confirm_payment.assert_called_once()++ new_orders_count = Order.objects.count()+ assert new_orders_count == orders_count + 1+++def test_checkout_complete_insufficient_stock(+ user_api_client, checkout_with_item, address, payment_dummy, shipping_method+):+ checkout = checkout_with_item+ checkout_line = checkout.lines.first()+ stock = Stock.objects.get(product_variant=checkout_line.variant)+ quantity_available = get_available_quantity_for_stock(stock)+ checkout_line.quantity = quantity_available + 1+ checkout_line.save()+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ 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)+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ orders_count = Order.objects.count()+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert data["checkoutErrors"][0]["message"] == "Insufficient product stock: 123"+ assert orders_count == Order.objects.count()+++@patch("saleor.graphql.checkout.mutations.gateway.refund")+def test_checkout_complete_insufficient_stock_payment_refunded(+ gateway_refund_mock,+ checkout_with_item,+ address,+ shipping_method,+ payment_dummy,+ user_api_client,+):+ # given+ checkout = checkout_with_item+ checkout_line = checkout.lines.first()+ stock = Stock.objects.get(product_variant=checkout_line.variant)+ quantity_available = get_available_quantity_for_stock(stock)+ checkout_line.quantity = quantity_available + 1+ checkout_line.save()++ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))++ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.charge_status = ChargeStatus.FULLY_CHARGED+ payment.save()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ orders_count = Order.objects.count()++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]++ assert data["checkoutErrors"][0]["message"] == "Insufficient product stock: 123"+ assert orders_count == Order.objects.count()++ gateway_refund_mock.assert_called_once_with(payment)+++@patch("saleor.graphql.checkout.mutations.gateway.void")+def test_checkout_complete_insufficient_stock_payment_voided(+ gateway_void_mock,+ checkout_with_item,+ address,+ shipping_method,+ payment_txn_preauth,+ user_api_client,+):+ # given+ checkout = checkout_with_item+ checkout_line = checkout.lines.first()+ stock = Stock.objects.get(product_variant=checkout_line.variant)+ quantity_available = get_available_quantity_for_stock(stock)+ checkout_line.quantity = quantity_available + 1+ checkout_line.save()++ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))++ payment = payment_txn_preauth+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.charge_status = ChargeStatus.NOT_CHARGED+ payment.save()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ orders_count = Order.objects.count()++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]++ assert data["checkoutErrors"][0]["message"] == "Insufficient product stock: 123"+ assert orders_count == Order.objects.count()++ gateway_void_mock.assert_called_once_with(payment)+++def test_checkout_complete_without_redirect_url(+ user_api_client,+ checkout_with_gift_card,+ gift_card,+ payment_dummy,+ address,+ shipping_method,+):++ assert not gift_card.last_used_on++ checkout = checkout_with_gift_card+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ checkout_line = checkout.lines.first()+ checkout_line_quantity = checkout_line.quantity+ checkout_line_variant = checkout_line.variant++ total = calculations.calculate_checkout_total_with_gift_cards(checkout=checkout)+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()+ assert not payment.transactions.exists()++ orders_count = Order.objects.count()+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ variables = {"checkoutId": checkout_id}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert not data["checkoutErrors"]++ order_token = data["order"]["token"]+ assert Order.objects.count() == orders_count + 1+ order = Order.objects.first()+ assert order.token == order_token+ assert order.total.gross == total.gross++ order_line = order.lines.first()+ assert checkout_line_quantity == order_line.quantity+ assert checkout_line_variant == order_line.variant+ assert order.shipping_address == address+ assert order.shipping_method == checkout.shipping_method+ assert order.payments.exists()+ order_payment = order.payments.first()+ assert order_payment == payment+ assert payment.transactions.count() == 1++ gift_card.refresh_from_db()+ assert gift_card.current_balance == zero_money()+ assert gift_card.last_used_on++ assert not Checkout.objects.filter(+ pk=checkout.pk+ ).exists(), "Checkout should have been deleted"+++@patch("saleor.graphql.checkout.mutations.gateway.payment_refund_or_void")+def test_checkout_complete_payment_payment_total_different_than_checkout(+ gateway_refund_or_void_mock,+ checkout_with_items,+ payment_dummy,+ user_api_client,+ address,+ shipping_method,+):+ # given+ checkout = checkout_with_items+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount + Decimal(10)+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()+ assert not payment.transactions.exists()++ orders_count = Order.objects.count()+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]++ assert (+ data["checkoutErrors"][0]["code"]+ == CheckoutErrorCode.CHECKOUT_NOT_FULLY_PAID.name+ )+ assert orders_count == Order.objects.count()++ gateway_refund_or_void_mock.assert_called_with(payment)+++def test_order_already_exists(+ user_api_client, checkout_ready_to_complete, payment_dummy, order_with_lines+):++ checkout = checkout_ready_to_complete+ order_with_lines.checkout_token = checkout.token+ order_with_lines.save()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ checkout.delete()+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert not data["checkoutErrors"]++ order_token = data["order"]["token"]+ assert Order.objects.count() == 1+ order = Order.objects.first()+ assert order.token == order_token++ assert Checkout.objects.count() == 0+++@patch("saleor.graphql.checkout.mutations.create_order")+def test_create_order_raises_insufficient_stock(+ mocked_create_order, user_api_client, checkout_ready_to_complete,+):+ mocked_create_order.side_effect = InsufficientStock("InsufficientStock")+ checkout = checkout_ready_to_complete++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert not data["checkoutErrors"]+ assert mocked_create_order.calleddiff --git a/saleor/graphql/checkout/utils.py b/saleor/graphql/checkout/utils.pyindex ef3777672a..c774daa2fe 100644--- a/saleor/graphql/checkout/utils.py+++ b/saleor/graphql/checkout/utils.py@@ -1,4 +1,4 @@-from typing import Iterable, Union+from typing import Iterable, Type, Unionfrom django.core.exceptions import ValidationError@@ -13,7 +13,7 @@ def clean_checkout_shipping(checkout: Checkout,lines: Iterable[CheckoutLine],discounts: Iterable[DiscountInfo],- error_code: Union[CheckoutErrorCode, PaymentErrorCode],+ error_code: Union[Type[CheckoutErrorCode], Type[PaymentErrorCode]],):if checkout.is_shipping_required():if not checkout.shipping_method:@@ -21,7 +21,7 @@ def clean_checkout_shipping({"shipping_method": ValidationError("Shipping method is not set",- code=error_code.SHIPPING_METHOD_NOT_SET,+ code=error_code.SHIPPING_METHOD_NOT_SET.value,)})@@ -30,7 +30,7 @@ def clean_checkout_shipping({"shipping_address": ValidationError("Shipping address is not set",- code=error_code.SHIPPING_ADDRESS_NOT_SET,+ code=error_code.SHIPPING_ADDRESS_NOT_SET.value,)})@@ -39,21 +39,22 @@ def clean_checkout_shipping({"shipping_method": ValidationError("Shipping method is not valid for your shipping address",- code=error_code.INVALID_SHIPPING_METHOD,+ code=error_code.INVALID_SHIPPING_METHOD.value,)})def clean_billing_address(- checkout: Checkout, error_code: Union[CheckoutErrorCode, PaymentErrorCode],+ checkout: Checkout,+ error_code: Union[Type[CheckoutErrorCode], Type[PaymentErrorCode]],):if not checkout.billing_address:raise ValidationError({"billing_address": ValidationError("Billing address is not set",- code=error_code.BILLING_ADDRESS_NOT_SET,+ code=error_code.BILLING_ADDRESS_NOT_SET.value,)})@@ -63,11 +64,11 @@ def clean_checkout_payment(checkout: Checkout,lines: Iterable[CheckoutLine],discounts: Iterable[DiscountInfo],- error_code: CheckoutErrorCode,+ error_code: Type[CheckoutErrorCode],):clean_billing_address(checkout, error_code)if not is_fully_paid(checkout, lines, discounts):raise ValidationError("Provided payment methods can not cover the checkout's total amount",- code=error_code.CHECKOUT_NOT_FULLY_PAID,+ code=error_code.CHECKOUT_NOT_FULLY_PAID.value,)diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.pyindex 1c8b654b23..0191596823 100644--- a/saleor/payment/gateway.py+++ b/saleor/payment/gateway.py@@ -248,7 +248,7 @@ def _fetch_gateway_response(fn, *args, **kwargs):logger.exception("Gateway response validation failed!")response = Noneerror = ERROR_MSG- except Exception:+ except PaymentError:logger.exception("Error encountered while executing payment gateway.")error = ERROR_MSGresponse = Nonediff --git a/saleor/payment/gateways/adyen/tests/conftest.py b/saleor/payment/gateways/adyen/tests/conftest.pyindex 86834d2483..010c9aa7c2 100644--- a/saleor/payment/gateways/adyen/tests/conftest.py+++ b/saleor/payment/gateways/adyen/tests/conftest.py@@ -57,7 +57,7 @@ def payment_adyen_for_checkout(checkout_with_items, address):payment = create_payment(gateway=AdyenGatewayPlugin.PLUGIN_ID,payment_token="",- total=Decimal("1234"),+ total=Decimal("12.34"),currency=checkout_with_items.currency,email=checkout_with_items.email,customer_ip_address="",diff --git a/saleor/payment/gateways/adyen/tests/webhooks/cassettes/test_handle_authorization_for_checkout_wrong_total.yaml b/saleor/payment/gateways/adyen/tests/webhooks/cassettes/test_handle_authorization_for_checkout_wrong_total.yamlnew file mode 100644index 0000000000..2031a5c0fd--- /dev/null+++ b/saleor/payment/gateways/adyen/tests/webhooks/cassettes/test_handle_authorization_for_checkout_wrong_total.yaml@@ -0,0 +1,46 @@+interactions:+- request:+ body: '{"merchantAccount": "SaleorECOM", "originalReference": "852595499936560C",+ "reference": "UGF5bWVudDoxMDg=", "applicationInfo": {"adyenLibrary": {"name":+ "adyen-python-api-library", "version": "3.0.0"}}}'+ headers:+ Accept:+ - '*/*'+ Accept-Encoding:+ - gzip, deflate+ Connection:+ - keep-alive+ Content-Length:+ - '202'+ Content-Type:+ - application/json+ User-Agent:+ - adyen-python-api-library/3.0.0+ x-api-key:+ - test_key+ method: POST+ uri: https://pal-test.adyen.com/pal/servlet/Payment/v49/cancel+ response:+ body:+ string: '{"status":401,"errorCode":"000","message":"HTTP Status Response - Unauthorized","errorType":"security"}'+ headers:+ Connection:+ - Keep-Alive+ Content-Type:+ - application/json+ Date:+ - Tue, 18 Aug 2020 13:28:46 GMT+ Keep-Alive:+ - timeout=15, max=100+ Server:+ - Apache+ Set-Cookie:+ - JSESSIONID=3ADD2912A60201D4D654B56E5610FA80.test103e; Path=/pal; Secure; HttpOnly+ Transfer-Encoding:+ - chunked+ WWW-Authenticate:+ - BASIC realm="Adyen PAL Service Authentication"+ status:+ code: 401+ message: '401'+version: 1diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.pyindex c4b45846e6..d25722f0ac 100644--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py@@ -22,7 +22,9 @@ from ...webhooks import ()-def test_handle_authorization(notification, adyen_plugin, payment_adyen_for_order):+def test_handle_authorization_for_order(+ notification, adyen_plugin, payment_adyen_for_order+):payment = payment_adyen_for_orderpayment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(@@ -38,6 +40,49 @@ def test_handle_authorization(notification, adyen_plugin, payment_adyen_for_ordeassert transaction.kind == TransactionKind.AUTH+def test_handle_authorization_for_checkout(+ notification, adyen_plugin, payment_adyen_for_checkout+):+ payment = payment_adyen_for_checkout+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)+ notification = notification(+ merchant_reference=payment_id,+ value=to_adyen_price(payment.total, payment.currency),+ )+ config = adyen_plugin().config+ handle_authorization(notification, config)++ payment.refresh_from_db()+ assert payment.transactions.count() == 1+ transaction = payment.transactions.get()+ assert transaction.is_success is True+ assert transaction.kind == TransactionKind.AUTH+ assert payment.checkout is None+ assert payment.order+++def test_handle_authorization_for_checkout_wrong_total(+ notification, adyen_plugin, payment_adyen_for_checkout+):+ payment = payment_adyen_for_checkout+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)+ notification = notification(+ merchant_reference=payment_id,+ value=to_adyen_price(Decimal(10), payment.currency),+ )+ config = adyen_plugin().config+ handle_authorization(notification, config)++ payment.refresh_from_db()+ assert payment.transactions.count() == 1+ transaction = payment.transactions.get()+ assert transaction.is_success is True+ assert transaction.kind == TransactionKind.AUTH+ assert payment.checkout is None+ assert payment.order++def test_handle_authorization_with_adyen_auto_capture(notification, adyen_plugin, payment_adyen_for_order):diff --git a/saleor/payment/gateways/adyen/utils.py b/saleor/payment/gateways/adyen/utils.pyindex 22599935de..75d7090c7a 100644--- a/saleor/payment/gateways/adyen/utils.py+++ b/saleor/payment/gateways/adyen/utils.py@@ -6,12 +6,15 @@ from typing import Any, Callable, Dict, Optionalimport Adyenfrom babel.numbers import get_currency_precisionfrom django.conf import settings+from django.contrib.auth.models import AnonymousUserfrom django_countries.fields import Countryfrom ....checkout.calculations import checkout_line_total, checkout_totalfrom ....checkout.models import Checkout+from ....checkout.utils import create_order, is_fully_paid, prepare_order_datafrom ....core.prices import quantize_pricefrom ....discount.utils import fetch_active_discounts+from ....order.models import Orderfrom ....payment.models import Paymentfrom ... import PaymentErrorfrom ...interface import PaymentData, PaymentMethodInfo@@ -281,3 +284,21 @@ def get_payment_method_info(type="card" if payment_method == "scheme" else payment_method,)return payment_method_info+++def create_order_from_checkout(checkout: "Checkout") -> "Order":+ discounts = fetch_active_discounts()+ lines = list(checkout)++ if not is_fully_paid(checkout, lines, discounts):+ raise PaymentError(+ "Provided payment methods can not cover the checkout's total amount"+ )++ order_data = prepare_order_data(+ checkout=checkout, lines=lines, discounts=discounts,+ )+ user = checkout.user or AnonymousUser()+ return create_order(+ checkout=checkout, order_data=order_data, user=user # type: ignore+ )diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.pyindex 630335607f..10e03e60b4 100644--- a/saleor/payment/gateways/adyen/webhooks.py+++ b/saleor/payment/gateways/adyen/webhooks.py@@ -11,6 +11,7 @@ import graphenefrom django.contrib.auth.hashers import check_passwordfrom django.core.exceptions import ObjectDoesNotExistfrom django.core.handlers.wsgi import WSGIRequest+from django.db import transactionfrom django.http import (HttpResponse,HttpResponseBadRequest,@@ -21,6 +22,7 @@ from django.http.request import HttpHeadersfrom django.shortcuts import redirectfrom graphql_relay import from_global_id+from ....checkout.models import Checkoutfrom ....core.utils.url import prepare_urlfrom ....order.actions import (cancel_order,@@ -31,10 +33,15 @@ from ....order.actions import (from ....order.events import external_notification_eventfrom ....payment.models import Payment, Transactionfrom ... import ChargeStatus, PaymentError, TransactionKind-from ...gateway import capture+from ...gateway import capture, payment_refund_or_voidfrom ...interface import GatewayConfig, GatewayResponsefrom ...utils import create_payment_information, create_transaction, gateway_postprocess-from .utils import FAILED_STATUSES, api_call, from_adyen_price+from .utils import (+ FAILED_STATUSES,+ api_call,+ create_order_from_checkout,+ from_adyen_price,+)def get_payment(payment_id: Optional[str]) -> Optional[Payment]:@@ -45,14 +52,27 @@ def get_payment(payment_id: Optional[str]) -> Optional[Payment]:except UnicodeDecodeError:return Nonepayment = (- Payment.objects.prefetch_related("order")- .select_related()+ Payment.objects.prefetch_related("order", "checkout")+ .select_for_update(of=("self",)).filter(id=db_payment_id).first())return payment+def get_checkout(payment: Payment) -> Optional[Checkout]:+ if not payment.checkout:+ return None+ # Lock checkout in the same way as in checkoutComplete+ return (+ Checkout.objects.select_for_update(of=("self",))+ .prefetch_related("gift_cards", "lines",)+ .select_related("shipping_method", "shipping_method__shipping_zone")+ .filter(token=payment.checkout.pk)+ .first()+ )++def get_transaction(payment: "Payment", transaction_id: Optional[str], kind: str,) -> Optional[Transaction]:@@ -101,11 +121,13 @@ def create_payment_notification_for_order()def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayConfig):payment = get_payment(notification.get("merchantReference"))if not payment:# We don't know anything about that paymentreturn+ checkout = get_checkout(payment)if payment.charge_status in {ChargeStatus.FULLY_CHARGED,ChargeStatus.PARTIALLY_CHARGED,@@ -132,6 +154,15 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCotransaction = create_new_transaction(notification, payment, kind)reason = notification.get("reason", "-")+ if not payment.order and transaction.is_success and checkout:+ try:+ order = create_order_from_checkout(checkout)+ except Exception:+ payment_refund_or_void(payment)+ return+ checkout.delete()+ payment.order = order+success_msg = f"Adyen: The payment {transaction_id} request was successful."failed_msg = f"Adyen: The payment {transaction_id} request failed. Reason: {reason}"create_payment_notification_for_order(@@ -150,6 +181,7 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCoorder_captured(payment.order, None, transaction.amount, payment)def handle_cancellation(notification: Dict[str, Any], _gateway_config: GatewayConfig):# https://docs.adyen.com/checkout/cancel#cancellation-notifciationpayment = get_payment(notification.get("merchantReference"))@@ -189,11 +221,14 @@ def handle_cancel_or_refund(handle_cancellation(notification, gateway_config)def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):# https://docs.adyen.com/checkout/capture#capture-notificationpayment = get_payment(notification.get("merchantReference"))if not payment:return+ checkout = get_checkout(payment)+transaction_id = notification.get("pspReference")if payment.charge_status == ChargeStatus.FULLY_CHARGED:# the payment has already status captured.@@ -206,6 +241,16 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)gateway_postprocess(new_transaction, payment)reason = notification.get("reason", "-")++ if not payment.order and new_transaction.is_success and checkout:+ try:+ order = create_order_from_checkout(checkout)+ except Exception:+ payment_refund_or_void(payment)+ return+ checkout.delete()+ payment.order = order+success_msg = f"Adyen: The capture {transaction_id} request was successful."failed_msg = f"Adyen: The capture {transaction_id} request failed. Reason: {reason}"create_payment_notification_for_order(@@ -215,6 +260,7 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)order_captured(payment.order, None, new_transaction.amount, payment)def handle_failed_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):# https://docs.adyen.com/checkout/capture#failed-capturepayment = get_payment(notification.get("merchantReference"))@@ -241,6 +287,7 @@ def handle_failed_capture(notification: Dict[str, Any], _gateway_config: Gatewaycreate_payment_notification_for_order(payment, msg, None, True)def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):# https://docs.adyen.com/development-resources/webhooks/understand-notifications## event-codes"@@ -264,6 +311,7 @@ def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):)def handle_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):# https://docs.adyen.com/checkout/refund#refund-notificationpayment = get_payment(notification.get("merchantReference"))@@ -296,6 +344,7 @@ def _get_kind(transaction: Optional[Transaction]) -> str:return TransactionKind.CAPTUREdef handle_failed_refund(notification: Dict[str, Any], gateway_config: GatewayConfig):# https://docs.adyen.com/checkout/refund#failed-refundpayment = get_payment(notification.get("merchantReference"))@@ -359,6 +408,7 @@ def handle_failed_refund(notification: Dict[str, Any], gateway_config: GatewayCogateway_postprocess(new_transaction, payment)def handle_reversed_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):@@ -395,6 +445,7 @@ def handle_refund_with_data(handle_refund(notification, gateway_config)def webhook_not_implemented(notification: Dict[str, Any], gateway_config: GatewayConfig):diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex c3cbb7c0bf..d5d8bd99cb 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -194,9 +194,9 @@ def get_already_processed_transaction_or_create_new_transaction(error_msg=None,) -> Transaction:if gateway_response and gateway_response.transaction_already_processed:- transaction = get_already_processed_transaction(payment, gateway_response)- if transaction:- return transaction+ txn = get_already_processed_transaction(payment, gateway_response)+ if txn:+ return txnreturn create_transaction(payment,kind,diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex fdc921cf04..d6b5d1aa4f 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -246,6 +246,19 @@ def checkout_with_item(checkout, product):return checkout+def checkout_ready_to_complete(checkout_with_item, address, shipping_method, gift_card):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.store_value_in_metadata(items={"accepted": "true"})+ checkout.store_value_in_private_metadata(items={"accepted": "false"})+ checkout_with_item.gift_cards.add(gift_card)+ checkout.save()+ return checkout++@pytest.fixturedef checkout_with_shipping_required(checkout_with_item, product):checkout = checkout_with_item@@ -285,10 +298,15 @@ def checkout_with_single_item(checkout, product):@pytest.fixturedef checkout_with_variant_without_inventory_tracking(- checkout, variant_without_inventory_tracking+ checkout, variant_without_inventory_tracking, address, shipping_method):variant = variant_without_inventory_trackingadd_variant_to_checkout(checkout, variant, 1)+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.store_value_in_metadata(items={"accepted": "true"})+ checkout.store_value_in_private_metadata(items={"accepted": "false"})checkout.save()return checkout