Skip to content

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

Allow automatic checkout completion (#16813)

Iga Karbowiak9ad7d3791e59
diff --git a/saleor/channel/migrations/0018_channel_automatically_complete_paid_checkouts.py b/saleor/channel/migrations/0018_channel_automatically_complete_paid_checkouts.py
new file mode 100644
index 0000000000..0a9f0f93b2
--- /dev/null
+++ b/saleor/channel/migrations/0018_channel_automatically_complete_paid_checkouts.py
@@ -0,0 +1,25 @@
+# Generated by Django 3.2.25 on 2024-09-26 09:59
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("channel", "0017_channel_include_draft_order_in_voucher_usage"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="channel",
+ name="automatically_complete_fully_paid_checkouts",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE channel_channel
+ ALTER COLUMN automatically_complete_fully_paid_checkouts
+ SET DEFAULT false;
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/channel/models.py b/saleor/channel/models.py
index 2353e23543..4585deba4b 100644
--- a/saleor/channel/models.py
+++ b/saleor/channel/models.py
@@ -47,6 +47,7 @@ class Channel(ModelWithMetadata):
include_draft_order_in_voucher_usage = models.BooleanField(default=False)
use_legacy_error_flow_for_checkout = models.BooleanField(default=True)
+ automatically_complete_fully_paid_checkouts = models.BooleanField(default=False)
class Meta(ModelWithMetadata.Meta):
ordering = ("slug",)
diff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.py
index a32e216926..7242a836fa 100644
--- a/saleor/checkout/actions.py
+++ b/saleor/checkout/actions.py
@@ -12,7 +12,7 @@ from ..core.utils.events import (
from ..payment.models import TransactionItem
from ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ..webhook.utils import get_webhooks_for_multiple_events
-from . import CheckoutChargeStatus
+from . import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .calculations import fetch_checkout_data
from .fetch import (
CheckoutInfo,
@@ -24,7 +24,8 @@ from .models import Checkout
from .payment_utils import update_refundable_for_checkout
if TYPE_CHECKING:
- from ..account.models import Address
+ from ..account.models import Address, User
+ from ..app.models import App
from ..webhook.models import Webhook
from ..plugins.manager import PluginsManager
@@ -203,13 +204,18 @@ def update_last_transaction_modified_at_for_checkout(
def transaction_amounts_for_checkout_updated(
transaction: TransactionItem,
manager: "PluginsManager",
+ user: Optional["User"],
+ app: Optional["App"],
):
+ from .tasks import automatic_checkout_completion_task
+
if not transaction.checkout_id:
return
checkout = cast(Checkout, transaction.checkout)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
previous_charge_status = checkout_info.checkout.charge_status
+ previous_authorize_status = checkout_info.checkout.authorize_status
fetch_checkout_data(checkout_info, manager, lines, force_status_update=True)
previous_charge_status_is_fully_paid = previous_charge_status in [
CheckoutChargeStatus.FULL,
@@ -239,3 +245,17 @@ def transaction_amounts_for_checkout_updated(
checkout_info=checkout_info,
lines=lines,
)
+
+ channel = checkout_info.channel
+ if (
+ channel.automatically_complete_fully_paid_checkouts
+ and
+ # ensure that checkout completion is triggered only once
+ (
+ previous_authorize_status != CheckoutAuthorizeStatus.FULL
+ and checkout_info.checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ )
+ ):
+ user_id = user.id if user else None
+ app_id = app.id if app else None
+ automatic_checkout_completion_task.delay(checkout.pk, user_id, app_id)
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index ac723651f9..798f000c42 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -618,6 +618,7 @@ def _create_order(
site_settings: Optional["SiteSettings"] = None,
metadata_list: Optional[list] = None,
private_metadata_list: Optional[list] = None,
+ is_automatic_completion: bool = False,
) -> Order:
"""Create an order from the checkout.
@@ -737,6 +738,7 @@ def _create_order(
app=app,
manager=manager,
site_settings=site_settings,
+ automatic=is_automatic_completion,
)
)
@@ -984,6 +986,7 @@ def complete_checkout_post_payment_part(
site_settings=None,
metadata_list: Optional[list] = None,
private_metadata_list: Optional[list] = None,
+ is_automatic_completion: bool = False,
) -> tuple[Optional[Order], bool, dict]:
action_required = False
action_data: dict[str, str] = {}
@@ -1015,6 +1018,7 @@ def complete_checkout_post_payment_part(
site_settings=site_settings,
metadata_list=metadata_list,
private_metadata_list=private_metadata_list,
+ is_automatic_completion=is_automatic_completion,
)
# remove checkout after order is successfully created
checkout_info.checkout.delete()
@@ -1175,6 +1179,7 @@ def _post_create_order_actions(
user: Optional[User],
app: Optional["App"],
site_settings: "SiteSettings",
+ is_automatic_completion: bool,
):
order_info = OrderInfo(
order=order,
@@ -1191,6 +1196,7 @@ def _post_create_order_actions(
app=app,
manager=manager,
site_settings=site_settings,
+ automatic=is_automatic_completion,
)
)
@@ -1210,6 +1216,7 @@ def _create_order_from_checkout(
app: Optional["App"],
metadata_list: Optional[list] = None,
private_metadata_list: Optional[list] = None,
+ is_automatic_completion: bool = False,
):
from ..order.utils import add_gift_cards_to_order
@@ -1374,6 +1381,7 @@ def _create_order_from_checkout(
user=user,
app=app,
site_settings=site_settings,
+ is_automatic_completion=is_automatic_completion,
)
return order
@@ -1386,6 +1394,7 @@ def create_order_from_checkout(
delete_checkout: bool = True,
metadata_list: Optional[list] = None,
private_metadata_list: Optional[list] = None,
+ is_automatic_completion: bool = False,
) -> Order:
"""Crate order from checkout.
@@ -1435,6 +1444,7 @@ def create_order_from_checkout(
app=app,
metadata_list=metadata_list,
private_metadata_list=private_metadata_list,
+ is_automatic_completion=is_automatic_completion,
)
if delete_checkout:
checkout_info.checkout.delete()
@@ -1482,6 +1492,7 @@ def complete_checkout(
redirect_url: Optional[str] = None,
metadata_list: Optional[list] = None,
private_metadata_list: Optional[list] = None,
+ is_automatic_completion: bool = False,
) -> tuple[Optional[Order], bool, dict]:
checkout = checkout_info.checkout
transactions = checkout_info.checkout.payment_transactions.all()
@@ -1529,6 +1540,7 @@ def complete_checkout(
redirect_url=redirect_url,
metadata_list=metadata_list,
private_metadata_list=private_metadata_list,
+ is_automatic_completion=is_automatic_completion,
)
return order, False, {}
@@ -1543,6 +1555,7 @@ def complete_checkout(
redirect_url=redirect_url,
metadata_list=metadata_list,
private_metadata_list=private_metadata_list,
+ is_automatic_completion=is_automatic_completion,
)
@@ -1555,6 +1568,7 @@ def complete_checkout_with_transaction(
redirect_url: Optional[str] = None,
metadata_list: Optional[list] = None,
private_metadata_list: Optional[list] = None,
+ is_automatic_completion: bool = False,
) -> Optional[Order]:
try:
_prepare_checkout_with_transactions(
@@ -1572,6 +1586,7 @@ def complete_checkout_with_transaction(
delete_checkout=True,
metadata_list=metadata_list,
private_metadata_list=private_metadata_list,
+ is_automatic_completion=is_automatic_completion,
)
except NotApplicable:
raise ValidationError(
@@ -1600,6 +1615,7 @@ def complete_checkout_with_payment(
redirect_url=None,
metadata_list: Optional[list] = None,
private_metadata_list: Optional[list] = None,
+ is_automatic_completion: bool = False,
) -> tuple[Optional[Order], bool, dict]:
"""Logic required to finalize the checkout and convert it to order.
@@ -1711,6 +1727,7 @@ def complete_checkout_with_payment(
site_settings=site_settings,
metadata_list=metadata_list,
private_metadata_list=private_metadata_list,
+ is_automatic_completion=is_automatic_completion,
)
if checkout.pk:
checkout.completing_started_at = None
diff --git a/saleor/checkout/payment_utils.py b/saleor/checkout/payment_utils.py
index 48d0043b9d..aa2c30005d 100644
--- a/saleor/checkout/payment_utils.py
+++ b/saleor/checkout/payment_utils.py
@@ -54,7 +54,7 @@ def _update_authorize_status(
checkout_has_lines and checkout_total_gross <= zero_money_amount
)
- if total_covered <= zero_money_amount and checkout_with_only_zero_price_lines:
+ if checkout_with_only_zero_price_lines:
checkout.authorize_status = CheckoutAuthorizeStatus.FULL
elif total_covered == zero_money_amount:
checkout.authorize_status = CheckoutAuthorizeStatus.NONE
diff --git a/saleor/checkout/tasks.py b/saleor/checkout/tasks.py
index 2c125e2425..4b18e634d2 100644
--- a/saleor/checkout/tasks.py
+++ b/saleor/checkout/tasks.py
@@ -1,14 +1,21 @@
import logging
from decimal import Decimal
+import graphene
from celery.utils.log import get_task_logger
from django.conf import settings
+from django.core.exceptions import ValidationError
from django.db.models import Exists, OuterRef, Q, QuerySet, Subquery
from django.utils import timezone
+from ..account.models import User
+from ..app.models import App
from ..celeryconf import app
from ..core.db.connection import allow_writer
from ..payment.models import TransactionItem
+from ..plugins.manager import get_plugins_manager
+from .complete_checkout import complete_checkout
+from .fetch import fetch_checkout_info, fetch_checkout_lines
from .models import Checkout, CheckoutLine
task_logger: logging.Logger = get_task_logger(__name__)
@@ -114,3 +121,60 @@ def delete_expired_checkouts(
else:
task_logger.warning("Invocation limit reached, aborting task")
return total_deleted, has_more
+
+
[email protected](queue=settings.AUTOMATIC_CHECKOUT_COMPLETION_QUEUE_NAME)
+@allow_writer()
+def automatic_checkout_completion_task(
+ checkout_pk,
+ user_id,
+ app_id,
+):
+ """Try to automatically complete the checkout.
+
+ If any error is raised during the process, it will be caught and logged.
+ """
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_pk)
+ try:
+ checkout = Checkout.objects.get(pk=checkout_pk)
+ except Checkout.DoesNotExist:
+ return
+
+ user = User.objects.filter(pk=user_id).first()
+ app = App.objects.filter(pk=app_id).first()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ task_logger.info(
+ "Automatic checkout completion triggered for checkout: %s.",
+ checkout_id,
+ extra={"checkout_id": checkout_id},
+ )
+ try:
+ complete_checkout(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ payment_data={},
+ store_source=False,
+ user=user,
+ app=app,
+ is_automatic_completion=True,
+ )
+ except ValidationError as error:
+ task_logger.warning(
+ "Automatic checkout completion failed for checkout: %s.",
+ checkout_id,
+ extra={
+ "checkout_id": checkout_id,
+ "error": str(error),
+ },
+ )
+ else:
+ task_logger.info(
+ "Automatic checkout completion succeeded for checkout: %s.",
+ checkout_id,
+ extra={"checkout_id": checkout_id},
+ )
diff --git a/saleor/checkout/tests/test_actions.py b/saleor/checkout/tests/test_actions.py
index b51454a8cb..26fae7938a 100644
--- a/saleor/checkout/tests/test_actions.py
+++ b/saleor/checkout/tests/test_actions.py
@@ -2,6 +2,7 @@ import datetime
from decimal import Decimal
from unittest.mock import call, patch
+import before_after
import pytest
import pytz
from django.test import override_settings
@@ -11,7 +12,6 @@ from freezegun import freeze_time
from ...core.models import EventDelivery
from ...core.utils.events import call_event_including_protected_events
from ...plugins.manager import get_plugins_manager
-from ...tests.utils import flush_post_commit_hooks
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from .. import CheckoutAuthorizeStatus, CheckoutChargeStatus
from ..actions import (
@@ -24,9 +24,15 @@ from ..calculations import fetch_checkout_data
from ..fetch import fetch_checkout_info, fetch_checkout_lines
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
def test_transaction_amounts_for_checkout_updated_fully_paid(
- mocked_fully_paid, checkout_with_items, transaction_item_generator, plugins_manager
+ mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ checkout_with_items,
+ transaction_item_generator,
+ plugins_manager,
+ django_capture_on_commit_callbacks,
):
# given
checkout = checkout_with_items
@@ -36,21 +42,107 @@ def test_transaction_amounts_for_checkout_updated_fully_paid(
transaction = transaction_item_generator(
checkout_id=checkout.pk, charged_value=checkout_info.checkout.total.gross.amount
)
+ assert checkout_info.channel.automatically_complete_fully_paid_checkouts is False
# when
- transaction_amounts_for_checkout_updated(transaction, manager=plugins_manager)
+ with django_capture_on_commit_callbacks(execute=True):
+ transaction_amounts_for_checkout_updated(
+ transaction, manager=plugins_manager, user=None, app=None
+ )
# then
- flush_post_commit_hooks()
checkout.refresh_from_db()
assert checkout.charge_status == CheckoutChargeStatus.FULL
assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
mocked_fully_paid.assert_called_with(checkout, webhooks=set())
+ assert not mocked_automatic_checkout_completion_task.called
+
+
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_amounts_for_checkout_fully_paid_automatic_checkout_complete(
+ mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ checkout_with_items,
+ transaction_item_generator,
+ plugins_manager,
+ app,
+ django_capture_on_commit_callbacks,
+):
+ # given
+ checkout = checkout_with_items
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=checkout_info.checkout.total.gross.amount
+ )
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ # when
+ with django_capture_on_commit_callbacks(execute=True):
+ transaction_amounts_for_checkout_updated(
+ transaction, manager=plugins_manager, user=None, app=app
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.charge_status == CheckoutChargeStatus.FULL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())
+ mocked_automatic_checkout_completion_task.assert_called_once_with(
+ checkout.pk, None, app.id
+ )
+
+
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_amounts_for_checkout_updated_not_fully_paid_no_automatic_complete(
+ mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ checkout_with_items,
+ transaction_item_generator,
+ plugins_manager,
+ django_capture_on_commit_callbacks,
+):
+ # given
+ checkout = checkout_with_items
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=checkout_info.checkout.total.gross.amount / 2,
+ )
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ # when
+ with django_capture_on_commit_callbacks(execute=True):
+ transaction_amounts_for_checkout_updated(
+ transaction, manager=plugins_manager, user=None, app=None
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.charge_status == CheckoutChargeStatus.PARTIAL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+ assert not mocked_fully_paid.called
+ assert not mocked_automatic_checkout_completion_task.called
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
def test_transaction_amounts_for_checkout_updated_with_already_fully_paid(
- mocked_fully_paid, checkout_with_items, transaction_item_generator, plugins_manager
+ mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ checkout_with_items,
+ transaction_item_generator,
+ plugins_manager,
+ django_capture_on_commit_callbacks,
):
# given
checkout = checkout_with_items
@@ -60,6 +152,7 @@ def test_transaction_amounts_for_checkout_updated_with_already_fully_paid(
transaction_item_generator(
checkout_id=checkout.pk, charged_value=checkout_info.checkout.total.gross.amount
)
+ assert checkout_info.channel.automatically_complete_fully_paid_checkouts is False
fetch_checkout_data(checkout_info, plugins_manager, lines, force_status_update=True)
@@ -67,16 +160,177 @@ def test_transaction_amounts_for_checkout_updated_with_already_fully_paid(
checkout_id=checkout.pk, charged_value=checkout_info.checkout.total.gross.amount
)
# when
- transaction_amounts_for_checkout_updated(
- second_transaction, manager=plugins_manager
- )
+ with django_capture_on_commit_callbacks(execute=True):
+ transaction_amounts_for_checkout_updated(
+ second_transaction, manager=plugins_manager, user=None, app=None
+ )
# then
- flush_post_commit_hooks()
checkout.refresh_from_db()
assert checkout.charge_status == CheckoutChargeStatus.OVERCHARGED
assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
assert not mocked_fully_paid.called
+ assert not mocked_automatic_checkout_completion_task.called
+
+
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_amounts_for_checkout_updated_0_checkout_automatic_complete(
+ mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ checkout_with_item_total_0,
+ transaction_item_generator,
+ plugins_manager,
+ app,
+ django_capture_on_commit_callbacks,
+):
+ # given
+ checkout = checkout_with_item_total_0
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ transaction = transaction_item_generator(checkout_id=checkout.pk, charged_value=0)
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ # when
+ with django_capture_on_commit_callbacks(execute=True):
+ transaction_amounts_for_checkout_updated(
+ transaction, manager=plugins_manager, user=None, app=app
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.charge_status == CheckoutChargeStatus.FULL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ mocked_fully_paid.assert_called_with(checkout, webhooks=set())
+ mocked_automatic_checkout_completion_task.assert_called_once_with(
+ checkout.pk, None, app.id
+ )
+
+
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_amounts_for_checkout_updated_fully_authorized(
+ mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ checkout_with_items,
+ transaction_item_generator,
+ plugins_manager,
+ django_capture_on_commit_callbacks,
+):
+ # given
+ checkout = checkout_with_items
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ authorized_value=checkout_info.checkout.total.gross.amount,
+ )
+ assert checkout_info.channel.automatically_complete_fully_paid_checkouts is False
+
+ # when
+ with django_capture_on_commit_callbacks(execute=True):
+ transaction_amounts_for_checkout_updated(
+ transaction, manager=plugins_manager, user=None, app=None
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.charge_status == CheckoutChargeStatus.NONE
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ assert not mocked_fully_paid.called
+ assert not mocked_automatic_checkout_completion_task.called
+
+
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_amounts_for_checkout_fully_authorized_automatic_checkout_complete(
+ mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ checkout_with_items,
+ transaction_item_generator,
+ plugins_manager,
+ staff_user,
+ django_capture_on_commit_callbacks,
+):
+ # given
+ checkout = checkout_with_items
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ authorized_value=checkout_info.checkout.total.gross.amount,
+ )
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ # when
+ with django_capture_on_commit_callbacks(execute=True):
+ transaction_amounts_for_checkout_updated(
+ transaction, manager=plugins_manager, user=staff_user, app=None
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.charge_status == CheckoutChargeStatus.NONE
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ assert not mocked_fully_paid.called
+ mocked_automatic_checkout_completion_task.assert_called_once_with(
+ checkout.pk, staff_user.id, None
+ )
+
+
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_amounts_automatic_checkout_complete_called_once(
+ mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ checkout_with_items,
+ transaction_item_generator,
+ plugins_manager,
+ app,
+ django_capture_on_commit_callbacks,
+):
+ # given
+ checkout = checkout_with_items
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=checkout_info.checkout.total.gross.amount
+ )
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ # when
+ def call_again(*args, **kwargs):
+ transaction_amounts_for_checkout_updated(
+ transaction, manager=plugins_manager, user=None, app=app
+ )
+
+ with django_capture_on_commit_callbacks(execute=True):
+ with before_after.after(
+ "saleor.checkout.actions.update_last_transaction_modified_at_for_checkout",
+ call_again,
+ ):
+ transaction_amounts_for_checkout_updated(
+ transaction, manager=plugins_manager, user=None, app=app
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.charge_status == CheckoutChargeStatus.FULL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())
+ mocked_automatic_checkout_completion_task.assert_called_once_with(
+ checkout.pk, None, app.id
+ )
@pytest.mark.parametrize(
@@ -91,6 +345,7 @@ def test_transaction_amounts_for_checkout_updated_updates_last_transaction_modif
checkout_with_items,
transaction_item_generator,
plugins_manager,
+ django_capture_on_commit_callbacks,
):
# given
checkout = checkout_with_items
@@ -109,10 +364,12 @@ def test_transaction_amounts_for_checkout_updated_updates_last_transaction_modif
)
# when
- transaction_amounts_for_checkout_updated(transaction, manager=plugins_manager)
+ with django_capture_on_commit_callbacks(execute=True):
+ transaction_amounts_for_checkout_updated(
+ transaction, manager=plugins_manager, user=None, app=None
+ )
# then
- flush_post_commit_hooks()
checkout.refresh_from_db()
assert checkout.last_transaction_modified_at == transaction.modified_at
mocked_fully_paid.assert_called_with(checkout, webhooks=set())
@@ -138,7 +395,9 @@ def test_get_checkout_refundable_with_transaction_and_last_refund_success(
)
# when
- transaction_amounts_for_checkout_updated(transaction, manager=plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ transaction, manager=plugins_manager, user=None, app=None
+ )
# then
checkout.refresh_from_db()
@@ -167,7 +426,9 @@ def test_get_checkout_refundable_with_transaction_and_last_refund_failure(
)
# when
- transaction_amounts_for_checkout_updated(transaction, manager=plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ transaction, manager=plugins_manager, user=None, app=None
+ )
# then
checkout.refresh_from_db()
@@ -196,7 +457,9 @@ def test_get_checkout_refundable_with_transaction_without_funds(
)
# when
- transaction_amounts_for_checkout_updated(transaction, manager=plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ transaction, manager=plugins_manager, user=None, app=None
+ )
# then
checkout.refresh_from_db()
@@ -226,7 +489,9 @@ def test_get_checkout_refundable_with_multiple_transactions_without_funds(
transaction_item_generator(checkout_id=checkout.pk, charged_value=Decimal(0))
# when
- transaction_amounts_for_checkout_updated(first_transaction, manager=plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ first_transaction, manager=plugins_manager, user=None, app=None
+ )
# then
checkout.refresh_from_db()
@@ -258,7 +523,9 @@ def test_get_checkout_refundable_with_multiple_transactions_with_failure_refund(
)
# when
- transaction_amounts_for_checkout_updated(first_transaction, manager=plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ first_transaction, manager=plugins_manager, app=None, user=None
+ )
# then
checkout.refresh_from_db()
@@ -293,7 +560,9 @@ def test_get_checkout_refundable_with_multiple_active_transactions(
)
# when
- transaction_amounts_for_checkout_updated(first_transaction, manager=plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ first_transaction, manager=plugins_manager, user=None, app=None
+ )
# then
checkout.refresh_from_db()
@@ -996,7 +1265,9 @@ def test_transaction_amounts_for_checkout_fully_paid_triggers_sync_webhook(
# when
with django_capture_on_commit_callbacks(execute=True):
- transaction_amounts_for_checkout_updated(transaction, manager=plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ transaction, manager=plugins_manager, user=None, app=None
+ )
# then
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index f293e24d29..832f54fdbf 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -2184,6 +2184,7 @@ def test_checkout_complete_pick_transaction_flow(
redirect_url=None,
metadata_list=None,
private_metadata_list=None,
+ is_automatic_completion=False,
)
@@ -2235,6 +2236,7 @@ def test_checkout_complete_pick_transaction_flow_when_checkout_total_zero(
redirect_url=None,
metadata_list=None,
private_metadata_list=None,
+ is_automatic_completion=False,
)
@@ -2294,6 +2296,7 @@ def test_checkout_complete_pick_transaction_flow_not_authorized_no_active_paymen
redirect_url=None,
metadata_list=None,
private_metadata_list=None,
+ is_automatic_completion=False,
)
@@ -2344,6 +2347,7 @@ def test_checkout_complete_pick_payment_flow(
redirect_url=None,
metadata_list=None,
private_metadata_list=None,
+ is_automatic_completion=False,
)
@@ -2404,6 +2408,7 @@ def test_checkout_complete_pick_payment_flow_not_authorized_active_payment(
redirect_url=None,
metadata_list=None,
private_metadata_list=None,
+ is_automatic_completion=False,
)
diff --git a/saleor/checkout/tests/test_tasks.py b/saleor/checkout/tests/test_tasks.py
index e0545bfedc..39105ec9e0 100644
--- a/saleor/checkout/tests/test_tasks.py
+++ b/saleor/checkout/tests/test_tasks.py
@@ -1,13 +1,21 @@
+import logging
from datetime import timedelta
from decimal import Decimal
from unittest import mock
from uuid import UUID
+import graphene
import pytest
from django.utils import timezone
+from ...order import OrderEvents
+from ...order.models import Order
from ..models import Checkout
-from ..tasks import delete_expired_checkouts
+from ..tasks import (
+ automatic_checkout_completion_task,
+ delete_expired_checkouts,
+ task_logger,
+)
def test_delete_expired_anonymous_checkouts(checkouts_list, variant, customer_user):
@@ -454,3 +462,141 @@ def test_aborts_deleting_checkouts_when_invocation_count_exhausted(
# Should have stopped there
mocked_task.assert_not_called()
+
+
+def test_automatic_checkout_completion_task_transaction_flow(
+ checkout_with_prices,
+ transaction_item_generator,
+ app,
+ caplog,
+ django_capture_on_commit_callbacks,
+):
+ # given
+ checkout = checkout_with_prices
+ checkout_pk = checkout.pk
+
+ # allow catching the log in caplog
+ parent_logger = task_logger.parent
+ parent_logger.propagate = True
+
+ transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=checkout.total.gross.amount
+ )
+
+ # when
+ with django_capture_on_commit_callbacks(execute=True):
+ automatic_checkout_completion_task(checkout_pk, None, app.id)
+
+ # then
+ assert not Checkout.objects.filter(pk=checkout_pk).exists()
+ order = Order.objects.filter(checkout_token=checkout_pk).first()
+ assert order
+ assert order.events.filter(
+ type=OrderEvents.PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT
+ ).exists()
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_pk)
+ assert len(caplog.records) == 2
+ assert caplog.records[0].message == (
+ f"Automatic checkout completion triggered for checkout: {checkout_id}."
+ )
+ assert caplog.records[0].checkout_id == checkout_id
+ assert caplog.records[0].levelno == logging.INFO
+
+ assert caplog.records[1].message == (
+ f"Automatic checkout completion succeeded for checkout: {checkout_id}."
+ )
+ assert caplog.records[1].checkout_id == checkout_id
+ assert caplog.records[1].levelno == logging.INFO
+
+
+def test_automatic_checkout_completion_task_payment_flow(
+ checkout_ready_to_complete,
+ payment_dummy,
+ app,
+ caplog,
+ django_capture_on_commit_callbacks,
+):
+ # given
+ checkout = checkout_ready_to_complete
+ checkout_pk = checkout.pk
+
+ checkout.gift_cards.clear()
+ checkout.payments.add(payment_dummy)
+
+ # allow catching the log in caplog
+ parent_logger = task_logger.parent
+ parent_logger.propagate = True
+
+ # when
+ with django_capture_on_commit_callbacks(execute=True):
+ automatic_checkout_completion_task(checkout_pk, None, app.id)
+
+ # then
+ assert not Checkout.objects.filter(pk=checkout_pk).exists()
+ order = Order.objects.filter(checkout_token=checkout_pk).first()
+ assert order
+ assert order.events.filter(
+ type=OrderEvents.PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT
+ ).exists()
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_pk)
+ assert len(caplog.records) == 2
+ assert caplog.records[0].message == (
+ f"Automatic checkout completion triggered for checkout: {checkout_id}."
+ )
+ assert caplog.records[0].checkout_id == checkout_id
+ assert caplog.records[0].levelno == logging.INFO
+
+ assert caplog.records[1].message == (
+ f"Automatic checkout completion succeeded for checkout: {checkout_id}."
+ )
+ assert caplog.records[1].checkout_id == checkout_id
+ assert caplog.records[1].levelno == logging.INFO
+
+
+def test_automatic_checkout_completion_task_missing_checkout(checkout, caplog):
+ # given
+ checkout_pk = checkout.pk
+ checkout.delete()
+
+ # allow catching the log in caplog
+ parent_logger = task_logger.parent
+ parent_logger.propagate = True
+
+ # when
+ automatic_checkout_completion_task(checkout_pk, None, None)
+
+ # then
+ assert not caplog.records
+
+
+def test_automatic_checkout_completion_task_error_raised(checkout, app, caplog):
+ # given
+ checkout_pk = checkout.pk
+ checkout.billing_address = None
+ checkout.save(update_fields=["billing_address"])
+
+ # allow catching the log in caplog
+ parent_logger = task_logger.parent
+ parent_logger.propagate = True
+
+ # when
+ automatic_checkout_completion_task(checkout_pk, None, app.id)
+
+ # then
+ assert Checkout.objects.filter(pk=checkout_pk).exists()
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_pk)
+ assert len(caplog.records) == 2
+ assert caplog.records[0].message == (
+ f"Automatic checkout completion triggered for checkout: {checkout_id}."
+ )
+ assert caplog.records[0].checkout_id == checkout_id
+ assert caplog.records[0].levelno == logging.INFO
+
+ assert caplog.records[1].message == (
+ f"Automatic checkout completion failed for checkout: {checkout_id}."
+ )
+ assert caplog.records[1].checkout_id == checkout_id
+ assert caplog.records[1].error
+ assert caplog.records[1].levelno == logging.WARNING
diff --git a/saleor/graphql/channel/mutations/channel_create.py b/saleor/graphql/channel/mutations/channel_create.py
index c4488f40f4..023ab69610 100644
--- a/saleor/graphql/channel/mutations/channel_create.py
+++ b/saleor/graphql/channel/mutations/channel_create.py
@@ -18,6 +18,7 @@ from ...core.descriptions import (
ADDED_IN_315,
ADDED_IN_316,
ADDED_IN_318,
+ ADDED_IN_320,
DEPRECATED_IN_3X_INPUT,
PREVIEW_FEATURE,
)
@@ -76,6 +77,18 @@ class CheckoutSettingsInput(BaseInputObjectType):
+ DEPRECATED_IN_3X_INPUT
)
)
+ automatically_complete_fully_paid_checkouts = graphene.Boolean(
+ description=(
+ "Default `false`. Determines if the paid checkouts should be automatically "
+ "completed. This setting applies only to checkouts where payment "
+ "was processed through transactions."
+ "When enabled, the checkout will be automatically completed once the "
+ "checkout `charge_status` reaches `FULL`. This occurs when the total sum "
+ "of charged and authorized transaction amounts equals or exceeds the "
+ "checkout's total amount."
+ )
+ + ADDED_IN_320,
+ )
class Meta:
doc_category = DOC_CATEGORY_CHECKOUT
diff --git a/saleor/graphql/channel/mutations/utils.py b/saleor/graphql/channel/mutations/utils.py
index 7109b383a0..fd778390c5 100644
--- a/saleor/graphql/channel/mutations/utils.py
+++ b/saleor/graphql/channel/mutations/utils.py
@@ -78,10 +78,13 @@ def clean_input_order_settings(
def clean_input_checkout_settings(checkout_settings: dict, cleaned_input: dict):
- if "use_legacy_error_flow" in checkout_settings:
- cleaned_input["use_legacy_error_flow_for_checkout"] = checkout_settings[
- "use_legacy_error_flow"
- ]
+ input_to_model_fields = {
+ "use_legacy_error_flow": "use_legacy_error_flow_for_checkout",
+ "automatically_complete_fully_paid_checkouts": "automatically_complete_fully_paid_checkouts",
+ }
+ for input_field, model_field in input_to_model_fields.items():
+ if input_field in checkout_settings:
+ cleaned_input[model_field] = checkout_settings[input_field]
def clean_input_payment_settings(payment_settings: dict, cleaned_input: dict):
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_create.py b/saleor/graphql/channel/tests/mutations/test_channel_create.py
index caf7376b1e..3a99ab3c9e 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_create.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_create.py
@@ -50,6 +50,7 @@ CHANNEL_CREATE_MUTATION = """
}
checkoutSettings {
useLegacyErrorFlow
+ automaticallyCompleteFullyPaidCheckouts
}
paymentSettings {
defaultTransactionFlowStrategy
@@ -122,6 +123,10 @@ def test_channel_create_mutation_as_staff_user(
assert channel_data["orderSettings"]["expireOrdersAfter"] == 10
assert channel_data["orderSettings"]["includeDraftOrderInVoucherUsage"] is True
assert channel_data["checkoutSettings"]["useLegacyErrorFlow"] is False
+ assert (
+ channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]
+ is False
+ )
def test_channel_create_mutation_as_app(
@@ -139,7 +144,10 @@ def test_channel_create_mutation_as_app(
"slug": slug,
"currencyCode": currency_code,
"defaultCountry": default_country,
- "checkoutSettings": {"useLegacyErrorFlow": False},
+ "checkoutSettings": {
+ "useLegacyErrorFlow": False,
+ "automaticallyCompleteFullyPaidCheckouts": True,
+ },
}
}
@@ -176,6 +184,10 @@ def test_channel_create_mutation_as_app(
assert channel_data["orderSettings"]["expireOrdersAfter"] is None
assert channel_data["orderSettings"]["includeDraftOrderInVoucherUsage"] is False
assert channel_data["checkoutSettings"]["useLegacyErrorFlow"] is False
+ assert (
+ channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]
+ is True
+ )
def test_channel_create_mutation_as_customer(user_api_client):
@@ -764,6 +776,45 @@ def test_channel_create_set_checkout_use_legacy_error_flow(
assert channel.use_legacy_error_flow_for_checkout is False
+def test_channel_create_set_automatically_complete_fully_paid_checkouts(
+ permission_manage_channels,
+ staff_api_client,
+):
+ # given
+ name = "testName"
+ slug = "test_slug"
+ currency_code = "USD"
+ default_country = "US"
+ variables = {
+ "input": {
+ "name": name,
+ "slug": slug,
+ "currencyCode": currency_code,
+ "defaultCountry": default_country,
+ "checkoutSettings": {"automaticallyCompleteFullyPaidCheckouts": True},
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_CREATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelCreate"]
+ assert not data["errors"]
+ channel_data = data["channel"]
+ channel = Channel.objects.get()
+ assert (
+ channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]
+ is True
+ )
+ assert channel.automatically_complete_fully_paid_checkouts is True
+
+
@pytest.mark.parametrize("allowUnpaid", [True, False])
def test_channel_create_set_allow_unpaid_orders(
allowUnpaid,
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.py
index d9545cdc88..d70cc5525d 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py
@@ -1189,6 +1189,7 @@ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS = """
currencyCode
checkoutSettings {
useLegacyErrorFlow
+ automaticallyCompleteFullyPaidCheckouts
}
}
errors{
@@ -1203,15 +1204,21 @@ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS = """
"""
-def test_channel_update_set_checkout_use_legacy_error_flow(
+def test_channel_update_channel_settings(
permission_manage_channels, staff_api_client, channel_USD
):
# given
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ use_legacy_error_flow = False
+ automatically_complete_fully_paid_checkouts = True
+
variables = {
"id": channel_id,
"input": {
- "checkoutSettings": {"useLegacyErrorFlow": False},
+ "checkoutSettings": {
+ "useLegacyErrorFlow": use_legacy_error_flow,
+ "automaticallyCompleteFullyPaidCheckouts": automatically_complete_fully_paid_checkouts,
+ },
},
}
@@ -1227,20 +1234,36 @@ def test_channel_update_set_checkout_use_legacy_error_flow(
data = content["data"]["channelUpdate"]
assert not data["errors"]
channel_data = data["channel"]
+ assert (
+ channel_data["checkoutSettings"]["useLegacyErrorFlow"] == use_legacy_error_flow
+ )
+ assert (
+ channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]
+ == automatically_complete_fully_paid_checkouts
+ )
channel_USD.refresh_from_db()
- assert channel_data["checkoutSettings"]["useLegacyErrorFlow"] is False
- assert channel_USD.use_legacy_error_flow_for_checkout is False
+ assert channel_USD.use_legacy_error_flow_for_checkout == use_legacy_error_flow
+ assert (
+ channel_USD.automatically_complete_fully_paid_checkouts
+ == automatically_complete_fully_paid_checkouts
+ )
-def test_channel_update_set_checkout_use_legacy_error_flow_with_checkout_permission(
+def test_channel_update_channel_settings_with_checkout_permission(
permission_manage_checkouts, staff_api_client, channel_USD
):
# given
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ use_legacy_error_flow = False
+ automatically_complete_fully_paid_checkouts = True
+
variables = {
"id": channel_id,
"input": {
- "checkoutSettings": {"useLegacyErrorFlow": False},
+ "checkoutSettings": {
+ "useLegacyErrorFlow": use_legacy_error_flow,
+ "automaticallyCompleteFullyPaidCheckouts": automatically_complete_fully_paid_checkouts,
+ },
},
}
@@ -1256,12 +1279,22 @@ def test_channel_update_set_checkout_use_legacy_error_flow_with_checkout_permiss
data = content["data"]["channelUpdate"]
assert not data["errors"]
channel_data = data["channel"]
+ assert (
+ channel_data["checkoutSettings"]["useLegacyErrorFlow"] == use_legacy_error_flow
+ )
+ assert (
+ channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]
+ == automatically_complete_fully_paid_checkouts
+ )
channel_USD.refresh_from_db()
- assert channel_data["checkoutSettings"]["useLegacyErrorFlow"] is False
- assert channel_USD.use_legacy_error_flow_for_checkout is False
+ assert channel_USD.use_legacy_error_flow_for_checkout == use_legacy_error_flow
+ assert (
+ channel_USD.automatically_complete_fully_paid_checkouts
+ == automatically_complete_fully_paid_checkouts
+ )
-def test_channel_update_set_checkout_use_legacy_error_flow_without_permission(
+def test_channel_update_channel_settings_without_permission(
staff_api_client, channel_USD
):
# given
@@ -1269,7 +1302,10 @@ def test_channel_update_set_checkout_use_legacy_error_flow_without_permission(
variables = {
"id": channel_id,
"input": {
- "checkoutSettings": {"useLegacyErrorFlow": False},
+ "checkoutSettings": {
+ "useLegacyErrorFlow": False,
+ "automaticallyCompleteFullyPaidCheckouts": True,
+ },
},
}
diff --git a/saleor/graphql/channel/tests/queries/test_channel.py b/saleor/graphql/channel/tests/queries/test_channel.py
index e1e13b4fc4..8195abcf11 100644
--- a/saleor/graphql/channel/tests/queries/test_channel.py
+++ b/saleor/graphql/channel/tests/queries/test_channel.py
@@ -452,6 +452,7 @@ QUERY_CHANNEL_CHECKOUT_SETTINGS = """
id
checkoutSettings {
useLegacyErrorFlow
+ automaticallyCompleteFullyPaidCheckouts
}
}
}
@@ -463,7 +464,14 @@ def test_query_channel_checkout_settings_as_staff_user(
):
# given
channel_USD.use_legacy_error_flow_for_checkout = False
- channel_USD.save()
+ channel_USD.automatically_complete_fully_paid_checkouts = True
+ channel_USD.save(
+ update_fields=[
+ "use_legacy_error_flow_for_checkout",
+ "automatically_complete_fully_paid_checkouts",
+ ]
+ )
+
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
variables = {"id": channel_id}
@@ -482,6 +490,10 @@ def test_query_channel_checkout_settings_as_staff_user(
channel_data["checkoutSettings"]["useLegacyErrorFlow"]
== channel_USD.use_legacy_error_flow_for_checkout
)
+ assert (
+ channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]
+ == channel_USD.automatically_complete_fully_paid_checkouts
+ )
def test_query_channel_checkout_settings_as_app(
@@ -508,6 +520,10 @@ def test_query_channel_checkout_settings_as_app(
channel_data["checkoutSettings"]["useLegacyErrorFlow"]
== channel_USD.use_legacy_error_flow_for_checkout
)
+ assert (
+ channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]
+ == channel_USD.automatically_complete_fully_paid_checkouts
+ )
def test_query_channel_checkout_settings_as_staff_user_no_permission(
@@ -550,7 +566,13 @@ def test_query_channel_checkout_settings_with_manage_checkouts(
):
# given
channel_USD.use_legacy_error_flow_for_checkout = False
- channel_USD.save()
+ channel_USD.automatically_complete_fully_paid_checkouts = True
+ channel_USD.save(
+ update_fields=[
+ "use_legacy_error_flow_for_checkout",
+ "automatically_complete_fully_paid_checkouts",
+ ]
+ )
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
variables = {"id": channel_id}
@@ -569,6 +591,10 @@ def test_query_channel_checkout_settings_with_manage_checkouts(
channel_data["checkoutSettings"]["useLegacyErrorFlow"]
== channel_USD.use_legacy_error_flow_for_checkout
)
+ assert (
+ channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]
+ == channel_USD.automatically_complete_fully_paid_checkouts
+ )
QUERY_CHANNEL_PAYMENT_SETTINGS = """
diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.py
index 7238fa33b5..fd3b7998cb 100644
--- a/saleor/graphql/channel/types.py
+++ b/saleor/graphql/channel/types.py
@@ -201,6 +201,19 @@ class CheckoutSettings(ObjectType):
+ DEPRECATED_IN_3X_FIELD
),
)
+ automatically_complete_fully_paid_checkouts = graphene.Boolean(
+ required=True,
+ description=(
+ "Default `false`. Determines if the paid checkouts should be automatically "
+ "completed. This setting applies only to checkouts where payment "
+ "was processed through transactions."
+ "When enabled, the checkout will be automatically completed once the "
+ "checkout `charge_status` reaches `FULL`. This occurs when the total sum "
+ "of charged and authorized transaction amounts equals or exceeds the "
+ "checkout's total amount."
+ )
+ + ADDED_IN_320,
+ )
class Meta:
description = (
@@ -577,8 +590,10 @@ class Channel(ModelObjectType):
@staticmethod
def resolve_checkout_settings(root: models.Channel, _info):
+ complete_paid_checkouts = root.automatically_complete_fully_paid_checkouts
return CheckoutSettings(
- use_legacy_error_flow=root.use_legacy_error_flow_for_checkout
+ use_legacy_error_flow=root.use_legacy_error_flow_for_checkout,
+ automatically_complete_fully_paid_checkouts=complete_paid_checkouts,
)
@staticmethod
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index c2346be628..8375282c35 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -1232,6 +1232,7 @@ class Checkout(ModelObjectType[models.Checkout]):
@staticmethod
def resolve_authorize_status(root: models.Checkout, info):
+ @allow_writer_in_context(info.context)
def _resolve_authorize_status(data):
address, lines, checkout_info, manager, payloads, transactions = data
database_connection_name = get_database_connection_name(info.context)
@@ -1255,6 +1256,7 @@ class Checkout(ModelObjectType[models.Checkout]):
@staticmethod
def resolve_charge_status(root: models.Checkout, info):
+ @allow_writer_in_context(info.context)
def _resolve_charge_status(data):
address, lines, checkout_info, manager, payloads, transactions = data
database_connection_name = get_database_connection_name(info.context)
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_create.py b/saleor/graphql/payment/mutations/transaction/transaction_create.py
index 6e6642e1e5..ea8195f819 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_create.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_create.py
@@ -394,7 +394,9 @@ class TransactionCreate(BaseMutation):
previous_refunded_value=Decimal(0),
)
if transaction_data.get("checkout_id") and money_data:
- transaction_amounts_for_checkout_updated(new_transaction, manager)
+ transaction_amounts_for_checkout_updated(
+ new_transaction, manager, user, app
+ )
if transaction_event:
cls.create_transaction_event(transaction_event, new_transaction, user, app)
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
index 3f93b2b149..f1a351e2c2 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
@@ -436,7 +436,9 @@ class TransactionEventReport(ModelMutation):
calculate_order_granted_refund_status(related_granted_refund)
if transaction.checkout_id:
manager = get_plugin_manager_promise(info.context).get()
- transaction_amounts_for_checkout_updated(transaction, manager)
+ transaction_amounts_for_checkout_updated(
+ transaction, manager, user, app
+ )
elif available_actions is not None and set(
transaction.available_actions
) != set(available_actions):
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_update.py b/saleor/graphql/payment/mutations/transaction/transaction_update.py
index 50d4bdfcd8..b219a2845c 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_update.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_update.py
@@ -253,6 +253,6 @@ class TransactionUpdate(TransactionCreate):
)
if instance.checkout_id and money_data:
manager = get_plugin_manager_promise(info.context).get()
- transaction_amounts_for_checkout_updated(instance, manager)
+ transaction_amounts_for_checkout_updated(instance, manager, user, app)
return TransactionUpdate(transaction=instance)
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
index 42e58b47f5..50ff39bccb 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -8,7 +8,9 @@ from freezegun import freeze_time
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....checkout.models import Checkout
from .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderEvents, OrderStatus
+from .....order.models import Order
from .....order.utils import update_order_authorize_data, update_order_charge_data
from .....payment import TransactionEventType
from .....payment.error_codes import TransactionCreateErrorCode
@@ -1174,9 +1176,11 @@ def test_transaction_create_for_checkout_by_staff(
assert transaction.user == staff_api_client.user
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
def test_transaction_create_for_checkout_fully_paid(
mocked_checkout_fully_paid,
+ mocked_automatic_checkout_completion_task,
checkout_with_prices,
permission_manage_payments,
staff_api_client,
@@ -1196,6 +1200,8 @@ def test_transaction_create_for_checkout_fully_paid(
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ assert checkout.channel.automatically_complete_fully_paid_checkouts is False
+
variables = {
"id": graphene.Node.to_global_id("Checkout", checkout.pk),
"transaction": {
@@ -1222,6 +1228,185 @@ def test_transaction_create_for_checkout_fully_paid(
assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
mocked_checkout_fully_paid.assert_called_once_with(checkout, webhooks=set())
+ mocked_automatic_checkout_completion_task.assert_not_called()
+
+
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_create_for_checkout_fully_paid_automatic_completion(
+ mocked_checkout_fully_paid,
+ checkout_with_prices,
+ permission_manage_payments,
+ staff_api_client,
+ plugins_manager,
+):
+ # given
+ name = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.name,
+ ]
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ checkout_token = checkout.pk
+
+ variables = {
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "transaction": {
+ "name": name,
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ "amountCharged": {
+ "amount": checkout_info.checkout.total.gross.amount,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
+ }
+
+ # when
+ staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ mocked_checkout_fully_paid.assert_called_once_with(checkout, webhooks=set())
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.FULL
+ assert order.authorize_status == CheckoutAuthorizeStatus.FULL
+ assert order.events.filter(
+ type=OrderEvents.PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT
+ ).exists()
+
+
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_create_for_checkout_fully_authorized(
+ mocked_checkout_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ checkout_with_prices,
+ permission_manage_payments,
+ staff_api_client,
+ plugins_manager,
+):
+ # given
+ name = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.name,
+ ]
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+
+ assert checkout.channel.automatically_complete_fully_paid_checkouts is False
+
+ variables = {
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "transaction": {
+ "name": name,
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": checkout_info.checkout.total.gross.amount,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
+ }
+
+ # when
+ staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.charge_status == CheckoutChargeStatus.NONE
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+
+ mocked_checkout_fully_paid.assert_not_called()
+ mocked_automatic_checkout_completion_task.assert_not_called()
+
+
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_create_for_checkout_fully_authorized_automatic_completion(
+ mocked_checkout_fully_paid,
+ checkout_with_prices,
+ permission_manage_payments,
+ staff_api_client,
+ plugins_manager,
+):
+ # given
+ name = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.name,
+ ]
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ checkout_token = checkout.pk
+
+ variables = {
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "transaction": {
+ "name": name,
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": checkout_info.checkout.total.gross.amount,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
+ }
+
+ # when
+ staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ mocked_checkout_fully_paid.assert_not_called()
+
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.NONE
+ assert order.authorize_status == CheckoutAuthorizeStatus.FULL
+ assert order.events.filter(
+ type=OrderEvents.PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT
+ ).exists()
@pytest.mark.parametrize(
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
index 079ce65fa1..791878682e 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -12,7 +12,9 @@ from freezegun import freeze_time
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....order import OrderGrantedRefundStatus, OrderStatus
+from .....checkout.models import Checkout
+from .....order import OrderEvents, OrderGrantedRefundStatus, OrderStatus
+from .....order.models import Order
from .....payment import OPTIONAL_AMOUNT_EVENTS, TransactionEventType
from .....payment.models import TransactionEvent
from .....payment.transaction_item_calculations import recalculate_transaction_amounts
@@ -1355,9 +1357,11 @@ def test_transaction_event_updates_checkout_last_transaction_modified_at(
assert checkout.last_transaction_modified_at == transaction.modified_at
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
def test_transaction_event_updates_checkout_full_paid_with_charged_amount(
mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
transaction_item_generator,
app_api_client,
permission_manage_payments,
@@ -1370,6 +1374,9 @@ def test_transaction_event_updates_checkout_full_paid_with_charged_amount(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+
+ assert checkout.channel.automatically_complete_fully_paid_checkouts is False
+
psp_reference = "111-abc"
transaction = transaction_item_generator(
app=app_api_client.app, checkout_id=checkout.pk
@@ -1417,11 +1424,14 @@ def test_transaction_event_updates_checkout_full_paid_with_charged_amount(
assert checkout.charge_status == CheckoutChargeStatus.FULL
assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())
+ mocked_automatic_checkout_completion_task.assert_not_called()
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
def test_transaction_event_updates_checkout_full_paid_with_pending_charge_amount(
mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
transaction_item_generator,
app_api_client,
permission_manage_payments,
@@ -1481,6 +1491,376 @@ def test_transaction_event_updates_checkout_full_paid_with_pending_charge_amount
assert checkout.charge_status == CheckoutChargeStatus.FULL
assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())
+ mocked_automatic_checkout_completion_task.assert_not_called()
+
+
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_event_updates_checkout_full_paid_automatic_completion(
+ mocked_fully_paid,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ checkout_with_prices,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_token = checkout.token
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ psp_reference = "111-abc"
+ transaction = transaction_item_generator(
+ app=app_api_client.app, checkout_id=checkout.pk
+ )
+ transaction_item_generator(
+ app=app_api_client.app,
+ checkout_id=checkout.pk,
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": checkout_info.checkout.total.gross.amount,
+ "pspReference": psp_reference,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+ mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.FULL
+ assert order.authorize_status == CheckoutAuthorizeStatus.FULL
+ assert order.events.filter(
+ type=OrderEvents.PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT
+ ).exists()
+
+ mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())
+
+
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_event_updates_checkout_full_paid_pending_charge_automatic_complete(
+ mocked_fully_paid,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ checkout_with_prices,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_token = checkout.token
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ psp_reference = "111-abc"
+ transaction = transaction_item_generator(
+ app=app_api_client.app, checkout_id=checkout.pk
+ )
+ transaction_item_generator(
+ app=app_api_client.app,
+ checkout_id=checkout.pk,
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_REQUEST.name,
+ "amount": checkout_info.checkout.total.gross.amount,
+ "pspReference": psp_reference,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.NONE
+ assert order.authorize_status == CheckoutAuthorizeStatus.NONE
+
+ mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())
+
+
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_event_updates_checkout_fully_authorized(
+ mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ checkout_with_prices,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+
+ assert checkout.channel.automatically_complete_fully_paid_checkouts is False
+
+ psp_reference = "111-abc"
+ transaction = transaction_item_generator(
+ app=app_api_client.app, checkout_id=checkout.pk
+ )
+ transaction_item_generator(
+ app=app_api_client.app,
+ checkout_id=checkout.pk,
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.AUTHORIZATION_SUCCESS.name,
+ "amount": checkout_info.checkout.total.gross.amount,
+ "pspReference": psp_reference,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+ checkout.refresh_from_db()
+
+ assert checkout.charge_status == CheckoutChargeStatus.NONE
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ mocked_fully_paid.assert_not_called()
+ mocked_automatic_checkout_completion_task.assert_not_called()
+
+
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_event_updates_checkout_fully_authorized_automatic_complete(
+ mocked_fully_paid,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ checkout_with_prices,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+
+ checkout_token = checkout.token
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ psp_reference = "111-abc"
+ transaction = transaction_item_generator(
+ app=app_api_client.app, checkout_id=checkout.pk
+ )
+ transaction_item_generator(
+ app=app_api_client.app,
+ checkout_id=checkout.pk,
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.AUTHORIZATION_SUCCESS.name,
+ "amount": checkout_info.checkout.total.gross.amount,
+ "pspReference": psp_reference,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.NONE
+ assert order.authorize_status == CheckoutAuthorizeStatus.FULL
+ assert order.events.filter(
+ type=OrderEvents.PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT
+ ).exists()
+ mocked_fully_paid.assert_not_called()
+
+
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_event_updates_checkout_fully_authorized_pending_automatic_complete(
+ mocked_fully_paid,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ checkout_with_prices,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+
+ checkout_token = checkout.token
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ psp_reference = "111-abc"
+ transaction = transaction_item_generator(
+ app=app_api_client.app, checkout_id=checkout.pk
+ )
+ transaction_item_generator(
+ app=app_api_client.app,
+ checkout_id=checkout.pk,
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.AUTHORIZATION_REQUEST.name,
+ "amount": checkout_info.checkout.total.gross.amount,
+ "pspReference": psp_reference,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.NONE
+ assert order.authorize_status == CheckoutAuthorizeStatus.NONE
+ mocked_fully_paid.assert_not_called()
def test_transaction_event_report_with_info_event(
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
index 94ae36c006..025a0141c6 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
@@ -12,8 +12,10 @@ from .....channel import TransactionFlowStrategy
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....checkout.models import Checkout
from .....core.prices import quantize_price
-from .....order import OrderChargeStatus, OrderStatus
+from .....order import OrderChargeStatus, OrderEvents, OrderStatus
+from .....order.models import Order
from .....payment import TransactionEventType, TransactionItemIdempotencyUniqueError
from .....payment.interface import (
PaymentGatewayData,
@@ -1814,11 +1816,13 @@ def test_order_doesnt_exists(
@pytest.mark.parametrize(
"result", [TransactionEventType.CHARGE_REQUEST, TransactionEventType.CHARGE_SUCCESS]
)
[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
@mock.patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
@mock.patch("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
def test_checkout_fully_paid(
mocked_initialize,
mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
result,
user_api_client,
checkout_with_prices,
@@ -1835,6 +1839,8 @@ def test_checkout_fully_paid(
webhook_app.identifier = expected_app_identifier
webhook_app.save()
+ assert checkout_info.channel.automatically_complete_fully_paid_checkouts is False
+
expected_psp_reference = "ppp-123"
expected_response = transaction_session_response.copy()
expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
@@ -1859,10 +1865,302 @@ def test_checkout_fully_paid(
assert not content["data"]["transactionInitialize"]["errors"]
checkout.refresh_from_db()
mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())
+ mocked_automatic_checkout_completion_task.assert_not_called()
assert checkout.charge_status == CheckoutChargeStatus.FULL
assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_checkout_fully_paid_automatic_completion(
+ mocked_initialize,
+ mocked_fully_paid,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ checkout_token = checkout.token
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["transactionInitialize"]["errors"]
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.FULL
+ assert order.authorize_status == CheckoutAuthorizeStatus.FULL
+ assert order.events.filter(
+ type=OrderEvents.PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT
+ ).exists()
+ mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())
+
+
[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_checkout_fully_paid_pending_charge_automatic_completion(
+ mocked_initialize,
+ mocked_fully_paid,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ checkout_token = checkout.token
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = TransactionEventType.CHARGE_REQUEST.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["transactionInitialize"]["errors"]
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.NONE
+ assert order.authorize_status == CheckoutAuthorizeStatus.NONE
+ mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())
+
+
+ "result",
+ [
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ ],
+)
[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_checkout_fully_authorized(
+ mocked_initialize,
+ mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ result,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ assert checkout_info.channel.automatically_complete_fully_paid_checkouts is False
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = result.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["transactionInitialize"]["errors"]
+ checkout.refresh_from_db()
+ assert checkout.charge_status == CheckoutChargeStatus.NONE
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ mocked_automatic_checkout_completion_task.assert_not_called()
+ mocked_fully_paid.assert_not_called()
+
+
[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_checkout_fully_authorized_automatic_completion(
+ mocked_initialize,
+ mocked_fully_paid,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ checkout_token = checkout.token
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = TransactionEventType.AUTHORIZATION_SUCCESS.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["transactionInitialize"]["errors"]
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.NONE
+ assert order.authorize_status == CheckoutAuthorizeStatus.FULL
+ assert order.events.filter(
+ type=OrderEvents.PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT
+ ).exists()
+ mocked_fully_paid.assert_not_called()
+
+
[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_checkout_fully_authorizaed_pending_authorization_automatic_completion(
+ mocked_initialize,
+ mocked_fully_paid,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ checkout_token = checkout.token
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = TransactionEventType.AUTHORIZATION_REQUEST.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["transactionInitialize"]["errors"]
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.NONE
+ assert order.authorize_status == CheckoutAuthorizeStatus.NONE
+ mocked_fully_paid.assert_not_called()
+
+
def test_user_missing_permission_for_customer_ip_address(
user_api_client,
order_with_lines,
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
index d9780289cd..5bcd0b87e2 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
@@ -12,8 +12,10 @@ from .....channel import TransactionFlowStrategy
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....checkout.models import Checkout
from .....core.prices import quantize_price
-from .....order import OrderChargeStatus, OrderStatus
+from .....order import OrderChargeStatus, OrderEvents, OrderStatus
+from .....order.models import Order
from .....payment import FAILED_TRANSACTION_EVENTS, TransactionEventType
from .....payment.interface import (
PaymentGatewayData,
@@ -1111,11 +1113,13 @@ def test_app_attached_to_transaction_doesnt_exist(
@pytest.mark.parametrize(
"result", [TransactionEventType.CHARGE_REQUEST, TransactionEventType.CHARGE_SUCCESS]
)
[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
@mock.patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
@mock.patch("saleor.plugins.manager.PluginsManager.transaction_process_session")
def test_checkout_fully_paid(
mocked_process,
mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
result,
user_api_client,
checkout_with_prices,
@@ -1133,6 +1137,8 @@ def test_checkout_fully_paid(
webhook_app.identifier = expected_app_identifier
webhook_app.save()
+ assert checkout_info.channel.automatically_complete_fully_paid_checkouts is False
+
transaction_item = transaction_item_generator(
checkout_id=checkout.pk,
app=webhook_app,
@@ -1168,10 +1174,362 @@ def test_checkout_fully_paid(
checkout.refresh_from_db()
mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())
+ mocked_automatic_checkout_completion_task.assert_not_called()
assert checkout.charge_status == CheckoutChargeStatus.FULL
assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_checkout_fully_paid_automatic_completion(
+ mocked_process,
+ mocked_fully_paid,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+ transaction_item_generator,
+):
+ # given
+ checkout = checkout_with_prices
+ checkout_token = checkout.token
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ )
+ TransactionEvent.objects.create(
+ include_in_calculations=False,
+ transaction=transaction_item,
+ amount_value=checkout_info.checkout.total_gross_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_process.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["transactionProcess"]["errors"]
+
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.FULL
+ assert order.authorize_status == CheckoutAuthorizeStatus.FULL
+ assert order.events.filter(
+ type=OrderEvents.PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT
+ ).exists()
+ mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())
+
+
[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_checkout_fully_paid_pending_automatic_completion(
+ mocked_process,
+ mocked_fully_paid,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+ transaction_item_generator,
+):
+ # given
+ checkout = checkout_with_prices
+ checkout_token = checkout.token
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ )
+ TransactionEvent.objects.create(
+ include_in_calculations=False,
+ transaction=transaction_item,
+ amount_value=checkout_info.checkout.total_gross_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = TransactionEventType.CHARGE_REQUEST.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_process.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["transactionProcess"]["errors"]
+
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.NONE
+ assert order.authorize_status == CheckoutAuthorizeStatus.NONE
+ mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())
+
+
+ "result",
+ [
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ ],
+)
[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_checkout_fully_authorized(
+ mocked_process,
+ mocked_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ result,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+ transaction_item_generator,
+):
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ assert checkout_info.channel.automatically_complete_fully_paid_checkouts is False
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ )
+ TransactionEvent.objects.create(
+ include_in_calculations=False,
+ transaction=transaction_item,
+ amount_value=checkout_info.checkout.total_gross_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.AUTHORIZATION_REQUEST,
+ )
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = result.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_process.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["transactionProcess"]["errors"]
+
+ checkout.refresh_from_db()
+ mocked_fully_paid.assert_not_called()
+ mocked_automatic_checkout_completion_task.assert_not_called()
+ assert checkout.charge_status == CheckoutChargeStatus.NONE
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+
+
[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_checkout_fully_authorized_automatic_completion(
+ mocked_process,
+ mocked_fully_paid,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+ transaction_item_generator,
+):
+ # given
+ checkout = checkout_with_prices
+ checkout_token = checkout.token
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ )
+ TransactionEvent.objects.create(
+ include_in_calculations=False,
+ transaction=transaction_item,
+ amount_value=checkout_info.checkout.total_gross_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.AUTHORIZATION_REQUEST,
+ )
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = TransactionEventType.AUTHORIZATION_SUCCESS.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_process.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["transactionProcess"]["errors"]
+
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.NONE
+ assert order.authorize_status == CheckoutAuthorizeStatus.FULL
+ assert order.events.filter(
+ type=OrderEvents.PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT
+ ).exists()
+ mocked_fully_paid.assert_not_called()
+
+
[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_checkout_fully_authorized_pending_automatic_completion(
+ mocked_process,
+ mocked_fully_paid,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+ transaction_item_generator,
+):
+ # given
+ checkout = checkout_with_prices
+ checkout_token = checkout.token
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ )
+ TransactionEvent.objects.create(
+ include_in_calculations=False,
+ transaction=transaction_item,
+ amount_value=checkout_info.checkout.total_gross_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.AUTHORIZATION_REQUEST,
+ )
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = TransactionEventType.AUTHORIZATION_REQUEST.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_process.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["transactionProcess"]["errors"]
+
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.NONE
+ assert order.authorize_status == CheckoutAuthorizeStatus.NONE
+ mocked_fully_paid.assert_not_called()
+
+
def test_transaction_process_doesnt_accept_old_id(
user_api_client,
order_with_lines,
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
index d4a2f07c40..9dbe8497e0 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
@@ -8,7 +8,9 @@ from freezegun import freeze_time
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....checkout.models import Checkout
from .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderEvents, OrderStatus
+from .....order.models import Order
from .....payment import TransactionEventType
from .....payment.error_codes import TransactionUpdateErrorCode
from .....payment.models import TransactionEvent, TransactionItem
@@ -2584,9 +2586,11 @@ def test_transaction_update_for_checkout_updates_payment_statuses(
assert checkout_with_items.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
def test_transaction_update_for_checkout_fully_paid(
mocked_checkout_fully_paid,
+ mocked_automatic_checkout_completion_task,
checkout_with_prices,
permission_manage_payments,
app_api_client,
@@ -2609,6 +2613,8 @@ def test_transaction_update_for_checkout_fully_paid(
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ assert checkout.channel.automatically_complete_fully_paid_checkouts is False
+
variables = {
"id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
@@ -2630,6 +2636,176 @@ def test_transaction_update_for_checkout_fully_paid(
assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
mocked_checkout_fully_paid.assert_called_once_with(checkout, webhooks=set())
+ mocked_automatic_checkout_completion_task.assert_not_called()
+
+
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_update_for_checkout_fully_paid_automatic_completion(
+ mocked_checkout_fully_paid,
+ checkout_with_prices,
+ permission_manage_payments,
+ app_api_client,
+ transaction_item_generator,
+ app,
+ plugins_manager,
+):
+ # given
+ current_authorized_value = Decimal("1")
+ current_charged_value = Decimal("2")
+ transaction = transaction_item_generator(
+ checkout_id=checkout_with_prices.pk,
+ app=app,
+ authorized_value=current_authorized_value,
+ charged_value=current_charged_value,
+ )
+
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_token = checkout.token
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "amountCharged": {
+ "amount": checkout_info.checkout.total.gross.amount,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.FULL
+ assert order.authorize_status == CheckoutAuthorizeStatus.FULL
+ assert order.events.filter(
+ type=OrderEvents.PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT
+ ).exists()
+
+ mocked_checkout_fully_paid.assert_called_once_with(checkout, webhooks=set())
+
+
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_update_for_checkout_fully_authorized(
+ mocked_checkout_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ checkout_with_prices,
+ permission_manage_payments,
+ app_api_client,
+ transaction_item_generator,
+ app,
+ plugins_manager,
+):
+ # given
+ current_authorized_value = Decimal("1")
+ current_charged_value = Decimal("2")
+ transaction = transaction_item_generator(
+ checkout_id=checkout_with_prices.pk,
+ app=app,
+ authorized_value=current_authorized_value,
+ charged_value=current_charged_value,
+ )
+
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+
+ assert checkout.channel.automatically_complete_fully_paid_checkouts is False
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "amountAuthorized": {
+ "amount": checkout_info.checkout.total.gross.amount,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.charge_status == CheckoutChargeStatus.PARTIAL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+
+ mocked_checkout_fully_paid.assert_not_called()
+ mocked_automatic_checkout_completion_task.assert_not_called()
+
+
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_update_for_checkout_fully_authorized_automatic_completion(
+ mocked_checkout_fully_paid,
+ checkout_with_prices,
+ permission_manage_payments,
+ app_api_client,
+ transaction_item_generator,
+ app,
+ plugins_manager,
+):
+ # given
+ current_authorized_value = Decimal("1")
+ transaction = transaction_item_generator(
+ checkout_id=checkout_with_prices.pk,
+ app=app,
+ authorized_value=current_authorized_value,
+ )
+
+ checkout = checkout_with_prices
+ checkout_token = checkout.token
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "amountAuthorized": {
+ "amount": checkout_info.checkout.total.gross.amount,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ order = Order.objects.get(checkout_token=checkout_token)
+ assert order.charge_status == CheckoutChargeStatus.NONE
+ assert order.authorize_status == CheckoutAuthorizeStatus.FULL
+ assert order.events.filter(
+ type=OrderEvents.PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT
+ ).exists()
+
+ mocked_checkout_fully_paid.assert_not_called()
def test_transaction_update_accepts_old_id_for_old_transaction(
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index c1956d0f80..fd2260e545 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -5767,6 +5767,13 @@ type CheckoutSettings {
Added in Saleor 3.15.This field will be removed in Saleor 4.0.
"""
useLegacyErrorFlow: Boolean!
+
+ """
+ Default `false`. Determines if the paid checkouts should be automatically completed. This setting applies only to checkouts where payment was processed through transactions.When enabled, the checkout will be automatically completed once the checkout `charge_status` reaches `FULL`. This occurs when the total sum of charged and authorized transaction amounts equals or exceeds the checkout's total amount.
+
+ Added in Saleor 3.20.
+ """
+ automaticallyCompleteFullyPaidCheckouts: Boolean!
}
"""Represents the channel-specific payment settings."""
@@ -12948,6 +12955,7 @@ enum OrderEventsEnum @doc(category: "Orders") {
REMOVED_PRODUCTS
PLACED
PLACED_FROM_DRAFT
+ PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT
OVERSOLD_ITEMS
CANCELED
EXPIRED
@@ -29991,6 +29999,13 @@ input CheckoutSettingsInput @doc(category: "Checkout") {
DEPRECATED: this field will be removed in Saleor 4.0.
"""
useLegacyErrorFlow: Boolean
+
+ """
+ Default `false`. Determines if the paid checkouts should be automatically completed. This setting applies only to checkouts where payment was processed through transactions.When enabled, the checkout will be automatically completed once the checkout `charge_status` reaches `FULL`. This occurs when the total sum of charged and authorized transaction amounts equals or exceeds the checkout's total amount.
+
+ Added in Saleor 3.20.
+ """
+ automaticallyCompleteFullyPaidCheckouts: Boolean
}
input PaymentSettingsInput @doc(category: "Payments") {
diff --git a/saleor/order/__init__.py b/saleor/order/__init__.py
index 0257d7522a..1fa409d2ec 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -89,6 +89,7 @@ class OrderEvents:
PLACED = "placed"
PLACED_FROM_DRAFT = "placed_from_draft"
+ PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT = "placed_automatically_from_paid_checkout"
OVERSOLD_ITEMS = "oversold_items"
CANCELED = "canceled"
@@ -152,6 +153,10 @@ class OrderEvents:
(REMOVED_PRODUCTS, "Some products were removed from the order"),
(PLACED, "The order was placed"),
(PLACED_FROM_DRAFT, "The draft order was placed"),
+ (
+ PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT,
+ "The order was placed automatically from fully paid checkout",
+ ),
(OVERSOLD_ITEMS, "The draft order was placed with oversold items"),
(CANCELED, "The order was canceled"),
(EXPIRED, "The order was automatically expired"),
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index dfce853e6e..ac3266c1c7 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -283,9 +283,12 @@ def order_created(
manager: "PluginsManager",
from_draft: bool = False,
site_settings: Optional["SiteSettings"] = None,
+ automatic: bool = False,
):
order = order_info.order
- events.order_created_event(order=order, user=user, app=app, from_draft=from_draft)
+ events.order_created_event(
+ order=order, user=user, app=app, from_draft=from_draft, automatic=automatic
+ )
webhook_event_map = get_webhooks_for_multiple_events(
WEBHOOK_EVENTS_FOR_ORDER_CREATED
diff --git a/saleor/order/events.py b/saleor/order/events.py
index 857e258c08..e248674cd4 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -323,10 +323,17 @@ def draft_order_created_from_replace_event(
def order_created_event(
- *, order: Order, user: Optional[User], app: Optional[App], from_draft=False
+ *,
+ order: Order,
+ user: Optional[User],
+ app: Optional[App],
+ from_draft=False,
+ automatic=False,
) -> OrderEvent:
if from_draft:
event_type = OrderEvents.PLACED_FROM_DRAFT
+ elif automatic:
+ event_type = OrderEvents.PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT
else:
event_type = OrderEvents.PLACED
if user:
diff --git a/saleor/order/migrations/0194_alter_orderevent_type.py b/saleor/order/migrations/0194_alter_orderevent_type.py
new file mode 100644
index 0000000000..5982b90140
--- /dev/null
+++ b/saleor/order/migrations/0194_alter_orderevent_type.py
@@ -0,0 +1,80 @@
+# Generated by Django 3.2.25 on 2024-10-01 11:10
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0193_merge_20240805_0810"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="orderevent",
+ name="type",
+ field=models.CharField(
+ choices=[
+ ("DRAFT_CREATED", "draft_created"),
+ ("DRAFT_CREATED_FROM_REPLACE", "draft_created_from_replace"),
+ ("ADDED_PRODUCTS", "added_products"),
+ ("REMOVED_PRODUCTS", "removed_products"),
+ ("PLACED", "placed"),
+ ("PLACED_FROM_DRAFT", "placed_from_draft"),
+ (
+ "PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT",
+ "placed_automatically_from_paid_checkout",
+ ),
+ ("OVERSOLD_ITEMS", "oversold_items"),
+ ("CANCELED", "canceled"),
+ ("EXPIRED", "expired"),
+ ("ORDER_MARKED_AS_PAID", "order_marked_as_paid"),
+ ("ORDER_FULLY_PAID", "order_fully_paid"),
+ ("ORDER_REPLACEMENT_CREATED", "order_replacement_created"),
+ ("ORDER_DISCOUNT_ADDED", "order_discount_added"),
+ (
+ "ORDER_DISCOUNT_AUTOMATICALLY_UPDATED",
+ "order_discount_automatically_updated",
+ ),
+ ("ORDER_DISCOUNT_UPDATED", "order_discount_updated"),
+ ("ORDER_DISCOUNT_DELETED", "order_discount_deleted"),
+ ("ORDER_LINE_DISCOUNT_UPDATED", "order_line_discount_updated"),
+ ("ORDER_LINE_DISCOUNT_REMOVED", "order_line_discount_removed"),
+ ("ORDER_LINE_PRODUCT_DELETED", "order_line_product_deleted"),
+ ("ORDER_LINE_VARIANT_DELETED", "order_line_variant_deleted"),
+ ("UPDATED_ADDRESS", "updated_address"),
+ ("EMAIL_SENT", "email_sent"),
+ ("CONFIRMED", "confirmed"),
+ ("PAYMENT_AUTHORIZED", "payment_authorized"),
+ ("PAYMENT_CAPTURED", "payment_captured"),
+ ("EXTERNAL_SERVICE_NOTIFICATION", "external_service_notification"),
+ ("PAYMENT_REFUNDED", "payment_refunded"),
+ ("PAYMENT_VOIDED", "payment_voided"),
+ ("PAYMENT_FAILED", "payment_failed"),
+ ("TRANSACTION_EVENT", "transaction_event"),
+ ("TRANSACTION_CHARGE_REQUESTED", "transaction_charge_requested"),
+ ("TRANSACTION_REFUND_REQUESTED", "transaction_refund_requested"),
+ ("TRANSACTION_CANCEL_REQUESTED", "transaction_cancel_requested"),
+ (
+ "TRANSACTION_MARK_AS_PAID_FAILED",
+ "transaction_mark_as_paid_failed",
+ ),
+ ("INVOICE_REQUESTED", "invoice_requested"),
+ ("INVOICE_GENERATED", "invoice_generated"),
+ ("INVOICE_UPDATED", "invoice_updated"),
+ ("INVOICE_SENT", "invoice_sent"),
+ ("FULFILLMENT_CANCELED", "fulfillment_canceled"),
+ ("FULFILLMENT_RESTOCKED_ITEMS", "fulfillment_restocked_items"),
+ ("FULFILLMENT_FULFILLED_ITEMS", "fulfillment_fulfilled_items"),
+ ("FULFILLMENT_REFUNDED", "fulfillment_refunded"),
+ ("FULFILLMENT_RETURNED", "fulfillment_returned"),
+ ("FULFILLMENT_REPLACED", "fulfillment_replaced"),
+ ("FULFILLMENT_AWAITS_APPROVAL", "fulfillment_awaits_approval"),
+ ("TRACKING_UPDATED", "tracking_updated"),
+ ("NOTE_ADDED", "note_added"),
+ ("NOTE_UPDATED", "note_updated"),
+ ("OTHER", "other"),
+ ],
+ max_length=255,
+ ),
+ ),
+ ]
diff --git a/saleor/order/migrations/0195_merge_20241004_0811.py b/saleor/order/migrations/0195_merge_20241004_0811.py
new file mode 100644
index 0000000000..70d24bbd06
--- /dev/null
+++ b/saleor/order/migrations/0195_merge_20241004_0811.py
@@ -0,0 +1,12 @@
+# Generated by Django 4.2.15 on 2024-10-04 08:11
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0194_alter_orderevent_type"),
+ ("order", "0194_merge_20240805_0820"),
+ ]
+
+ operations = []
diff --git a/saleor/payment/tests/test_tasks.py b/saleor/payment/tests/test_tasks.py
index 044d33c735..2396992e1c 100644
--- a/saleor/payment/tests/test_tasks.py
+++ b/saleor/payment/tests/test_tasks.py
@@ -31,7 +31,9 @@ def test_transaction_release_funds_for_checkout_task_checkout_with_new_last_chan
checkout_id=checkout.pk,
charged_value=Decimal(100),
)
- transaction_amounts_for_checkout_updated(transaction_item, plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ transaction_item, plugins_manager, user=None, app=None
+ )
with freeze_time(time_before_ttl):
checkout.automatically_refundable = True
@@ -64,7 +66,9 @@ def test_transaction_release_funds_for_checkout_task_checkout_not_refundable(
checkout_id=checkout.pk,
charged_value=Decimal(100),
)
- transaction_amounts_for_checkout_updated(transaction_item, plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ transaction_item, plugins_manager, user=None, app=None
+ )
checkout.automatically_refundable = False
checkout.save(update_fields=["automatically_refundable", "last_change"])
@@ -96,7 +100,9 @@ def test_transaction_release_funds_for_checkout_task_checkout_with_new_tr_modifi
checkout_id=checkout.pk,
charged_value=Decimal(100),
)
- transaction_amounts_for_checkout_updated(transaction_item, plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ transaction_item, plugins_manager, user=None, app=None
+ )
with freeze_time(time_after_ttl):
checkout.automatically_refundable = True
@@ -129,7 +135,9 @@ def test_transaction_release_funds_for_checkout_task_checkout_with_none_status(
checkout_id=checkout.pk,
charged_value=0,
)
- transaction_amounts_for_checkout_updated(transaction_item, plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ transaction_item, plugins_manager, user=None, app=None
+ )
checkout.automatically_refundable = True
checkout.save(update_fields=["automatically_refundable", "last_change"])
@@ -251,7 +259,9 @@ def test_transaction_release_funds_for_checkout_task_refund_already_requested(
checkout_id=checkout.pk,
charged_value=Decimal(100),
)
- transaction_amounts_for_checkout_updated(transaction_item, plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ transaction_item, plugins_manager, user=None, app=None
+ )
checkout.automatically_refundable = True
checkout.save(update_fields=["automatically_refundable", "last_change"])
transaction_item.events.create(type=TransactionEventType.REFUND_REQUEST)
@@ -283,7 +293,9 @@ def test_transaction_release_funds_for_checkout_task_cancel_already_requested(
checkout_id=checkout.pk,
authorized_value=Decimal(100),
)
- transaction_amounts_for_checkout_updated(transaction_item, plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ transaction_item, plugins_manager, user=None, app=None
+ )
checkout.automatically_refundable = True
checkout.save(update_fields=["automatically_refundable", "last_change"])
transaction_item.events.create(type=TransactionEventType.CANCEL_REQUEST)
@@ -315,7 +327,9 @@ def test_transaction_release_funds_for_checkout_task_transaction_with_authorizat
checkout_id=checkout.pk,
authorized_value=Decimal(100),
)
- transaction_amounts_for_checkout_updated(transaction_item, plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ transaction_item, plugins_manager, user=None, app=None
+ )
checkout.automatically_refundable = True
checkout.save(update_fields=["automatically_refundable", "last_change"])
@@ -359,7 +373,9 @@ def test_transaction_release_funds_for_checkout_task_transaction_with_charge(
checkout_id=checkout.pk,
charged_value=Decimal(100),
)
- transaction_amounts_for_checkout_updated(transaction_item, plugins_manager)
+ transaction_amounts_for_checkout_updated(
+ transaction_item, plugins_manager, user=None, app=None
+ )
checkout.automatically_refundable = True
checkout.save(update_fields=["automatically_refundable", "last_change"])
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index 5d9e56e468..abcf13757a 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -7,6 +7,7 @@ import pytz
from django.utils import timezone
from freezegun import freeze_time
+from ...checkout import CheckoutAuthorizeStatus
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...order import OrderAuthorizeStatus, OrderChargeStatus, OrderGrantedRefundStatus
from ...plugins.manager import get_plugins_manager
@@ -987,6 +988,203 @@ def test_create_transaction_event_from_request_and_webhook_response_full_event(
assert event.type == event_type
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_create_transaction_event_from_request_when_paid(
+ mocked_checkout_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ transaction_item_generator,
+ app,
+ checkout_with_prices,
+):
+ # given
+ checkout = checkout_with_prices
+
+ transaction = transaction_item_generator(checkout_id=checkout.pk)
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=checkout.total.gross.amount,
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = checkout.total.gross.amount
+ event_type = TransactionEventType.CHARGE_SUCCESS
+
+ expected_psp_reference = "psp:122:222"
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ }
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ flush_post_commit_hooks()
+ checkout.refresh_from_db()
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ mocked_checkout_fully_paid.assert_called_once_with(checkout, webhooks=set())
+ mocked_automatic_checkout_completion_task.assert_not_called()
+
+
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_create_transaction_event_from_request_when_authorized(
+ mocked_checkout_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ transaction_item_generator,
+ app,
+ checkout_with_prices,
+):
+ # given
+ checkout = checkout_with_prices
+
+ channel = checkout.channel
+ assert channel.automatically_complete_fully_paid_checkouts is False
+
+ transaction = transaction_item_generator(checkout_id=checkout.pk)
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.AUTHORIZATION_REQUEST,
+ amount_value=checkout.total.gross.amount,
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = checkout.total.gross.amount
+ event_type = TransactionEventType.AUTHORIZATION_SUCCESS
+
+ expected_psp_reference = "psp:122:222"
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ }
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ flush_post_commit_hooks()
+ checkout.refresh_from_db()
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ mocked_checkout_fully_paid.assert_not_called()
+ mocked_automatic_checkout_completion_task.assert_not_called()
+
+
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_create_transaction_event_from_request_when_paid_triggers_checkout_completion(
+ mocked_checkout_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ transaction_item_generator,
+ app,
+ checkout_with_prices,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ transaction = transaction_item_generator(checkout_id=checkout.pk)
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=checkout.total.gross.amount,
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = checkout.total.gross.amount
+ event_type = TransactionEventType.CHARGE_SUCCESS
+
+ expected_psp_reference = "psp:122:222"
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ }
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ flush_post_commit_hooks()
+ checkout.refresh_from_db()
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ mocked_checkout_fully_paid.assert_called_once_with(checkout, webhooks=set())
+ mocked_automatic_checkout_completion_task.assert_called_once_with(
+ checkout.pk, None, app.id
+ )
+
+
+@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_create_transaction_event_from_request_when_authorized_triggers_checkout_completion(
+ mocked_checkout_fully_paid,
+ mocked_automatic_checkout_completion_task,
+ transaction_item_generator,
+ app,
+ checkout_with_prices,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+
+ channel = checkout_info.channel
+ channel.automatically_complete_fully_paid_checkouts = True
+ channel.save(update_fields=["automatically_complete_fully_paid_checkouts"])
+
+ transaction = transaction_item_generator(checkout_id=checkout.pk)
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.AUTHORIZATION_REQUEST,
+ amount_value=checkout.total.gross.amount,
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = checkout.total.gross.amount
+ event_type = TransactionEventType.AUTHORIZATION_SUCCESS
+
+ expected_psp_reference = "psp:122:222"
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ }
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ flush_post_commit_hooks()
+ checkout.refresh_from_db()
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ mocked_checkout_fully_paid.assert_not_called()
+ mocked_automatic_checkout_completion_task.assert_called_once_with(
+ checkout.pk, None, app.id
+ )
+
+
def test_create_transaction_event_from_request_and_webhook_response_incorrect_data(
transaction_item_generator,
app,
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 47e3455255..e3c6422d3e 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -1281,7 +1281,9 @@ def create_transaction_event_for_transaction_session(
previous_refunded_value=previous_refunded_value,
)
elif transaction_item.checkout_id:
- transaction_amounts_for_checkout_updated(transaction_item, manager)
+ transaction_amounts_for_checkout_updated(
+ transaction_item, manager, app=app, user=None
+ )
elif event.psp_reference and transaction_item.psp_reference != event.psp_reference:
transaction_item.psp_reference = event.psp_reference
transaction_item.save(update_fields=["psp_reference", "modified_at"])
@@ -1388,7 +1390,9 @@ def create_transaction_event_from_request_and_webhook_response(
elif transaction_item.checkout_id:
manager = get_plugins_manager(allow_replica=True)
recalculate_refundable_for_checkout(transaction_item, request_event, event)
- transaction_amounts_for_checkout_updated(transaction_item, manager)
+ transaction_amounts_for_checkout_updated(
+ transaction_item, manager, app=app, user=None
+ )
return event
diff --git a/saleor/settings.py b/saleor/settings.py
index 4f05484fcc..01f32eb677 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -934,6 +934,11 @@ COLLECTION_PRODUCT_UPDATED_QUEUE_NAME = os.environ.get(
"COLLECTION_PRODUCT_UPDATED_QUEUE_NAME", None
)
+# Queue name for execution of automatic checkout completion
+AUTOMATIC_CHECKOUT_COMPLETION_QUEUE_NAME = os.environ.get(
+ "AUTOMATIC_CHECKOUT_COMPLETION_QUEUE_NAME", None
+)
+
# Lock time for request password reset mutation per user (seconds)
RESET_PASSWORD_LOCK_TIME = parse(
os.environ.get("RESET_PASSWORD_LOCK_TIME", "15 minutes")
diff --git a/saleor/tests/e2e/channel/utils/channel_create.py b/saleor/tests/e2e/channel/utils/channel_create.py
index 686bd211c4..343d0ebfc9 100644
--- a/saleor/tests/e2e/channel/utils/channel_create.py
+++ b/saleor/tests/e2e/channel/utils/channel_create.py
@@ -41,6 +41,9 @@ mutation ChannelCreate($input: ChannelCreateInput!) {
expireOrdersAfter
deleteExpiredOrdersAfter
}
+ checkoutSettings {
+ automaticallyCompleteFullyPaidCheckouts
+ }
}
}
}
@@ -57,6 +60,7 @@ def create_channel(
shipping_zones=None,
is_active=True,
order_settings={},
+ checkout_settings={},
):
if not warehouse_ids:
warehouse_ids = []
@@ -82,6 +86,9 @@ def create_channel(
"deleteExpiredOrdersAfter": 1,
**order_settings,
},
+ "checkoutSettings": {
+ **checkout_settings,
+ },
}
}
diff --git a/saleor/tests/e2e/checkout/test_checkout_automatic_completion_authorize_flow.py b/saleor/tests/e2e/checkout/test_checkout_automatic_completion_authorize_flow.py
new file mode 100644
index 0000000000..7ba1b03481
--- /dev/null
+++ b/saleor/tests/e2e/checkout/test_checkout_automatic_completion_authorize_flow.py
@@ -0,0 +1,128 @@
+import pytest
+
+from ..orders.utils import order_by_checkout_id_query
+from ..product.utils.preparing_product import prepare_product
+from ..shop.utils import prepare_shop
+from ..transactions.utils import create_transaction
+from ..utils import assign_permissions
+from .utils import (
+ checkout_create,
+ checkout_delivery_method_update,
+)
+
+
+def test_automatically_complete_checkout_paid_by_transaction_create_authorization_flow_CORE_0127(
+ e2e_app_api_client,
+ e2e_not_logged_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_orders,
+ permission_manage_checkouts,
+ permission_manage_payments,
+ shop_permissions,
+):
+ # Before
+ permissions = [
+ *shop_permissions,
+ permission_manage_product_types_and_attributes,
+ permission_manage_orders,
+ permission_manage_checkouts,
+ permission_manage_payments,
+ ]
+ assign_permissions(e2e_app_api_client, permissions)
+
+ shop_data, _tax_config = prepare_shop(
+ e2e_app_api_client,
+ channels=[
+ {
+ "shipping_zones": [
+ {
+ "shipping_methods": [{}],
+ },
+ ],
+ "order_settings": {
+ "allowUnpaidOrders": False,
+ "automaticallyConfirmAllNewOrders": True,
+ },
+ "checkout_settings": {
+ "automaticallyCompleteFullyPaidCheckouts": True,
+ },
+ }
+ ],
+ )
+ channel_id = shop_data[0]["id"]
+ channel_slug = shop_data[0]["slug"]
+ warehouse_id = shop_data[0]["warehouse_id"]
+ shipping_method_id = shop_data[0]["shipping_zones"][0]["shipping_methods"][0]["id"]
+
+ variant_price = 10
+
+ (
+ _product_id,
+ product_variant_id,
+ _product_variant_price,
+ ) = prepare_product(
+ e2e_app_api_client,
+ warehouse_id,
+ channel_id,
+ variant_price,
+ )
+
+ assert shipping_method_id is not None
+
+ # Step 1 - Create checkout
+ lines = [
+ {"variantId": product_variant_id, "quantity": 1},
+ ]
+ checkout_data = checkout_create(
+ e2e_not_logged_api_client,
+ lines,
+ channel_slug,
+ set_default_billing_address=True,
+ set_default_shipping_address=True,
+ )
+ checkout_id = checkout_data["id"]
+
+ assert checkout_data["isShippingRequired"] is True
+ assert checkout_data["deliveryMethod"] is None
+ assert checkout_data["shippingMethod"] is None
+ subtotal_gross_amount = checkout_data["subtotalPrice"]["gross"]["amount"]
+ assert subtotal_gross_amount == float(variant_price)
+
+ # Step 2 - Update delivery method
+ checkout_data = checkout_delivery_method_update(
+ e2e_not_logged_api_client,
+ checkout_id,
+ shipping_method_id,
+ )
+ assert checkout_data["deliveryMethod"]["id"] == shipping_method_id
+ total_gross_amount = checkout_data["totalPrice"]["gross"]["amount"]
+ shipping_price = checkout_data["deliveryMethod"]["price"]["amount"]
+ assert shipping_price == 10
+ assert total_gross_amount == subtotal_gross_amount + shipping_price
+ assert checkout_data["chargeStatus"] == "NONE"
+ assert checkout_data["authorizeStatus"] == "NONE"
+
+ # Step 3 - Create transaction that authorize payment
+ psp_reference = "PSP-test"
+ transaction_data = create_transaction(
+ e2e_app_api_client,
+ checkout_id,
+ transaction_name="transaction",
+ psp_reference=psp_reference,
+ available_actions=["CHARGE", "CANCEL"],
+ amount_authorized=total_gross_amount,
+ )
+ transaction_id = transaction_data["id"]
+
+ # Step 4 - verify if the order has been created
+ order_data = order_by_checkout_id_query(e2e_app_api_client, checkout_id)
+
+ assert order_data["chargeStatus"] == "NONE"
+ assert order_data["authorizeStatus"] == "FULL"
+ assert len(order_data["transactions"]) == 1
+ assert order_data["transactions"][0]["id"] == transaction_id
+ assert order_data["transactions"][0]["pspReference"] == psp_reference
+ event_types = [event_data["type"] for event_data in order_data["events"]]
+ assert "PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT" in event_types
diff --git a/saleor/tests/e2e/checkout/test_checkout_automatic_completion_charge_flow.py b/saleor/tests/e2e/checkout/test_checkout_automatic_completion_charge_flow.py
new file mode 100644
index 0000000000..28f64225ab
--- /dev/null
+++ b/saleor/tests/e2e/checkout/test_checkout_automatic_completion_charge_flow.py
@@ -0,0 +1,143 @@
+import pytest
+
+from ..orders.utils import order_by_checkout_id_query
+from ..product.utils.preparing_product import prepare_product
+from ..shop.utils import prepare_shop
+from ..transactions.utils import create_transaction, transaction_event_report
+from ..utils import assign_permissions
+from .utils import (
+ checkout_create,
+ checkout_delivery_method_update,
+)
+
+
+def test_automatically_complete_checkout_paid_by_transaction_create_charge_flow_CORE_0128(
+ e2e_app_api_client,
+ e2e_not_logged_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_orders,
+ permission_manage_checkouts,
+ permission_manage_payments,
+ shop_permissions,
+):
+ # Before
+ permissions = [
+ *shop_permissions,
+ permission_manage_product_types_and_attributes,
+ permission_manage_orders,
+ permission_manage_checkouts,
+ permission_manage_payments,
+ ]
+ assign_permissions(e2e_app_api_client, permissions)
+
+ shop_data, _tax_config = prepare_shop(
+ e2e_app_api_client,
+ channels=[
+ {
+ "shipping_zones": [
+ {
+ "shipping_methods": [{}],
+ },
+ ],
+ "order_settings": {
+ "allowUnpaidOrders": False,
+ "automaticallyConfirmAllNewOrders": True,
+ },
+ "checkout_settings": {
+ "automaticallyCompleteFullyPaidCheckouts": True,
+ },
+ }
+ ],
+ )
+ channel_id = shop_data[0]["id"]
+ channel_slug = shop_data[0]["slug"]
+ warehouse_id = shop_data[0]["warehouse_id"]
+ shipping_method_id = shop_data[0]["shipping_zones"][0]["shipping_methods"][0]["id"]
+
+ variant_price = 10
+
+ (
+ _product_id,
+ product_variant_id,
+ _product_variant_price,
+ ) = prepare_product(
+ e2e_app_api_client,
+ warehouse_id,
+ channel_id,
+ variant_price,
+ )
+
+ assert shipping_method_id is not None
+
+ # Step 1 - Create checkout
+ lines = [
+ {"variantId": product_variant_id, "quantity": 1},
+ ]
+ checkout_data = checkout_create(
+ e2e_not_logged_api_client,
+ lines,
+ channel_slug,
+ set_default_billing_address=True,
+ set_default_shipping_address=True,
+ )
+ checkout_id = checkout_data["id"]
+
+ assert checkout_data["isShippingRequired"] is True
+ assert checkout_data["deliveryMethod"] is None
+ assert checkout_data["shippingMethod"] is None
+ subtotal_gross_amount = checkout_data["subtotalPrice"]["gross"]["amount"]
+ assert subtotal_gross_amount == float(variant_price)
+
+ # Step 2 - Update delivery method
+ checkout_data = checkout_delivery_method_update(
+ e2e_not_logged_api_client,
+ checkout_id,
+ shipping_method_id,
+ )
+ assert checkout_data["deliveryMethod"]["id"] == shipping_method_id
+ total_gross_amount = checkout_data["totalPrice"]["gross"]["amount"]
+ shipping_price = checkout_data["deliveryMethod"]["price"]["amount"]
+ assert shipping_price == 10
+ assert total_gross_amount == subtotal_gross_amount + shipping_price
+ assert checkout_data["chargeStatus"] == "NONE"
+ assert checkout_data["authorizeStatus"] == "NONE"
+
+ # Step 3 - Create transaction
+ psp_reference = "PSP-test"
+ transaction_data = create_transaction(
+ e2e_app_api_client,
+ checkout_id,
+ transaction_name="transaction",
+ psp_reference=psp_reference,
+ available_actions=["CHARGE"],
+ )
+ transaction_id = transaction_data["id"]
+
+ # Step 4 - report charge success
+ event_type = "CHARGE_SUCCESS"
+ transaction_data = transaction_event_report(
+ e2e_app_api_client,
+ transaction_id,
+ event_type,
+ total_gross_amount,
+ psp_reference,
+ external_url="https://saleor.io/event-details/123",
+ available_actions=["REFUND"],
+ )
+ assert transaction_data["transactionEvent"]["type"] == event_type
+ assert (
+ transaction_data["transactionEvent"]["amount"]["amount"] == total_gross_amount
+ )
+
+ # Step 5 - verify if the order has been created
+ order_data = order_by_checkout_id_query(e2e_app_api_client, checkout_id)
+
+ assert order_data["chargeStatus"] == "FULL"
+ assert order_data["authorizeStatus"] == "FULL"
+ assert len(order_data["transactions"]) == 1
+ assert order_data["transactions"][0]["id"] == transaction_id
+ assert order_data["transactions"][0]["pspReference"] == psp_reference
+ event_types = [event_data["type"] for event_data in order_data["events"]]
+ assert "PLACED_AUTOMATICALLY_FROM_PAID_CHECKOUT" in event_types
diff --git a/saleor/tests/e2e/checkout/test_checkout_create_partially_paid_order.py b/saleor/tests/e2e/checkout/test_checkout_create_partially_paid_order.py
index 3e48276192..f56b0e17c9 100644
--- a/saleor/tests/e2e/checkout/test_checkout_create_partially_paid_order.py
+++ b/saleor/tests/e2e/checkout/test_checkout_create_partially_paid_order.py
@@ -110,7 +110,7 @@ def test_should_be_able_to_create_partially_paid_order_core_0112(
message="Charged",
psp_reference="PSP-ref123",
available_actions=["REFUND", "CANCEL"],
- amount=1,
+ amount_charged=1,
)
# Step 4 - Complete checkout and check created order
diff --git a/saleor/tests/e2e/checkout/utils/checkout_delivery_method_update.py b/saleor/tests/e2e/checkout/utils/checkout_delivery_method_update.py
index 06907207e1..5b7bc0f3b0 100644
--- a/saleor/tests/e2e/checkout/utils/checkout_delivery_method_update.py
+++ b/saleor/tests/e2e/checkout/utils/checkout_delivery_method_update.py
@@ -13,6 +13,8 @@ mutation checkoutDeliveryMethodUpdate($checkoutId: ID!, $deliveryMethodId: ID) {
}
checkout {
id
+ chargeStatus
+ authorizeStatus
totalPrice {
gross {
amount
diff --git a/saleor/tests/e2e/orders/test_cancel_fully_paid_order.py b/saleor/tests/e2e/orders/test_cancel_fully_paid_order.py
index 2a6ab12026..0d4d3d554e 100644
--- a/saleor/tests/e2e/orders/test_cancel_fully_paid_order.py
+++ b/saleor/tests/e2e/orders/test_cancel_fully_paid_order.py
@@ -96,7 +96,7 @@ def test_cancel_fully_paid_order_CORE_0206(
message="Charged",
psp_reference="PSP-ref123",
available_actions=["REFUND", "CANCEL"],
- amount=order_total,
+ amount_charged=order_total,
)
order = order_query(e2e_staff_api_client, order_id)
diff --git a/saleor/tests/e2e/orders/test_cancel_partially_paid_order.py b/saleor/tests/e2e/orders/test_cancel_partially_paid_order.py
index ece588b354..d2a99d4800 100644
--- a/saleor/tests/e2e/orders/test_cancel_partially_paid_order.py
+++ b/saleor/tests/e2e/orders/test_cancel_partially_paid_order.py
@@ -106,7 +106,7 @@ def test_cancel_partially_paid_order_CORE_0207(
message="Charged",
psp_reference="PSP-ref123",
available_actions=["REFUND", "CANCEL"],
- amount=partial_amount,
+ amount_charged=partial_amount,
)
order = order_query(e2e_staff_api_client, order_id)
diff --git a/saleor/tests/e2e/orders/test_draft_order_complete_with_transaction.py b/saleor/tests/e2e/orders/test_draft_order_complete_with_transaction.py
index e7f6922937..ac4a3629ca 100644
--- a/saleor/tests/e2e/orders/test_draft_order_complete_with_transaction.py
+++ b/saleor/tests/e2e/orders/test_draft_order_complete_with_transaction.py
@@ -99,7 +99,7 @@ def test_draft_order_complete_with_transaction_CORE_0221(
message="Charged",
psp_reference="PSP-ref123",
available_actions=["REFUND", "CANCEL"],
- amount=order_total,
+ amount_charged=order_total,
)
order = order_query(e2e_staff_api_client, order_id)
diff --git a/saleor/tests/e2e/orders/utils/__init__.py b/saleor/tests/e2e/orders/utils/__init__.py
index 7e05754290..b65c0fbef8 100644
--- a/saleor/tests/e2e/orders/utils/__init__.py
+++ b/saleor/tests/e2e/orders/utils/__init__.py
@@ -3,6 +3,7 @@ from .draft_order_complete import draft_order_complete, raw_draft_order_complete
from .draft_order_create import draft_order_create
from .draft_order_delete import draft_order_delete
from .draft_order_update import draft_order_update
+from .order_by_checkout_id_query import order_by_checkout_id_query
from .order_cancel import order_cancel
from .order_create_from_checkout import order_create_from_checkout
from .order_discount_add import order_discount_add
@@ -24,6 +25,7 @@ __all__ = [
"draft_order_complete",
"draft_order_update",
"order_query",
+ "order_by_checkout_id_query",
"mark_order_paid",
"order_cancel",
"draft_order_delete",
diff --git a/saleor/tests/e2e/orders/utils/order_by_checkout_id_query.py b/saleor/tests/e2e/orders/utils/order_by_checkout_id_query.py
new file mode 100644
index 0000000000..1a07c92464
--- /dev/null
+++ b/saleor/tests/e2e/orders/utils/order_by_checkout_id_query.py
@@ -0,0 +1,82 @@
+from saleor.graphql.tests.utils import get_graphql_content
+
+ORDER_BY_CHECKOUT_ID_QUERY = """
+query OrderByCheckoutIdDetails($checkout_id: ID!) {
+ orders(first:1, filter: {checkoutIds: [$checkout_id]}) {
+ totalCount
+ edges {
+ node {
+ chargeStatus
+ authorizeStatus
+ availableShippingMethods {
+ id
+ active
+ }
+ paymentStatus
+ isPaid
+ payments {
+ id
+ gateway
+ paymentMethodType
+ chargeStatus
+ token
+ }
+ events {
+ type
+ }
+ channel {
+ id
+ name
+ }
+ updatedAt
+ fulfillments {
+ created
+ id
+ }
+ deliveryMethod {
+ ... on ShippingMethod {
+ id
+ name
+ active
+ }
+ }
+ shippingMethods {
+ id
+ }
+ shippingAddress {
+ country {
+ code
+ }
+ countryArea
+ firstName
+ cityArea
+ city
+ phone
+ postalCode
+ streetAddress1
+ streetAddress2
+ }
+ statusDisplay
+ status
+ transactions {
+ id
+ pspReference
+ }
+ }
+ }
+ }
+}
+
+"""
+
+
+def order_by_checkout_id_query(
+ api_client,
+ checkout_id,
+):
+ variables = {"checkout_id": checkout_id}
+
+ response = api_client.post_graphql(ORDER_BY_CHECKOUT_ID_QUERY, variables)
+ content = get_graphql_content(response)
+
+ return content["data"]["orders"]["edges"][0]["node"]
diff --git a/saleor/tests/e2e/shop/utils/preparing_shop.py b/saleor/tests/e2e/shop/utils/preparing_shop.py
index 51c6b171f5..536fa11e45 100644
--- a/saleor/tests/e2e/shop/utils/preparing_shop.py
+++ b/saleor/tests/e2e/shop/utils/preparing_shop.py
@@ -62,10 +62,11 @@ def prepare_shop(
created_channels = []
for channel_index, channel in enumerate(channels):
if channel is None:
- channel = []
+ channel = {}
created_channel = create_channel(
e2e_staff_api_client,
order_settings=channel["order_settings"],
+ checkout_settings=channel.get("checkout_settings", {}),
warehouse_ids=[warehouse_id],
)
channel_id = created_channel["id"]
@@ -76,6 +77,7 @@ def prepare_shop(
"slug": created_channel["slug"],
"shipping_zones": [],
"order_settings": created_channel["orderSettings"],
+ "checkout_settings": created_channel["checkoutSettings"],
}
)
diff --git a/saleor/tests/e2e/transactions/utils/__init__.py b/saleor/tests/e2e/transactions/utils/__init__.py
index 403fe276f4..37ea4ca2b8 100644
--- a/saleor/tests/e2e/transactions/utils/__init__.py
+++ b/saleor/tests/e2e/transactions/utils/__init__.py
@@ -1,7 +1,9 @@
from .transaction_create import create_transaction
+from .transaction_event_report import transaction_event_report
from .transaction_initialize import transaction_initialize
__all__ = [
"create_transaction",
"transaction_initialize",
+ "transaction_event_report",
]
diff --git a/saleor/tests/e2e/transactions/utils/transaction_create.py b/saleor/tests/e2e/transactions/utils/transaction_create.py
index 9b1faf1efc..0ff0ebf30d 100644
--- a/saleor/tests/e2e/transactions/utils/transaction_create.py
+++ b/saleor/tests/e2e/transactions/utils/transaction_create.py
@@ -19,6 +19,10 @@ mutation TransactionCreate($id: ID!, $transactionCreateInput: TransactionCreateI
currency
amount
}
+ authorizedAmount {
+ currency
+ amount
+ }
}
}
}
@@ -33,7 +37,8 @@ def create_transaction(
psp_reference="PSP-ref123",
available_actions=None,
currency="USD",
- amount=1,
+ amount_charged=None,
+ amount_authorized=None,
external_url="https://saleor.io/payment-id/123",
):
if not available_actions:
@@ -45,7 +50,12 @@ def create_transaction(
"message": message,
"pspReference": psp_reference,
"availableActions": available_actions,
- "amountCharged": {"currency": currency, "amount": amount},
+ "amountCharged": {"currency": currency, "amount": amount_charged}
+ if amount_charged is not None
+ else None,
+ "amountAuthorized": {"currency": currency, "amount": amount_authorized}
+ if amount_authorized is not None
+ else None,
"externalUrl": external_url,
},
}
@@ -61,7 +71,9 @@ def create_transaction(
assert data["message"] == message
assert data["pspReference"] == psp_reference
assert set(data["actions"]) == set(available_actions)
- assert data["chargedAmount"]["amount"] == amount
+ assert data["chargedAmount"]["amount"] == (amount_charged or 0)
assert data["chargedAmount"]["currency"] == currency
+ assert data["authorizedAmount"]["amount"] == (amount_authorized or 0)
+ assert data["authorizedAmount"]["currency"] == currency
return data
diff --git a/saleor/tests/e2e/transactions/utils/transaction_event_report.py b/saleor/tests/e2e/transactions/utils/transaction_event_report.py
new file mode 100644
index 0000000000..cd1e43214d
--- /dev/null
+++ b/saleor/tests/e2e/transactions/utils/transaction_event_report.py
@@ -0,0 +1,103 @@
+from ...utils import get_graphql_content
+
+TRANSACTION_EVENT_REPORT_MUTATION = """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $time: DateTime
+ $externalUrl: String
+ $message: String
+ $availableActions: [TransactionActionEnum!]!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ time: $time
+ externalUrl: $externalUrl
+ message: $message
+ availableActions: $availableActions
+ ) {
+ alreadyProcessed
+ transaction {
+ id
+ actions
+ pspReference
+ events {
+ id
+ }
+ createdBy {
+ ... on User {
+ id
+ }
+ ... on App {
+ id
+ }
+ }
+ }
+ transactionEvent {
+ id
+ createdAt
+ pspReference
+ message
+ externalUrl
+ amount {
+ currency
+ amount
+ }
+ type
+ createdBy {
+ ... on User {
+ id
+ }
+ ... on App {
+ id
+ }
+ }
+ }
+ errors {
+ field
+ code
+ }
+ }
+ }
+"""
+
+
+def transaction_event_report(
+ e2e_api_client,
+ transaction_id,
+ type,
+ amount,
+ psp_reference,
+ external_url=None,
+ event_time=None,
+ message="",
+ available_actions=None,
+):
+ if not available_actions:
+ available_actions = []
+ variables = {
+ "id": transaction_id,
+ "type": type,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "time": event_time,
+ "externalUrl": external_url,
+ "message": message,
+ "availableActions": available_actions,
+ }
+
+ response = e2e_api_client.post_graphql(TRANSACTION_EVENT_REPORT_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ assert content["data"]["transactionEventReport"]["errors"] == []
+
+ data = content["data"]["transactionEventReport"]
+ assert data["transaction"]["id"] is not None
+ assert data["transactionEvent"]["id"] is not None
+
+ return data