Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Do not create and process payment for checkout total 0 in 3.1 (#8979)
Jakub571a3b145aea
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 06c61ccfb5..d86f5863ab 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -30,7 +30,7 @@ from ..graphql.checkout.utils import (prepare_insufficient_stock_checkout_validation_error,)from ..order import OrderOrigin, OrderStatus-from ..order.actions import order_created+from ..order.actions import mark_order_as_paid, order_createdfrom ..order.fetch import OrderInfo, OrderLineInfofrom ..order.models import Order, OrderLinefrom ..order.notifications import send_order_confirmation@@ -721,21 +721,25 @@ def complete_checkout(if payment and user.is_authenticated:customer_id = fetch_customer_id(user=user, gateway=payment.gateway)- txn = _process_payment(- payment=payment, # type: ignore- customer_id=customer_id,- store_source=store_source,- payment_data=payment_data,- order_data=order_data,- manager=manager,- channel_slug=channel_slug,- )+ action_required = False+ action_data: Dict[str, str] = {}+ if payment:+ txn = _process_payment(+ payment=payment, # type: ignore+ customer_id=customer_id,+ store_source=store_source,+ payment_data=payment_data,+ order_data=order_data,+ manager=manager,+ channel_slug=channel_slug,+ )- if txn.customer_id and user.is_authenticated:- store_customer_id(user, payment.gateway, txn.customer_id) # type: ignore+ 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_required else {}+ action_required = txn.action_required+ if action_required:+ action_data = txn.action_required_dataorder = Noneif not action_required:@@ -756,4 +760,9 @@ def complete_checkout(gateway.payment_refund_or_void(payment, manager, channel_slug=channel_slug)error = prepare_insufficient_stock_checkout_validation_error(e)raise error++ # if the order total value is 0 it is paid from the definition+ if order.total.net.amount == 0:+ mark_order_as_paid(order, user, app, manager)+return order, action_required, action_datadiff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.pyindex a8cf8a1e02..5f25c584de 100644--- a/saleor/checkout/tests/test_checkout_complete.py+++ b/saleor/checkout/tests/test_checkout_complete.py@@ -18,7 +18,7 @@ from ...plugins.manager import get_plugins_managerfrom ...product.models import ProductTranslation, ProductVariantTranslationfrom ...tests.utils import flush_post_commit_hooksfrom .. import calculations-from ..complete_checkout import _create_order, _prepare_order_data+from ..complete_checkout import _create_order, _prepare_order_data, complete_checkoutfrom ..fetch import fetch_checkout_info, fetch_checkout_linesfrom ..utils import add_variant_to_checkout@@ -1089,3 +1089,105 @@ def test_create_order_use_translations(assert order_line.translated_product_name == translated_product_nameassert order_line.translated_variant_name == translated_variant_name++[email protected]("saleor.plugins.manager.PluginsManager.notify")+def test_complete_checkout_0_total_captured_payment_creates_expected_events(+ mock_notify, checkout_with_item_total_0, customer_user, channel_USD, app+):+ checkout = checkout_with_item_total_0+ checkout_user = customer_user++ # Ensure not events are existing prior+ assert not OrderEvent.objects.exists()+ assert not CustomerEvent.objects.exists()++ # Prepare valid checkout+ checkout.user = checkout_user+ checkout.billing_address = customer_user.default_billing_address+ checkout.redirect_url = "https://www.example.com"+ checkout.save()++ # Place checkout+ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ order, action_required, action_data = complete_checkout(+ checkout_info=checkout_info,+ manager=manager,+ lines=lines,+ payment_data={},+ store_source=False,+ discounts=None,+ user=customer_user,+ app=app,+ )++ flush_post_commit_hooks()+ (+ order_marked_as_paid,+ order_placed_event,+ order_confirmed_event,+ ) = order.events.all() # type: OrderEvent++ # Ensure the correct order event was created+ # is the event the expected type+ assert order_placed_event.type == OrderEvents.PLACED+ # is the user anonymous/ the customer+ assert order_placed_event.user == checkout_user+ # is the associated backref order valid+ assert order_placed_event.order is order+ # ensure a date was set+ assert order_placed_event.date+ # should not have any additional parameters+ assert not order_placed_event.parameters++ # Ensure the correct order event was created+ # is the event the expected type+ assert order_marked_as_paid.type == OrderEvents.ORDER_MARKED_AS_PAID+ # is the user anonymous/ the customer+ assert order_marked_as_paid.user == checkout_user+ # is the associated backref order valid+ assert order_marked_as_paid.order is order+ # ensure a date was set+ assert order_marked_as_paid.date+ # should not have any additional parameters+ assert not order_marked_as_paid.parameters++ expected_order_payload = {+ "order": get_default_order_payload(order, checkout.redirect_url),+ "recipient_email": order.get_customer_email(),+ "site_name": "mirumee.com",+ "domain": "mirumee.com",+ }++ # Ensure the correct order confirmed event was created+ # should be order confirmed event+ assert order_confirmed_event.type == OrderEvents.CONFIRMED+ # ensure the user is checkout user+ assert order_confirmed_event.user == checkout_user+ # ensure the order confirmed event is related to order+ assert order_confirmed_event.order is order+ # ensure a date was set+ assert order_confirmed_event.date+ # ensure the event parameters are empty+ assert order_confirmed_event.parameters == {}++ mock_notify.assert_has_calls(+ [+ mock.call(+ NotifyEventType.ORDER_CONFIRMATION,+ expected_order_payload,+ channel_slug=channel_USD.slug,+ )+ ],+ any_order=True,+ )++ # Ensure the correct customer event was created if the user was not anonymous+ placement_event = customer_user.events.get() # type: CustomerEvent+ assert placement_event.type == CustomerEvents.PLACED_ORDER # check the event type+ assert placement_event.user == customer_user # check the backref is valid+ assert placement_event.order == order # check the associated order is valid+ assert placement_event.date # ensure a date was set+ assert not placement_event.parameters # should not have any additional parametersdiff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.pyindex 94fb782c2f..ff15569d61 100644--- a/saleor/graphql/checkout/tests/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py@@ -8,6 +8,7 @@ import pytestfrom django.contrib.auth.models import AnonymousUserfrom django.db.models.aggregates import Sumfrom django.utils import timezone+from prices import Moneyfrom ....checkout import calculationsfrom ....checkout.error_codes import CheckoutErrorCode@@ -1957,3 +1958,162 @@ def test_checkout_complete_with_preorder_variant(pk=checkout.pk).exists(), "Checkout should have been deleted"order_confirmed_mock.assert_called_once_with(order)+++def test_checkout_complete_0_total_value_no_payment(+ user_api_client,+ checkout_with_item_total_0,+ address,+):+ checkout = checkout_with_item_total_0+ 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++ checkout.refresh_from_db()++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.checkout_total(+ manager=manager, checkout_info=checkout_info, lines=lines, address=address+ )+ orders_count = Order.objects.count()+ variables = {"token": checkout.token, "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["errors"]++ 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 is None+ assert order.shipping_method is None++ assert not Checkout.objects.filter(+ pk=checkout.pk+ ).exists(), "Checkout should have been deleted"+++def test_checkout_complete_0_total_value_from_voucher(+ user_api_client,+ checkout_without_shipping_required,+ shipping_method,+ address,+ voucher,+):+ checkout = checkout_without_shipping_required+ checkout.billing_address = address+ checkout.store_value_in_metadata(items={"accepted": "true"})+ checkout.store_value_in_private_metadata(items={"accepted": "false"})+ checkout.voucher_code = voucher.code+ checkout.discount = Money("10.00", "USD")++ checkout.save()++ checkout_line = checkout.lines.first()+ checkout_line_quantity = checkout_line.quantity+ checkout_line_variant = checkout_line.variant++ checkout.refresh_from_db()++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager=manager, checkout_info=checkout_info, lines=lines, address=address+ )+ orders_count = Order.objects.count()+ variables = {"token": checkout.token, "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["errors"]++ 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 is None+ assert order.shipping_method is None++ assert not Checkout.objects.filter(+ pk=checkout.pk+ ).exists(), "Checkout should have been deleted"+++def test_checkout_complete_0_total_value_from_giftcard(+ user_api_client,+ checkout_without_shipping_required,+ address,+ gift_card,+):+ checkout = checkout_without_shipping_required+ checkout.billing_address = address+ checkout.store_value_in_metadata(items={"accepted": "true"})+ checkout.store_value_in_private_metadata(items={"accepted": "false"})+ checkout.gift_cards.add(gift_card)+ checkout.save()++ checkout_line = checkout.lines.first()+ checkout_line_quantity = checkout_line.quantity+ checkout_line_variant = checkout_line.variant++ checkout.refresh_from_db()++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager=manager, checkout_info=checkout_info, lines=lines, address=address+ )+ orders_count = Order.objects.count()+ variables = {"token": checkout.token, "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["errors"]++ 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 is None+ assert order.shipping_method is None++ assert not Checkout.objects.filter(+ pk=checkout.pk+ ).exists(), "Checkout should have been deleted"diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex cdc27bf016..730b6f9527 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -259,20 +259,23 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):cls.validate_metadata_keys(metadata)metadata = {data.key: data.value for data in metadata}- payment = create_payment(- gateway=gateway,- payment_token=data.get("token", ""),- total=amount,- currency=checkout.currency,- email=checkout.get_customer_email(),- extra_data=extra_data,- # FIXME this is not a customer IP address. It is a client storefront ip- customer_ip_address=get_client_ip(info.context),- checkout=checkout,- return_url=data.get("return_url"),- store_payment_method=data["store_payment_method"],- metadata=metadata,- )+ payment = None+ if amount != 0:+ payment = create_payment(+ gateway=gateway,+ payment_token=data.get("token", ""),+ total=amount,+ currency=checkout.currency,+ email=checkout.get_customer_email(),+ extra_data=extra_data,+ # FIXME this is not a customer IP address. It is a client storefront ip+ customer_ip_address=get_client_ip(info.context),+ checkout=checkout,+ return_url=data.get("return_url"),+ store_payment_method=data["store_payment_method"],+ metadata=metadata,+ )+return CheckoutPaymentCreate(payment=payment, checkout=checkout)diff --git a/saleor/graphql/payment/tests/test_payment.py b/saleor/graphql/payment/tests/test_payment.pyindex f8ff819e58..22c7f5f499 100644--- a/saleor/graphql/payment/tests/test_payment.py+++ b/saleor/graphql/payment/tests/test_payment.py@@ -7,6 +7,7 @@ import pytestfrom ....checkout import calculationsfrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from ....checkout.utils import add_variant_to_checkoutfrom ....payment import PaymentErrorfrom ....payment.error_codes import PaymentErrorCodefrom ....payment.gateways.dummy_credit_card import (@@ -416,16 +417,19 @@ def test_use_checkout_billing_address_as_payment_billing(def test_create_payment_for_checkout_with_active_payments(- checkout_with_payments, user_api_client, address+ checkout_with_payments, user_api_client, address, product_without_shipping):# givencheckout = checkout_with_paymentsaddress.street_address_1 = "spanish-inqusition"address.save()checkout.billing_address = address+ manager = get_plugins_manager()+ variant = product_without_shipping.variants.get()+ checkout_info = fetch_checkout_info(checkout, [], [], manager)+ add_variant_to_checkout(checkout_info, variant, 1)checkout.save()- manager = get_plugins_manager()lines = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, [], manager)total = calculations.checkout_total(diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex bf9d02651a..be7a6d54a1 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -316,6 +316,15 @@ def checkout_line(checkout_with_item):return checkout_with_item.lines.first()+def checkout_with_item_total_0(checkout, product_price_0):+ variant = product_price_0.variants.get()+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())+ add_variant_to_checkout(checkout_info, variant, 1)+ checkout.save()+ return checkout++@pytest.fixturedef checkout_JPY_with_item(checkout_JPY, product_in_channel_JPY):variant = product_in_channel_JPY.variants.get()@@ -1781,6 +1790,38 @@ def shippable_gift_card_product(return product+def product_price_0(category, warehouse, channel_USD):+ product_type = ProductType.objects.create(+ name="Type with no shipping",+ slug="no-shipping",+ has_variants=False,+ is_shipping_required=False,+ )+ product = Product.objects.create(+ name="Test product",+ slug="test-product-4",+ product_type=product_type,+ category=category,+ )+ ProductChannelListing.objects.create(+ product=product,+ channel=channel_USD,+ is_published=True,+ visible_in_listings=True,+ )+ variant = ProductVariant.objects.create(product=product, sku="SKU_C")+ ProductVariantChannelListing.objects.create(+ variant=variant,+ channel=channel_USD,+ price_amount=Decimal(0),+ cost_price_amount=Decimal(0),+ currency=channel_USD.currency_code,+ )+ Stock.objects.create(product_variant=variant, warehouse=warehouse, quantity=1)+ return product++@pytest.fixturedef product_in_channel_JPY(product, channel_JPY, warehouse_JPY):ProductChannelListing.objects.create(