Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Extract checkout logic from mutation. Fix tests
Maciej Korycinski7ca37dbde7f3
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pynew file mode 100644index 0000000000..71608fce76--- /dev/null+++ b/saleor/checkout/complete_checkout.py@@ -0,0 +1,191 @@+from typing import List, Optional, Tuple++from django.core.exceptions import ValidationError+from django.db import transaction++from ..account.error_codes import AccountErrorCode+from ..account.models import User+from ..core.exceptions import InsufficientStock+from ..core.taxes import TaxError+from ..core.utils.url import validate_storefront_url+from ..discount import DiscountInfo+from ..discount.models import NotApplicable+from ..graphql.checkout.utils import ( # TODO move from graphql+ clean_checkout_payment,+ clean_checkout_shipping,+)+from ..order import models as order_models+from ..order.models import Order+from ..payment import PaymentError, gateway+from ..payment.models import Payment, Transaction+from ..payment.utils import store_customer_id+from . import models+from .calculations import calculate_checkout_total_with_gift_cards+from .error_codes import CheckoutErrorCode+from .utils import abort_order_data, create_order, get_order, prepare_order_data+++def prepare_checkout(checkout: models.Checkout, discounts, tracking_code, redirect_url):+ lines = list(checkout)++ clean_checkout_shipping(checkout, lines, discounts, CheckoutErrorCode)+ clean_checkout_payment(checkout, lines, discounts, CheckoutErrorCode)++ payment = checkout.get_last_active_payment()++ validate_payment_amount(discounts, payment, checkout)++ if redirect_url:+ try:+ validate_storefront_url(redirect_url)+ except ValidationError as error:+ raise ValidationError(+ {"redirect_url": error}, code=AccountErrorCode.INVALID.value+ )++ to_update = []+ if redirect_url and redirect_url != checkout.redirect_url:+ checkout.redirect_url = redirect_url+ to_update.append("redirect_url")++ if tracking_code and tracking_code != checkout.tracking_code:+ checkout.tracking_code = tracking_code+ to_update.append("tracking_code")++ if to_update:+ checkout.save(update_fields=to_update)+++def convert_checkout_to_order(+ checkout: models.Checkout, order_data: dict, user: Optional[User]+) -> 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+++def validate_payment_amount(discounts, payment, checkout):+ if (+ payment.total+ != calculate_checkout_total_with_gift_cards(checkout, discounts).gross.amount+ ):+ gateway.payment_refund_or_void(payment)+ raise ValidationError(+ "Payment does not cover all checkout value.",+ code=CheckoutErrorCode.CHECKOUT_NOT_FULLY_PAID.value,+ )+++def get_order_data(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 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+++def process_payment(+ payment: Payment,+ store_source: bool,+ payment_data: Optional[dict],+ order_data: dict,+) -> Transaction:+ try:+ if payment.to_confirm:+ txn = gateway.confirm(payment, additional_data=payment_data)+ else:+ txn = gateway.process_payment(+ payment=payment,+ token=payment.token,+ store_source=store_source,+ additional_data=payment_data,+ )+ payment.refresh_from_db()+ 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.value)+ return txn+++def complete_checkout(+ checkout: models.Checkout,+ payment_data,+ store_source,+ discounts,+ user,+ tracking_code=None,+ redirect_url=None,+) -> Tuple[Optional[Order], bool, dict]:+ action_required = False+ action_data = {} # type: ignore+ order = get_order(checkout.token)+ if order:+ return order, action_required, action_data+ prepare_checkout(+ checkout=checkout,+ discounts=discounts,+ tracking_code=tracking_code,+ redirect_url=redirect_url,+ )++ payment = checkout.get_last_active_payment()+ try:+ order_data = get_order_data(checkout, discounts)+ except ValidationError as error:+ gateway.payment_refund_or_void(payment)+ raise error++ txn = process_payment(+ payment=payment, # type: ignore+ store_source=store_source,+ payment_data=payment_data,+ order_data=order_data,+ )++ if txn.customer_id and user.is_authenticated:+ store_customer_id(user, payment.gateway, txn.customer_id) # type: ignore++ action_required = txn.action_required+ action_data = txn.action_required_data if action_data else {}++ if not action_required:+ 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 = 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)++ if not order:+ abort_order_data(order_data)++ return order, action_required, action_datadiff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 0f8c4769a7..dd303f9439 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -698,10 +698,7 @@ def abort_order_data(order_data: dict):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+ return Order.objects.confirmed().filter(checkout_token=checkout_token).first()@transaction.atomicdiff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 2db033a13d..82f517492d 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -1,41 +1,29 @@-from typing import List, Optional, Tuple, Union+from typing import List, Optional, Tupleimport 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 Prefetch-from ...account.error_codes import AccountErrorCode-from ...account.models import Userfrom ...checkout import models-from ...checkout.calculations import calculate_checkout_total_with_gift_cards+from ...checkout.complete_checkout import complete_checkoutfrom ...checkout.error_codes import CheckoutErrorCodefrom ...checkout.utils import (- abort_order_data,add_promo_code_to_checkout,add_variant_to_checkout,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,recalculate_checkout_discount,remove_promo_code_from_checkout,)from ...core import analyticsfrom ...core.exceptions import InsufficientStock, PermissionDenied, ProductNotPublishedfrom ...core.permissions import OrderPermissions-from ...core.taxes import TaxError-from ...core.utils.url import validate_storefront_url-from ...discount import DiscountInfo, models as voucher_model-from ...graphql.checkout.utils import clean_checkout_payment, clean_checkout_shipping-from ...order import models as order_models-from ...payment import PaymentError, gateway, models as payment_models-from ...payment.utils import store_customer_id+from ...payment import models as payment_modelsfrom ...product import models as product_modelsfrom ...warehouse.availability import check_stock_quantity, get_available_quantityfrom ..account.i18n import I18nMixin@@ -777,180 +765,6 @@ class CheckoutComplete(BaseMutation):error_type_class = CheckoutErrorerror_type_field = "checkout_errors"- @classmethod- def validate_payment_amount(cls, discounts, payment, checkout):- if (- payment.total- != calculate_checkout_total_with_gift_cards(- checkout, discounts- ).gross.amount- ):- gateway.payment_refund_or_void(payment)- raise ValidationError(- "Payment does not cover all checkout value.",- code=CheckoutErrorCode.CHECKOUT_NOT_FULLY_PAID.value,- )-- @classmethod- @transaction.atomic- def _prepare_checkout(cls, checkout: models.Checkout, context, redirect_url):- lines = list(checkout)-- discounts = context.discounts- clean_checkout_shipping(checkout, lines, discounts, CheckoutErrorCode)- clean_checkout_payment(checkout, lines, discounts, CheckoutErrorCode)-- payment = checkout.get_last_active_payment()-- cls.validate_payment_amount(discounts, payment, checkout)-- if redirect_url:- try:- validate_storefront_url(redirect_url)- except ValidationError as error:- raise ValidationError(- {"redirect_url": error}, code=AccountErrorCode.INVALID.value- )-- to_update = []- if redirect_url and redirect_url != checkout.redirect_url:- checkout.redirect_url = redirect_url- to_update.append("redirect_url")-- 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")-- if to_update:- checkout.save()-- @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_confirm- try:- if payment_confirmation:- txn = gateway.confirm(payment, additional_data=payment_data)- else:- txn = gateway.process_payment(- payment=payment,- token=payment.token,- store_source=store_source,- 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.value)- return txn-- @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-- 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: ignore-- if not txn.action_required:- 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- )-- 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- return CheckoutComplete(- order=order,- confirmation_needed=txn.action_required,- confirmation_data=txn.action_required_data if txn.action_required else {},- )-@classmethoddef perform_mutation(cls, _root, info, checkout_id, store_source, **data):checkout_token = from_global_id_strict_type(@@ -983,7 +797,23 @@ class CheckoutComplete(BaseMutation):).select_related("shipping_method", "shipping_method__shipping_zone"),)- return cls.complete_checkout(checkout, info.context, data, store_source)+ tracking_code = analytics.get_client_id(info.context)+ order, action_required, action_data = complete_checkout(+ checkout=checkout,+ payment_data=data.get("payment_data", {}),+ store_source=store_source,+ discounts=info.context.discounts,+ user=info.context.user,+ tracking_code=tracking_code,+ redirect_url=data.get("redirect_url"),+ )+ # If gateway returns information that additional steps are required we need+ # to inform the frontend and pass all required data+ return CheckoutComplete(+ order=order,+ confirmation_needed=action_required,+ confirmation_data=action_data,+ )class CheckoutAddPromoCode(BaseMutation):diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.pyindex c06bdb230d..e9dda6aa64 100644--- a/saleor/graphql/checkout/tests/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py@@ -773,12 +773,20 @@ def test_order_already_exists(assert Checkout.objects.count() == 0-@patch("saleor.graphql.checkout.mutations.create_order")+@patch("saleor.checkout.complete_checkout.create_order")def test_create_order_raises_insufficient_stock(- mocked_create_order, user_api_client, checkout_ready_to_complete,+ mocked_create_order, user_api_client, checkout_ready_to_complete, payment_dummy):mocked_create_order.side_effect = InsufficientStock("InsufficientStock")checkout = checkout_ready_to_complete+ 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()checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}@@ -786,5 +794,10 @@ def test_create_order_raises_insufficient_stock(content = get_graphql_content(response)data = content["data"]["checkoutComplete"]- assert not data["checkoutErrors"]+ assert (+ data["checkoutErrors"][0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ )assert mocked_create_order.called++ payment.refresh_from_db()+ assert payment.charge_status == ChargeStatus.FULLY_REFUNDEDdiff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.pyindex fa9a47002f..1735b3f10d 100644--- a/saleor/payment/gateways/adyen/plugin.py+++ b/saleor/payment/gateways/adyen/plugin.py@@ -455,22 +455,14 @@ class AdyenGatewayPlugin(BasePlugin):def capture_payment(self, payment_information: "PaymentData", previous_value) -> "GatewayResponse":- transaction = (- Transaction.objects.filter(- payment__id=payment_information.payment_id,- kind=TransactionKind.AUTH,- is_success=True,- )- .exclude(token__isnull=True, token__exact="")- .last()- )- if not transaction:++ if not payment_information.token:raise PaymentError("Cannot find a payment reference to capture.")result = call_capture(payment_information=payment_information,merchant_account=self.config.connection_params["merchant_account"],- token=transaction.token,+ token=payment_information.token,adyen_client=self.adyen,)diff --git a/saleor/payment/gateways/adyen/tests/conftest.py b/saleor/payment/gateways/adyen/tests/conftest.pyindex 010c9aa7c2..c58404c52f 100644--- a/saleor/payment/gateways/adyen/tests/conftest.py+++ b/saleor/payment/gateways/adyen/tests/conftest.py@@ -1,8 +1,9 @@-from decimal import Decimal-import pytest+from .....checkout import calculationsfrom .....plugins.manager import get_plugins_manager+from .... import TransactionKind+from ....models import Transactionfrom ....utils import create_paymentfrom ..plugin import AdyenGatewayPlugin@@ -51,13 +52,18 @@ def adyen_plugin(settings):@pytest.fixture-def payment_adyen_for_checkout(checkout_with_items, address):+def payment_adyen_for_checkout(checkout_with_items, address, shipping_method):checkout_with_items.billing_address = address+ checkout_with_items.shipping_address = address+ checkout_with_items.shipping_method = shipping_methodcheckout_with_items.save()+ total = calculations.calculate_checkout_total_with_gift_cards(+ checkout=checkout_with_items+ )payment = create_payment(gateway=AdyenGatewayPlugin.PLUGIN_ID,payment_token="",- total=Decimal("12.34"),+ total=total.gross.amount,currency=checkout_with_items.currency,email=checkout_with_items.email,customer_ip_address="",@@ -72,6 +78,19 @@ def payment_adyen_for_order(payment_adyen_for_checkout, order_with_lines):payment_adyen_for_checkout.checkout = Nonepayment_adyen_for_checkout.order = order_with_linespayment_adyen_for_checkout.save()++ Transaction.objects.create(+ payment=payment_adyen_for_checkout,+ action_required=False,+ kind=TransactionKind.AUTH,+ token="token",+ is_success=True,+ amount=order_with_lines.total_gross_amount,+ currency=order_with_lines.currency,+ error="",+ gateway_response={},+ action_required_data={},+ )return payment_adyen_for_checkoutdiff --git a/saleor/payment/gateways/adyen/tests/test_plugin.py b/saleor/payment/gateways/adyen/tests/test_plugin.pyindex 63259040d2..378130888b 100644--- a/saleor/payment/gateways/adyen/tests/test_plugin.py+++ b/saleor/payment/gateways/adyen/tests/test_plugin.py@@ -44,7 +44,7 @@ def test_process_payment(payment_adyen_for_checkout, checkout_with_items, adyen_assert response.is_success is Trueassert response.action_required is Falseassert response.kind == TransactionKind.AUTH- assert response.amount == Decimal("1234")+ assert response.amount == Decimal("80.00")assert response.currency == checkout_with_items.currencyassert response.transaction_id == "882595494831959A" # ID returned by Adyenassert response.error is None@@ -65,7 +65,7 @@ def test_process_payment_with_adyen_auto_capture(assert response.is_success is Trueassert response.action_required is Falseassert response.kind == TransactionKind.CAPTURE- assert response.amount == Decimal("1234")+ assert response.amount == Decimal("80.00")assert response.currency == checkout_with_items.currencyassert response.transaction_id == "882595494831959A" # ID returned by Adyenassert response.error is None@@ -84,7 +84,7 @@ def test_process_payment_with_auto_capture(assert response.is_success is Trueassert response.action_required is Falseassert response.kind == TransactionKind.CAPTURE- assert response.amount == Decimal("1234")+ assert response.amount == Decimal("80.00")assert response.currency == checkout_with_items.currencyassert response.transaction_id == "853596624248395G" # ID returned by Adyenassert response.error is None@@ -123,7 +123,7 @@ def test_process_payment_additional_action(assert response.is_success is Trueassert response.action_required is Trueassert response.kind == TransactionKind.AUTH- assert response.amount == Decimal("1234")+ assert response.amount == Decimal("80.00")assert response.currency == checkout_with_items.currencyassert response.transaction_id == "882595494831959A"assert response.error is None@@ -272,7 +272,8 @@ def test_confirm_already_processed_payment(payment_adyen_for_order, adyen_pluginassert response.kind == TransactionKind.AUTHassert response.amount == action_transaction.amountassert response.currency == action_transaction.currency- assert payment_adyen_for_order.transactions.count() == 2+ print(payment_adyen_for_order.transactions.all())+ assert payment_adyen_for_order.transactions.count() == 3def test_confirm_payment_with_adyen_auto_capture(payment_adyen_for_order, adyen_plugin):@@ -340,7 +341,7 @@ def test_refund_payment(payment_adyen_for_order, order_with_lines, adyen_plugin)assert response.is_success is Trueassert response.action_required is Falseassert response.kind == TransactionKind.REFUND_ONGOING- assert response.amount == Decimal("1234")+ assert response.amount == Decimal("80.00")assert response.currency == order_with_lines.currencyassert response.transaction_id == "882595499620961A" # ID returned by Adyen@@ -370,7 +371,7 @@ def test_void_payment(payment_adyen_for_order, order_with_lines, adyen_plugin):assert response.is_success is Trueassert response.action_required is Falseassert response.kind == TransactionKind.VOID- assert response.amount == Decimal("1234")+ assert response.amount == Decimal("80.00")assert response.currency == order_with_lines.currencyassert response.transaction_id == "853597151490739D" # ID returned by Adyen@@ -379,6 +380,7 @@ def test_void_payment(payment_adyen_for_order, order_with_lines, adyen_plugin):def test_capture_payment(payment_adyen_for_order, order_with_lines, adyen_plugin):payment_info = create_payment_information(payment_adyen_for_order,+ payment_token="882595494831959A",additional_data={"paymentMethod": {"paymentdata": "", "type": "test"}},)gateway_response = GatewayResponse(@@ -402,7 +404,7 @@ def test_capture_payment(payment_adyen_for_order, order_with_lines, adyen_pluginassert response.is_success is Trueassert response.action_required is Falseassert response.kind == TransactionKind.CAPTURE- assert response.amount == Decimal("1234")+ assert response.amount == Decimal("80.00")assert response.currency == order_with_lines.currencyassert response.transaction_id == "852595499936560C" # ID returned by Adyenassert response.payment_method_info == PaymentMethodInfo(brand="visa", type="test")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.yamldeleted file mode 100644index 2031a5c0fd..0000000000--- a/saleor/payment/gateways/adyen/tests/webhooks/cassettes/test_handle_authorization_for_checkout_wrong_total.yaml+++ /dev/null@@ -1,46 +0,0 @@-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 d25722f0ac..19139aa235 100644--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py@@ -4,6 +4,7 @@ from unittest import mockimport grapheneimport pytest+from ......checkout import calculationsfrom ......order import OrderStatusfrom ..... import ChargeStatus, TransactionKindfrom ...utils import to_adyen_price@@ -41,9 +42,24 @@ def test_handle_authorization_for_order(def test_handle_authorization_for_checkout(- notification, adyen_plugin, payment_adyen_for_checkout+ notification, adyen_plugin, payment_adyen_for_checkout, address, shipping_method,):+ checkout = payment_adyen_for_checkout.checkout+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()+ checkout_token = str(checkout.token)+payment = payment_adyen_for_checkout+ total = calculations.calculate_checkout_total_with_gift_cards(checkout=checkout)+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.to_confirm = True+ payment.save()+payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(merchant_reference=payment_id,@@ -53,74 +69,72 @@ def test_handle_authorization_for_checkout(handle_authorization(notification, config)payment.refresh_from_db()- assert payment.transactions.count() == 1- transaction = payment.transactions.get()+ assert payment.transactions.count() == 2+ transaction = payment.transactions.exclude(+ kind=TransactionKind.ACTION_TO_CONFIRM+ ).get()assert transaction.is_success is Trueassert transaction.kind == TransactionKind.AUTHassert payment.checkout is Noneassert payment.order+ assert payment.order.checkout_token == checkout_token-def test_handle_authorization_for_checkout_wrong_total(- notification, adyen_plugin, payment_adyen_for_checkout+def test_handle_authorization_with_adyen_auto_capture(+ notification, adyen_plugin, payment_adyen_for_checkout, address, shipping_method):- 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+ checkout = payment_adyen_for_checkout.checkout+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()+ payment = payment_adyen_for_checkout+ total = calculations.calculate_checkout_total_with_gift_cards(checkout=checkout)+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.to_confirm = True+ payment.save()-def test_handle_authorization_with_adyen_auto_capture(- notification, adyen_plugin, payment_adyen_for_order-):- payment = payment_adyen_for_orderpayment_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- config.connection_params["adyen_auto_capture"] = True- handle_authorization(notification, config)- assert payment.transactions.count() == 1- assert payment.transactions.get().kind == TransactionKind.CAPTURE+ plugin = adyen_plugin(adyen_auto_capture=True)+ handle_authorization(notification, plugin.config)++ assert payment.transactions.count() == 2+ transaction = payment.transactions.filter(kind=TransactionKind.CAPTURE).get()+ assert transaction.is_success is True@pytest.mark.vcrdef test_handle_authorization_with_auto_capture(- notification, adyen_plugin, payment_adyen_for_order+ notification, adyen_plugin, payment_adyen_for_checkout):- payment = payment_adyen_for_order+ payment = payment_adyen_for_checkout+ payment.to_confirm = True+ payment.save()+payment_id = graphene.Node.to_global_id("Payment", payment.pk)notification = notification(psp_reference="853596537720508F",merchant_reference=payment_id,value=to_adyen_price(payment.total, payment.currency),)- config = adyen_plugin().config- config.auto_capture = True- config.connection_params["adyen_auto_capture"] = False+ config = adyen_plugin(adyen_auto_capture=False, auto_capture=True).confighandle_authorization(notification, config)payment.refresh_from_db()assert payment.transactions.count() == 2- assert payment.transactions.first().kind == TransactionKind.AUTH- assert payment.transactions.last().kind == TransactionKind.CAPTURE+ transaction = payment.transactions.filter(kind=TransactionKind.CAPTURE).get()+ assert transaction.is_success is Trueassert payment.charge_status == ChargeStatus.FULLY_CHARGED@@ -140,7 +154,7 @@ def test_handle_authorization_with_adyen_auto_capture_and_payment_charged(handle_authorization(notification, config)# payment already has a charge status no need to handle auth action- assert payment.transactions.count() == 0+ assert payment.transactions.count() == 1def test_handle_cancel(notification, adyen_plugin, payment_adyen_for_order):@@ -156,10 +170,9 @@ def test_handle_cancel(notification, adyen_plugin, payment_adyen_for_order):handle_cancellation(notification, config)payment.order.refresh_from_db()- assert payment.transactions.count() == 1- transaction = payment.transactions.get()+ assert payment.transactions.count() == 2+ transaction = payment.transactions.filter(kind=TransactionKind.CANCEL).get()assert transaction.is_success is True- assert transaction.kind == TransactionKind.CANCELassert payment.order.status == OrderStatus.CANCELED@@ -179,7 +192,7 @@ def test_handle_cancel_already_canceleld(handle_cancellation(notification, config)- assert payment.transactions.count() == 1+ assert payment.transactions.count() == 2@mock.patch("saleor.payment.gateways.adyen.webhooks.order_captured")@@ -196,10 +209,9 @@ def test_handle_capture(handle_capture(notification, config)- assert payment.transactions.count() == 1- transaction = payment.transactions.get()+ assert payment.transactions.count() == 2+ transaction = payment.transactions.filter(kind=TransactionKind.CAPTURE).get()assert transaction.is_success is True- assert transaction.kind == TransactionKind.CAPTUREpayment.refresh_from_db()assert payment.charge_status == ChargeStatus.FULLY_CHARGEDmocked_captured.assert_called_once_with(@@ -224,7 +236,7 @@ def test_handle_capture_with_payment_already_charged(handle_capture(notification, config)# Payment is already captured so no need to save capture transaction- assert payment.transactions.count() == 0+ assert payment.transactions.count() == 1@pytest.mark.parametrize(@@ -246,10 +258,9 @@ def test_handle_failed_capture(handle_failed_capture(notification, config)- assert payment.transactions.count() == 1- transaction = payment.transactions.get()+ assert payment.transactions.count() == 2+ transaction = payment.transactions.filter(kind=TransactionKind.CAPTURE_FAILED).get()assert transaction.is_success is True- assert transaction.kind == TransactionKind.CAPTURE_FAILEDpayment.refresh_from_db()assert payment.charge_status == ChargeStatus.NOT_CHARGED@@ -270,10 +281,9 @@ def test_handle_failed_capture_partial_charge(handle_failed_capture(notification, config)- assert payment.transactions.count() == 1- transaction = payment.transactions.get()+ assert payment.transactions.count() == 2+ transaction = payment.transactions.filter(kind=TransactionKind.CAPTURE_FAILED).get()assert transaction.is_success is True- assert transaction.kind == TransactionKind.CAPTURE_FAILEDpayment.refresh_from_db()assert payment.charge_status == ChargeStatus.PARTIALLY_CHARGED@@ -289,10 +299,9 @@ def test_handle_pending(notification, adyen_plugin, payment_adyen_for_order):handle_pending(notification, config)- assert payment.transactions.count() == 1- transaction = payment.transactions.get()+ assert payment.transactions.count() == 2+ transaction = payment.transactions.filter(kind=TransactionKind.PENDING).get()assert transaction.is_success is True- assert transaction.kind == TransactionKind.PENDINGpayment.refresh_from_db()assert payment.charge_status == ChargeStatus.PENDING@@ -313,8 +322,8 @@ def test_handle_pending_with_adyen_auto_capture(# in case of autocapture we don't want to store the pending status as all payments# by default get capture status.- assert payment.transactions.count() == 1- assert payment.transactions.get().kind == TransactionKind.PENDING+ assert payment.transactions.count() == 2+ assert payment.transactions.filter(kind=TransactionKind.PENDING).first()payment.refresh_from_db()assert payment.charge_status == ChargeStatus.PENDING@@ -334,7 +343,7 @@ def test_handle_pending_already_pending(handle_pending(notification, config)- assert payment.transactions.count() == 1+ assert payment.transactions.filter(kind=TransactionKind.PENDING).exists()@mock.patch("saleor.payment.gateways.adyen.webhooks.order_refunded")@@ -354,10 +363,9 @@ def test_handle_refund(handle_refund(notification, config)- assert payment.transactions.count() == 1- transaction = payment.transactions.get()+ assert payment.transactions.count() == 2+ transaction = payment.transactions.filter(kind=TransactionKind.REFUND).get()assert transaction.is_success is True- assert transaction.kind == TransactionKind.REFUNDpayment.refresh_from_db()assert payment.charge_status == ChargeStatus.FULLY_REFUNDEDassert payment.captured_amount == Decimal("0.00")@@ -385,7 +393,7 @@ def test_handle_refund_already_refunded(handle_refund(notification, config)- assert payment.transactions.count() == 1+ assert payment.transactions.count() == 2 # AUTH, REFUNDassert not mock_order_refunded.called@@ -405,7 +413,7 @@ def test_handle_failed_refund_missing_transaction(handle_failed_refund(notification, config)- assert payment.transactions.count() == 0+ assert payment.transactions.count() == 1def test_handle_failed_refund_with_transaction_refund_ongoing(@@ -425,8 +433,8 @@ def test_handle_failed_refund_with_transaction_refund_ongoing(handle_failed_refund(notification, config)assert (- payment.transactions.count() == 3- ) # REFUND_ONGOING, REFUND_FAILED, FULLY_CHARGED+ payment.transactions.count() == 4+ ) # ACTION_TO_CONFIRM, REFUND_ONGOING, REFUND_FAILED, FULLY_CHARGEDassert payment.charge_status == ChargeStatus.FULLY_CHARGEDassert payment.total == payment.captured_amount@@ -448,7 +456,7 @@ def test_handle_failed_refund_with_transaction_refund(handle_failed_refund(notification, config)payment.refresh_from_db()- assert payment.transactions.count() == 3 # REFUND, REFUND_FAILED, FULLY_CHARGED+ assert payment.transactions.count() == 4 # REFUND, REFUND_FAILED, FULLY_CHARGEDassert payment.charge_status == ChargeStatus.FULLY_CHARGEDassert payment.total == payment.captured_amount@@ -467,7 +475,7 @@ def test_handle_reversed_refund(notification, adyen_plugin, payment_adyen_for_orhandle_reversed_refund(notification, config)payment.refresh_from_db()- assert payment.transactions.count() == 1 # REFUND_REVERSED+ assert payment.transactions.filter(kind=TransactionKind.REFUND_REVERSED).exists()assert payment.charge_status == ChargeStatus.FULLY_CHARGEDassert payment.total == payment.captured_amount@@ -489,7 +497,7 @@ def test_handle_reversed_refund_already_processed(handle_reversed_refund(notification, config)payment.refresh_from_db()- assert payment.transactions.count() == 1+ assert payment.transactions.filter(kind=TransactionKind.REFUND_REVERSED).exists()def test_webhook_not_implemented(notification, adyen_plugin, payment_adyen_for_order):diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.pyindex 10e03e60b4..e4937711ba 100644--- a/saleor/payment/gateways/adyen/webhooks.py+++ b/saleor/payment/gateways/adyen/webhooks.py@@ -9,9 +9,10 @@ from urllib.parse import urlencodeimport Adyenimport graphenefrom django.contrib.auth.hashers import check_password-from django.core.exceptions import ObjectDoesNotExist+from django.contrib.auth.models import AnonymousUser+from django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.core.handlers.wsgi import WSGIRequest-from django.db import transaction+from django.db import transaction as django_transactionfrom django.http import (HttpResponse,HttpResponseBadRequest,@@ -22,18 +23,15 @@ from django.http.request import HttpHeadersfrom django.shortcuts import redirectfrom graphql_relay import from_global_id+from ....checkout.complete_checkout import complete_checkoutfrom ....checkout.models import Checkoutfrom ....core.utils.url import prepare_url-from ....order.actions import (- cancel_order,- order_authorized,- order_captured,- order_refunded,-)+from ....discount.utils import fetch_active_discounts+from ....order.actions import cancel_order, order_captured, order_refundedfrom ....order.events import external_notification_eventfrom ....payment.models import Payment, Transactionfrom ... import ChargeStatus, PaymentError, TransactionKind-from ...gateway import capture, payment_refund_or_void+from ...gateway import payment_refund_or_voidfrom ...interface import GatewayConfig, GatewayResponsefrom ...utils import create_payment_information, create_transaction, gateway_postprocessfrom .utils import (@@ -68,7 +66,7 @@ def get_checkout(payment: Payment) -> Optional[Checkout]: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)+ .filter(pk=payment.checkout.pk).first())@@ -121,8 +119,8 @@ def create_payment_notification_for_order()-def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayConfig):+@django_transaction.atomic+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 payment@@ -134,11 +132,6 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCo}:return- kind = TransactionKind.AUTH- adyen_auto_capture = gateway_config.connection_params["adyen_auto_capture"]- if adyen_auto_capture:- kind = TransactionKind.CAPTURE-transaction_id = notification.get("pspReference")transaction = payment.transactions.filter(token=transaction_id,@@ -151,37 +144,44 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCo# We already have this transactionreturn- transaction = create_new_transaction(notification, payment, kind)- reason = notification.get("reason", "-")+ action_transaction = payment.transactions.filter(+ token=transaction_id,+ action_required=False,+ is_success=True,+ kind=TransactionKind.ACTION_TO_CONFIRM,+ ).last()- 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+ if not payment.order:+ # If the payment is not Auth/Capture, it means that user didn't return to the+ # storefront and we need to finalize the checkout asynchronously.+ if not action_transaction:+ action_transaction = create_new_transaction(+ notification, payment, TransactionKind.ACTION_TO_CONFIRM+ )++ if action_transaction.is_success and checkout: # type: ignore+ try:+ discounts = fetch_active_discounts()+ order, _, _ = complete_checkout(+ checkout=checkout,+ payment_data={},+ store_source=False,+ discounts=discounts,+ user=checkout.user or AnonymousUser(),+ )+ except ValidationError as e:+ print(e)+ payment_refund_or_void(payment)+ return+ reason = notification.get("reason", "-")+ is_success = True if notification.get("success") == "true" else Falsesuccess_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(- payment, success_msg, failed_msg, transaction.is_success- )- if not payment.order:- return-- # If saleor has enabled auto capture we need to proceed the capture action.- if gateway_config.auto_capture:- capture(payment, amount=transaction.amount)+ create_payment_notification_for_order(payment, success_msg, failed_msg, is_success)- if kind == TransactionKind.AUTH:- order_authorized(payment.order, None, transaction.amount, payment)- elif kind == TransactionKind.CAPTURE:- order_captured(payment.order, None, transaction.amount, payment)-+@django_transaction.atomicdef handle_cancellation(notification: Dict[str, Any], _gateway_config: GatewayConfig):# https://docs.adyen.com/checkout/cancel#cancellation-notifciationpayment = get_payment(notification.get("merchantReference"))@@ -221,7 +221,7 @@ def handle_cancel_or_refund(handle_cancellation(notification, gateway_config)+@django_transaction.atomicdef handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):# https://docs.adyen.com/checkout/capture#capture-notificationpayment = get_payment(notification.get("merchantReference"))@@ -260,7 +260,7 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)order_captured(payment.order, None, new_transaction.amount, payment)+@django_transaction.atomicdef handle_failed_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):# https://docs.adyen.com/checkout/capture#failed-capturepayment = get_payment(notification.get("merchantReference"))@@ -287,7 +287,7 @@ def handle_failed_capture(notification: Dict[str, Any], _gateway_config: Gatewaycreate_payment_notification_for_order(payment, msg, None, True)+@django_transaction.atomicdef handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):# https://docs.adyen.com/development-resources/webhooks/understand-notifications## event-codes"@@ -311,7 +311,7 @@ def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):)+@django_transaction.atomicdef handle_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):# https://docs.adyen.com/checkout/refund#refund-notificationpayment = get_payment(notification.get("merchantReference"))@@ -344,7 +344,7 @@ def _get_kind(transaction: Optional[Transaction]) -> str:return TransactionKind.CAPTURE+@django_transaction.atomicdef handle_failed_refund(notification: Dict[str, Any], gateway_config: GatewayConfig):# https://docs.adyen.com/checkout/refund#failed-refundpayment = get_payment(notification.get("merchantReference"))@@ -353,12 +353,10 @@ def handle_failed_refund(notification: Dict[str, Any], gateway_config: GatewayCotransaction_id = notification.get("pspReference")# take the last status of payment before we tried to perform the refund- last_transaction = payment.transactions.exclude(- kind__in=[- TransactionKind.REFUND_ONGOING,- TransactionKind.REFUND,- TransactionKind.REFUND_FAILED,- ]+ last_transaction = payment.transactions.filter(+ action_required=False,+ is_success=True,+ kind__in=[TransactionKind.AUTH, TransactionKind.CAPTURE],).last()last_kind = _get_kind(last_transaction)@@ -404,11 +402,13 @@ def handle_failed_refund(notification: Dict[str, Any], gateway_config: GatewayCo# create new failed transaction which will allows us to discover duplicated# notificationcreate_new_transaction(notification, payment, TransactionKind.REFUND_FAILED)- new_transaction = create_new_transaction(notification, payment, last_kind)+ new_transaction = create_new_transaction(+ notification, payment, TransactionKind.CAPTURE+ )gateway_postprocess(new_transaction, payment)+@django_transaction.atomicdef handle_reversed_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):@@ -445,7 +445,7 @@ def handle_refund_with_data(handle_refund(notification, gateway_config)+@django_transaction.atomicdef webhook_not_implemented(notification: Dict[str, Any], gateway_config: GatewayConfig):