Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix automatic checkout completion (#18539)
Iga Karbowiak9aa434eeefe7
diff --git a/saleor/channel/migrations/0024_channel_automatic_completion_delay.py b/saleor/channel/migrations/0024_channel_automatic_completion_delay.pynew file mode 100644index 0000000000..a87de4bc88--- /dev/null+++ b/saleor/channel/migrations/0024_channel_automatic_completion_delay.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.8 on 2025-11-13 15:31++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("channel", "0023_merge_20250709_1453"),+ ]++ operations = [+ migrations.AddField(+ model_name="channel",+ name="automatic_completion_delay",+ field=models.IntegerField(blank=True, default=None, null=True),+ ),+ ]diff --git a/saleor/channel/migrations/0025_set_automatic_completion_delay.py b/saleor/channel/migrations/0025_set_automatic_completion_delay.pynew file mode 100644index 0000000000..7f809dcc1b--- /dev/null+++ b/saleor/channel/migrations/0025_set_automatic_completion_delay.py@@ -0,0 +1,23 @@+# Generated by Django 5.2.8 on 2025-11-13 16:16++from django.db import migrations+++def set_automatic_completion_delay(apps, schema_editor):+ Channel = apps.get_model("channel", "Channel")+ Channel.objects.filter(automatically_complete_fully_paid_checkouts=True).update(+ automatic_completion_delay=0+ )+++class Migration(migrations.Migration):+ dependencies = [+ ("channel", "0024_channel_automatic_completion_delay"),+ ]++ operations = [+ migrations.RunPython(+ set_automatic_completion_delay,+ migrations.RunPython.noop,+ ),+ ]diff --git a/saleor/channel/migrations/0026_channel_automatic_completion_cut_off_date.py b/saleor/channel/migrations/0026_channel_automatic_completion_cut_off_date.pynew file mode 100644index 0000000000..ffceb9b143--- /dev/null+++ b/saleor/channel/migrations/0026_channel_automatic_completion_cut_off_date.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.8 on 2025-11-17 13:51++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("channel", "0025_set_automatic_completion_delay"),+ ]++ operations = [+ migrations.AddField(+ model_name="channel",+ name="automatic_completion_cut_off_date",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/saleor/channel/models.py b/saleor/channel/models.pyindex 4346d13d39..e33fd0eab6 100644--- a/saleor/channel/models.py+++ b/saleor/channel/models.py@@ -49,6 +49,14 @@ class Channel(ModelWithMetadata):use_legacy_error_flow_for_checkout = models.BooleanField(default=True)automatically_complete_fully_paid_checkouts = models.BooleanField(default=False)+ # automatic_completion_delay applies only when+ # automatically_complete_fully_paid_checkouts is set to True+ automatic_completion_delay = models.IntegerField(+ null=True, blank=True, default=None+ )+ # define the cut-off date for automatic completion of fully paid checkouts+ automatic_completion_cut_off_date = models.DateTimeField(null=True, blank=True)+# time in hours after which the draft order line price will be refresheddraft_order_line_price_freeze_period = models.PositiveIntegerField(default=24, null=True, blank=Truediff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.pyindex 2776bf00b2..448f35a0ac 100644--- a/saleor/checkout/actions.py+++ b/saleor/checkout/actions.py@@ -276,8 +276,6 @@ def _transaction_amounts_for_checkout_updated(user: Optional["User"],app: Optional["App"],):- from .tasks import automatic_checkout_completion_task-checkout = checkout_info.checkoutprevious_charge_status_is_fully_paid = previous_charge_status in [@@ -321,14 +319,3 @@ 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- (not previous_authorize_status_is_full and current_authorize_status_is_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/migrations/0083_checkout_last_automatic_completion_attempt.py b/saleor/checkout/migrations/0083_checkout_last_automatic_completion_attempt.pynew file mode 100644index 0000000000..42a166fd9e--- /dev/null+++ b/saleor/checkout/migrations/0083_checkout_last_automatic_completion_attempt.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.8 on 2025-11-17 09:05++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("checkout", "0082_merge_20251107_1235"),+ ]++ operations = [+ migrations.AddField(+ model_name="checkout",+ name="last_automatic_completion_attempt",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/saleor/checkout/migrations/0084_checkout_automaticcompletionattempt_idx.py b/saleor/checkout/migrations/0084_checkout_automaticcompletionattempt_idx.pynew file mode 100644index 0000000000..e0deaed657--- /dev/null+++ b/saleor/checkout/migrations/0084_checkout_automaticcompletionattempt_idx.py@@ -0,0 +1,29 @@+# Generated by Django 5.2.8 on 2025-11-18 12:34+++from django.contrib.postgres.indexes import BTreeIndex+from django.contrib.postgres.operations import AddIndexConcurrently+from django.db import migrations+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("account", "0095_repopulate_user_number_of_orders"),+ ("channel", "0026_channel_automatic_completion_cut_off_date"),+ ("checkout", "0083_checkout_last_automatic_completion_attempt"),+ ("giftcard", "0022_merge_20250527_1210"),+ ("shipping", "0037_merge_20250630_1332"),+ ("warehouse", "0035_alter_warehouse_metadata_and_more"),+ ]++ operations = [+ AddIndexConcurrently(+ model_name="checkout",+ index=BTreeIndex(+ fields=["last_automatic_completion_attempt"],+ name="automaticcompletionattempt_idx",+ ),+ ),+ ]diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex 5fad24d284..d8e6ad788a 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Optionalfrom uuid import uuid4from django.conf import settings+from django.contrib.postgres.indexes import BTreeIndexfrom django.core.validators import MinValueValidatorfrom django.db import modelsfrom django.utils import timezone@@ -44,6 +45,9 @@ class Checkout(models.Model):last_transaction_modified_at = models.DateTimeField(null=True, blank=True)automatically_refundable = models.BooleanField(default=False)+ # Tracks the last time automatic checkout completion was attempted+ last_automatic_completion_attempt = models.DateTimeField(null=True, blank=True)+user = models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,@@ -235,6 +239,12 @@ class Checkout(models.Model):(CheckoutPermissions.HANDLE_TAXES.codename, "Handle taxes"),(CheckoutPermissions.MANAGE_TAXES.codename, "Manage taxes"),)+ indexes = [+ BTreeIndex(+ fields=["last_automatic_completion_attempt"],+ name="automaticcompletionattempt_idx",+ )+ ]def __iter__(self):return iter(self.lines.all())diff --git a/saleor/checkout/tasks.py b/saleor/checkout/tasks.pyindex 9aaa4171dd..8066443ed8 100644--- a/saleor/checkout/tasks.py+++ b/saleor/checkout/tasks.py@@ -1,3 +1,4 @@+import datetimeimport loggingfrom decimal import Decimal@@ -5,16 +6,20 @@ import graphenefrom celery.utils.log import get_task_loggerfrom django.conf import settingsfrom django.core.exceptions import ValidationError-from django.db.models import Exists, OuterRef, Q, QuerySet, Subquery-from django.db.utils import DatabaseError, IntegrityError+from django.db import transaction+from django.db.models import Exists, F, OuterRef, Q, QuerySet, Subqueryfrom django.utils import timezonefrom ..account.models import Userfrom ..app.models import Appfrom ..celeryconf import app+from ..channel.models import Channel+from ..checkout import CheckoutAuthorizeStatusfrom ..core.db.connection import allow_writer+from ..core.utils import get_domainfrom ..payment.models import TransactionItemfrom ..plugins.manager import get_plugins_manager+from ..webhook.transport.utils import get_sqs_message_group_idfrom .complete_checkout import complete_checkoutfrom .fetch import fetch_checkout_info, fetch_checkout_linesfrom .models import Checkout, CheckoutLine@@ -22,6 +27,10 @@ from .utils import delete_checkoutstask_logger: logging.Logger = get_task_logger(__name__)+# Checkout complete might take even 3 seconds. The task is scheduled to run+# every 1 minute, so to avoid overlapping executions, the limit is set to 20.+AUTOMATIC_COMPLETION_BATCH_SIZE = 20+@app.task@allow_writer()@@ -123,6 +132,68 @@ def delete_expired_checkouts(return total_deleted, has_more+def trigger_automatic_checkout_completion_task():+ """Trigger automatic checkout completion for eligible checkouts.++ This task:+ - Finds checkouts that are fully authorized and ready for completion+ - Tracks the last completion attempt time to avoid repeated retries+ - Sorts by last attempt time to prioritize checkouts that haven't been tried recently+ - Includes a safety check to skip very old checkouts (older than 30 days)+ """+ now = timezone.now()+ # Don't retry checkouts older than defined threshold+ oldest_allowed_checkout = (+ now - settings.AUTOMATIC_CHECKOUT_COMPLETION_OLDEST_MODIFIED+ )++ with allow_writer():+ channels = Channel.objects.filter(+ automatically_complete_fully_paid_checkouts=True+ )+ if not channels:+ task_logger.info(+ "No channels configured for automatic checkout completion."+ )+ return++ lookup = Q()+ for channel in channels:+ # calculate threshold time for automatic completion for given channel+ delay_minutes = channel.automatic_completion_delay or 0+ threshold_time = now - datetime.timedelta(minutes=float(delay_minutes))+ kwargs = {+ "channel_id": channel.pk,+ "last_change__lt": threshold_time,+ }+ if cut_off_date := channel.automatic_completion_cut_off_date:+ kwargs["created_at__gte"] = cut_off_date+ lookup |= Q(**kwargs)++ checkouts = (+ Checkout.objects.filter(authorize_status=CheckoutAuthorizeStatus.FULL)+ .filter(last_change__gte=oldest_allowed_checkout)+ .filter(lookup)+ # Sort by last attempt time (nulls first - never attempted), then by last_change+ .order_by(+ F("last_automatic_completion_attempt").asc(nulls_first=True),+ "last_change",+ )+ )++ if not checkouts:+ task_logger.info("No checkouts found for automatic completion.")++ domain = get_domain()+ for checkout in checkouts[:AUTOMATIC_COMPLETION_BATCH_SIZE]:+ automatic_checkout_completion_task.apply_async(+ args=[checkout.pk],+ kwargs={},+ headers={"MessageGroupId": get_sqs_message_group_id(domain)},+ )++@app.task(queue=settings.AUTOMATIC_CHECKOUT_COMPLETION_QUEUE_NAME,bind=True,@@ -133,21 +204,23 @@ def delete_expired_checkouts(def automatic_checkout_completion_task(self,checkout_pk,- user_id,- app_id,+ user_id=None,+ app_id=None,):"""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+ with transaction.atomic():+ checkout = Checkout.objects.select_for_update().filter(pk=checkout_pk).first()+ if not checkout:+ return+ checkout.last_automatic_completion_attempt = timezone.now()+ checkout.save(update_fields=["last_automatic_completion_attempt"])- user = User.objects.filter(pk=user_id).first()- app = App.objects.filter(pk=app_id).first()+ user = User.objects.filter(pk=user_id).first() if user_id else None+ app = App.objects.filter(pk=app_id).first() if app_id else Nonemanager = get_plugins_manager(allow_replica=False)lines, unavailable_variant_pks = fetch_checkout_lines(checkout)@@ -198,25 +271,6 @@ def automatic_checkout_completion_task("error": str(error),},)- except (IntegrityError, DatabaseError) as error:- if checkout_not_exists := not Checkout.objects.filter(pk=checkout_pk).exists():- failed_error_msg = failed_error_msg + " The checkout no longer exists."-- task_logger.warning(- failed_error_msg,- checkout_id,- extra={- "checkout_id": checkout_id,- "error": str(error),- },- )- if not checkout_not_exists:- task_logger.info(- "Retrying automatic checkout completion for checkout: %s.",- checkout_id,- extra={"checkout_id": checkout_id},- )- raise self.retry() from errorelse:task_logger.info("Automatic checkout completion succeeded for checkout: %s.",diff --git a/saleor/checkout/tests/test_actions.py b/saleor/checkout/tests/test_actions.pyindex 1f1724bc3f..ff1d8e9e08 100644--- a/saleor/checkout/tests/test_actions.py+++ b/saleor/checkout/tests/test_actions.py@@ -16,7 +16,6 @@ from ...graphql.webhook.dataloaders.pregenerated_payloads_for_checkout_filter_shPregeneratedCheckoutFilterShippingMethodPayloadsByCheckoutTokenLoader,)from ...plugins.manager import get_plugins_manager-from ...tests import race_conditionfrom ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom .. import CheckoutAuthorizeStatus, CheckoutChargeStatusfrom ..actions import (@@ -67,48 +66,6 @@ def test_transaction_amounts_for_checkout_updated_fully_paid(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")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")-def test_transaction_amounts_for_checkout_fully_paid_automatic_checkout_complete(- mocked_fully_authorized,- 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_fully_authorized.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")@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")@@ -281,100 +238,6 @@ def test_transaction_amounts_for_checkout_updated_fully_authorized(mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())-@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")-def test_transaction_amounts_for_checkout_fully_authorized_automatic_checkout_complete(- mocked_fully_authorized,- 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- )- mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())---@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")-def test_transaction_amounts_automatic_checkout_complete_called_once(- mocked_fully_authorized,- 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 race_condition.RunAfter(- "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- )- mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())--@pytest.mark.parametrize("previous_modified_at",[None, datetime.datetime(2018, 5, 31, 12, 0, 0, tzinfo=datetime.UTC)],diff --git a/saleor/checkout/tests/test_tasks.py b/saleor/checkout/tests/test_tasks.pyindex 81c2001d35..5064920f39 100644--- a/saleor/checkout/tests/test_tasks.py+++ b/saleor/checkout/tests/test_tasks.py@@ -6,23 +6,20 @@ from uuid import UUIDimport grapheneimport pytest-from celery.exceptions import Retry as CeleryTaskRetryError-from django.db.utils import DatabaseError, IntegrityErrorfrom django.utils import timezone+from freezegun import freeze_time-from ...core.taxes import zero_money+from ...channel.models import Channelfrom ...order import OrderEventsfrom ...order.models import Order-from ...plugins.manager import get_plugins_managerfrom ...product.models import ProductChannelListing, ProductVariantChannelListing-from .. import calculations-from ..fetch import fetch_checkout_info, fetch_checkout_lines+from .. import CheckoutAuthorizeStatusfrom ..models import Checkout, CheckoutLine-from ..payment_utils import update_checkout_payment_statusesfrom ..tasks import (automatic_checkout_completion_task,delete_expired_checkouts,task_logger,+ trigger_automatic_checkout_completion_task,)@@ -598,7 +595,7 @@ def test_aborts_deleting_checkouts_when_invocation_count_exhausted(mocked_task.assert_not_called()-def test_automatic_checkout_completion_task_transaction_flow(+def test_automatic_checkout_completion_transaction_flow(checkout_with_prices,transaction_item_generator,app,@@ -619,7 +616,7 @@ def test_automatic_checkout_completion_task_transaction_flow(# whenwith django_capture_on_commit_callbacks(execute=True):- automatic_checkout_completion_task(checkout_pk, None, app.id)+ automatic_checkout_completion_task(checkout.pk)# thenassert not Checkout.objects.filter(pk=checkout_pk).exists()@@ -644,7 +641,7 @@ def test_automatic_checkout_completion_task_transaction_flow(assert caplog.records[1].levelno == logging.INFO-def test_automatic_checkout_completion_task_payment_flow(+def test_automatic_checkout_completion_payment_flow(checkout_ready_to_complete,payment_dummy,app,@@ -664,7 +661,7 @@ def test_automatic_checkout_completion_task_payment_flow(# whenwith django_capture_on_commit_callbacks(execute=True):- automatic_checkout_completion_task(checkout_pk, None, app.id)+ automatic_checkout_completion_task(checkout.pk)# thenassert not Checkout.objects.filter(pk=checkout_pk).exists()@@ -689,9 +686,8 @@ def test_automatic_checkout_completion_task_payment_flow(assert caplog.records[1].levelno == logging.INFO-def test_automatic_checkout_completion_task_missing_checkout(checkout, caplog):+def test_automatic_checkout_completion_missing_checkout(checkout, caplog):# given- checkout_pk = checkout.pkcheckout.delete()# allow catching the log in caplog@@ -699,13 +695,13 @@ def test_automatic_checkout_completion_task_missing_checkout(checkout, caplog):parent_logger.propagate = True# when- automatic_checkout_completion_task(checkout_pk, None, None)+ automatic_checkout_completion_task(checkout.pk)# thenassert not caplog.records-def test_automatic_checkout_completion_task_unavailable_variant(+def test_automatic_checkout_completion_unavailable_variant(checkout_with_prices,transaction_item_generator,app,@@ -732,7 +728,7 @@ def test_automatic_checkout_completion_task_unavailable_variant(# whenwith django_capture_on_commit_callbacks(execute=True):- automatic_checkout_completion_task(checkout_pk, None, app.id)+ automatic_checkout_completion_task(checkout.pk)# thenassert Checkout.objects.filter(pk=checkout_pk).exists()@@ -754,7 +750,7 @@ def test_automatic_checkout_completion_task_unavailable_variant((ProductChannelListing, "product__variants__id"),],)-def test_automatic_checkout_completion_task_line_without_listing(+def test_automatic_checkout_completion_line_without_listing(channel_listing_model,listing_filter_field,checkout_with_prices,@@ -786,7 +782,7 @@ def test_automatic_checkout_completion_task_line_without_listing(# whenwith django_capture_on_commit_callbacks(execute=True):- automatic_checkout_completion_task(checkout_pk, None, app.id)+ automatic_checkout_completion_task(checkout.pk)# thenassert Checkout.objects.filter(pk=checkout_pk).exists()@@ -801,7 +797,7 @@ def test_automatic_checkout_completion_task_line_without_listing(assert caplog.records[0].levelno == logging.INFO-def test_automatic_checkout_completion_task_error_raised(checkout, app, caplog):+def test_automatic_checkout_completion_error_raised(checkout, app, caplog):# givencheckout_pk = checkout.pkcheckout.billing_address = None@@ -812,7 +808,7 @@ def test_automatic_checkout_completion_task_error_raised(checkout, app, caplog):parent_logger.propagate = True# when- automatic_checkout_completion_task(checkout_pk, None, app.id)+ automatic_checkout_completion_task(checkout.pk)# thenassert Checkout.objects.filter(pk=checkout_pk).exists()@@ -832,147 +828,355 @@ def test_automatic_checkout_completion_task_error_raised(checkout, app, caplog):assert caplog.records[1].levelno == logging.WARNING- "error",- [IntegrityError, DatabaseError],-)[email protected]("saleor.checkout.tasks.complete_checkout")[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.retry")-def test_automatic_checkout_completion_task_checkout_error_task_retried(- mocked_retry,- mocked_complete_checkout,- error,- checkout_with_prices,- transaction_item_generator,- app,[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.apply_async")+def test_trigger_automatic_checkout_completion_task_no_channels(+ mocked_automatic_checkout_completion,caplog,- django_capture_on_commit_callbacks,+ checkouts_list,):# given- checkout = checkout_with_prices- checkout_pk = checkout.pk-- mocked_complete_checkout.side_effect = error()- mocked_retry.side_effect = CeleryTaskRetryError()+ Channel.objects.all().update(automatically_complete_fully_paid_checkouts=False)+ Checkout.objects.update(authorize_status=CheckoutAuthorizeStatus.FULL)# allow catching the log in caplogparent_logger = task_logger.parentparent_logger.propagate = True- manager = get_plugins_manager(allow_replica=False)- lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, manager)- total = calculations.calculate_checkout_total(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout.shipping_address,- )- transaction_item_generator(- checkout_id=checkout.pk, charged_value=total.gross.amount+ # when+ trigger_automatic_checkout_completion_task()++ # then+ assert not mocked_automatic_checkout_completion.called+ assert len(caplog.records) == 1+ assert (+ caplog.records[0].message+ == "No channels configured for automatic checkout completion.")- update_checkout_payment_statuses(- checkout, zero_money(checkout.currency), checkout_has_lines=True+ assert caplog.records[0].levelno == logging.INFO++[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.apply_async")+@freeze_time("2024-05-31 12:00:01")+def test_trigger_automatic_checkout_completion_task_no_eligible_checkouts(+ mocked_automatic_checkout_completion, channel_USD, caplog, checkouts_list+):+ # given+ channel_USD.automatically_complete_fully_paid_checkouts = True+ channel_USD.automatic_completion_delay = 5+ channel_USD.save(+ update_fields=[+ "automatically_complete_fully_paid_checkouts",+ "automatic_completion_delay",+ ])+ # allow catching the log in caplog+ parent_logger = task_logger.parent+ parent_logger.propagate = True+# when- with django_capture_on_commit_callbacks(execute=True):- try:- automatic_checkout_completion_task(checkout_pk, None, app.id)- except CeleryTaskRetryError:- pass+ trigger_automatic_checkout_completion_task()# then- # Checkout exists so task is retired- mocked_retry.assert_called_once()+ assert not mocked_automatic_checkout_completion.called+ assert len(caplog.records) == 1+ assert caplog.records[0].message == "No checkouts found for automatic completion."+ assert caplog.records[0].levelno == logging.INFO- checkout_id = graphene.Node.to_global_id("Checkout", checkout_pk)- assert len(caplog.records) == 3- assert caplog.records[0].message == (- f"Automatic checkout completion triggered for checkout: {checkout_id}."+[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.apply_async")+@freeze_time("2024-05-31 12:00:01")+def test_trigger_automatic_checkout_completion_task_with_eligible_checkouts(+ mocked_automatic_checkout_completion,+ checkout_with_prices,+ channel_USD,+):+ # given+ channel_USD.automatically_complete_fully_paid_checkouts = True+ channel_USD.automatic_completion_delay = 5+ channel_USD.save(+ update_fields=[+ "automatically_complete_fully_paid_checkouts",+ "automatic_completion_delay",+ ])- 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}."+ Checkout.objects.update(+ authorize_status=CheckoutAuthorizeStatus.FULL,+ last_change=timezone.now() - datetime.timedelta(minutes=7),)- assert caplog.records[1].checkout_id == checkout_id- assert caplog.records[1].levelno == logging.WARNING- assert caplog.records[2].message == (- f"Retrying automatic checkout completion for checkout: {checkout_id}."+ # when+ trigger_automatic_checkout_completion_task()++ # then+ assert mocked_automatic_checkout_completion.call_count == 1+ mocked_automatic_checkout_completion.assert_called_once_with(+ args=[checkout_with_prices.token],+ kwargs={},+ headers={"MessageGroupId": mock.ANY},)- assert caplog.records[2].checkout_id == checkout_id- assert caplog.records[2].levelno == logging.INFO- "error",- [IntegrityError, DatabaseError],-)[email protected]("saleor.checkout.tasks.complete_checkout")[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.retry")-def test_automatic_checkout_completion_task_checkout_deleted_in_meantime(- mocked_retry,- mocked_complete_checkout,- error,[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.apply_async")+@freeze_time("2024-05-31 12:00:01")+def test_trigger_automatic_checkout_completion_task_checkout_not_eligible_due_to_delay(+ mocked_automatic_checkout_completion,checkout_with_prices,- transaction_item_generator,- app,- caplog,- django_capture_on_commit_callbacks,+ channel_USD,):# given+ channel_USD.automatically_complete_fully_paid_checkouts = True+ channel_USD.automatic_completion_delay = 10+ channel_USD.save(+ update_fields=[+ "automatically_complete_fully_paid_checkouts",+ "automatic_completion_delay",+ ]+ )++ Checkout.objects.update(+ authorize_status=CheckoutAuthorizeStatus.FULL,+ last_change=timezone.now() - datetime.timedelta(minutes=5),+ channel=channel_USD,+ )++ # when+ trigger_automatic_checkout_completion_task()++ # then+ assert not mocked_automatic_checkout_completion.called++[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.apply_async")+@freeze_time("2024-05-31 12:00:01")+def test_trigger_automatic_checkout_completion_task_checkout_too_old(+ mocked_automatic_checkout_completion,+ checkout_with_prices,+ channel_USD,+ settings,+):+ # given+ channel_USD.automatically_complete_fully_paid_checkouts = True+ channel_USD.automatic_completion_delay = 5+ channel_USD.save(+ update_fields=[+ "automatically_complete_fully_paid_checkouts",+ "automatic_completion_delay",+ ]+ )+checkout = checkout_with_prices- checkout_pk = checkout.pk+ # Older than the threshold defined in settings+ Checkout.objects.filter(pk=checkout.pk).update(+ last_change=timezone.now()+ - (+ settings.AUTOMATIC_CHECKOUT_COMPLETION_OLDEST_MODIFIED+ + datetime.timedelta(days=1)+ ),+ authorize_status=CheckoutAuthorizeStatus.FULL,+ channel=channel_USD,+ )- def delete_checkout_and_raise_an_error(*args, **kwargs):- checkout.delete()- raise error()+ # when+ trigger_automatic_checkout_completion_task()- mocked_complete_checkout.side_effect = delete_checkout_and_raise_an_error- mocked_retry.side_effect = CeleryTaskRetryError()+ # then+ assert not mocked_automatic_checkout_completion.called- # allow catching the log in caplog- parent_logger = task_logger.parent- parent_logger.propagate = True- manager = get_plugins_manager(allow_replica=False)- lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, manager)- total = calculations.calculate_checkout_total(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout.shipping_address,[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.apply_async")+@freeze_time("2024-05-31 12:00:01")[email protected]("batch_size", [1, 2, 5])+def test_trigger_automatic_checkout_completion_task_respects_batch_size(+ mocked_automatic_checkout_completion, checkouts_list, channel_USD, batch_size+):+ # given++ channel_USD.automatically_complete_fully_paid_checkouts = True+ channel_USD.automatic_completion_delay = 5+ channel_USD.save(+ update_fields=[+ "automatically_complete_fully_paid_checkouts",+ "automatic_completion_delay",+ ])- transaction_item_generator(- checkout_id=checkout.pk, charged_value=total.gross.amount++ Checkout.objects.update(+ authorize_status=CheckoutAuthorizeStatus.FULL,+ channel=channel_USD,+ last_change=timezone.now() - datetime.timedelta(minutes=10),)- update_checkout_payment_statuses(- checkout, zero_money(checkout.currency), checkout_has_lines=True++ # when+ with mock.patch(+ "saleor.checkout.tasks.AUTOMATIC_COMPLETION_BATCH_SIZE", batch_size+ ):+ trigger_automatic_checkout_completion_task()++ # then+ # Should only process the specified batch of checkouts+ assert mocked_automatic_checkout_completion.call_count == batch_size++[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.apply_async")+@freeze_time("2024-05-31 12:00:01")+def test_trigger_automatic_checkout_completion_task_prioritizes_never_attempted(+ mocked_automatic_checkout_completion,+ checkouts_list,+ channel_USD,+):+ # given+ channel_USD.automatically_complete_fully_paid_checkouts = True+ channel_USD.automatic_completion_delay = 5+ channel_USD.save(+ update_fields=[+ "automatically_complete_fully_paid_checkouts",+ "automatic_completion_delay",+ ]+ )++ # Create checkouts with different last_automatic_completion_attempt times+ never_attempted = checkouts_list[0]+ attempted_recently = checkouts_list[1]++ never_attempted.authorize_status = CheckoutAuthorizeStatus.FULL+ never_attempted.last_change = timezone.now() - datetime.timedelta(minutes=10)+ never_attempted.last_automatic_completion_attempt = None+ never_attempted.channel = channel_USD++ attempted_recently.authorize_status = CheckoutAuthorizeStatus.FULL+ attempted_recently.last_change = timezone.now() - datetime.timedelta(minutes=10)+ attempted_recently.last_automatic_completion_attempt = (+ timezone.now() - datetime.timedelta(minutes=2)+ )+ attempted_recently.channel = channel_USD++ Checkout.objects.bulk_update(+ [never_attempted, attempted_recently],+ [+ "authorize_status",+ "last_change",+ "last_automatic_completion_attempt",+ "channel",+ ],)# when- with django_capture_on_commit_callbacks(execute=True):- automatic_checkout_completion_task(checkout_pk, None, app.id)+ trigger_automatic_checkout_completion_task()# then- # Checkout exists so task is retired- mocked_retry.assert_not_called()+ assert mocked_automatic_checkout_completion.call_count == 2+ # Never attempted should be processed first+ assert (+ mocked_automatic_checkout_completion.call_args_list[0][1]["args"][0]+ == never_attempted.pk+ )- 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}."+[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.apply_async")+@freeze_time("2024-05-31 12:00:01")+def test_trigger_automatic_checkout_completion_task_multiple_channels(+ mocked_automatic_checkout_completion,+ checkouts_list,+ channel_USD,+ channel_PLN,+):+ # given+ channel_USD.automatically_complete_fully_paid_checkouts = True+ channel_USD.automatic_completion_delay = 5++ channel_PLN.automatically_complete_fully_paid_checkouts = True+ channel_PLN.automatic_completion_delay = 10+ Channel.objects.bulk_update(+ [channel_USD, channel_PLN],+ ["automatically_complete_fully_paid_checkouts", "automatic_completion_delay"],)- 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}. "- "The checkout no longer exists."+ # Prepare checkouts for bulk update+ checkout_usd = checkouts_list[0]+ checkout_usd.channel = channel_USD+ checkout_usd.authorize_status = CheckoutAuthorizeStatus.FULL+ checkout_usd.last_change = timezone.now() - datetime.timedelta(minutes=10)++ checkout_pln = checkouts_list[1]+ checkout_pln.channel = channel_PLN+ checkout_pln.authorize_status = CheckoutAuthorizeStatus.FULL+ checkout_pln.last_change = timezone.now() - datetime.timedelta(minutes=15)++ checkout_pln_not_ready = checkouts_list[2]+ checkout_pln_not_ready.channel = channel_PLN+ checkout_pln_not_ready.authorize_status = CheckoutAuthorizeStatus.FULL++ Checkout.objects.bulk_update(+ [checkout_usd, checkout_pln, checkout_pln_not_ready],+ ["channel", "authorize_status", "last_change"],)- assert caplog.records[1].checkout_id == checkout_id- assert caplog.records[1].levelno == logging.WARNING++ # when+ trigger_automatic_checkout_completion_task()++ # then+ assert mocked_automatic_checkout_completion.call_count == 2+ called_checkouts = [+ call.kwargs["args"][0]+ for call in mocked_automatic_checkout_completion.call_args_list+ ]+ assert checkout_usd.pk in called_checkouts+ assert checkout_pln.pk in called_checkouts+ assert checkout_pln_not_ready.pk not in called_checkouts++[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.apply_async")+@freeze_time("2024-05-31 12:00:01")+def test_trigger_automatic_checkout_completion_task_with_cut_off_date(+ mocked_automatic_checkout_completion,+ checkouts_list,+ channel_USD,+):+ # given+ channel_USD.automatically_complete_fully_paid_checkouts = True+ channel_USD.automatic_completion_delay = 5+ channel_USD.automatic_completion_cut_off_date = timezone.now() - datetime.timedelta(+ days=10+ )+ channel_USD.save(+ update_fields=[+ "automatically_complete_fully_paid_checkouts",+ "automatic_completion_delay",+ "automatic_completion_cut_off_date",+ ]+ )++ eligible_checkout = checkouts_list[0]+ eligible_checkout.channel = channel_USD+ eligible_checkout.authorize_status = CheckoutAuthorizeStatus.FULL+ eligible_checkout.last_change = timezone.now() - datetime.timedelta(minutes=15)+ eligible_checkout.created_at = timezone.now() - datetime.timedelta(days=5)++ ineligible_checkout_due_to_cut_off = checkouts_list[1]+ ineligible_checkout_due_to_cut_off.channel = channel_USD+ ineligible_checkout_due_to_cut_off.authorize_status = CheckoutAuthorizeStatus.FULL+ ineligible_checkout_due_to_cut_off.last_change = (+ timezone.now() - datetime.timedelta(minutes=15)+ )+ ineligible_checkout_due_to_cut_off.created_at = timezone.now() - datetime.timedelta(+ days=15+ )++ Checkout.objects.bulk_update(+ [eligible_checkout, ineligible_checkout_due_to_cut_off],+ ["channel", "authorize_status", "last_change", "created_at"],+ )++ # when+ trigger_automatic_checkout_completion_task()++ # then+ assert mocked_automatic_checkout_completion.call_count == 1+ called_checkouts = [+ call.kwargs["args"][0]+ for call in mocked_automatic_checkout_completion.call_args_list+ ]+ assert eligible_checkout.pk in called_checkouts+ assert ineligible_checkout_due_to_cut_off.pk not in called_checkoutsdiff --git a/saleor/core/schedules.py b/saleor/core/schedules.pyindex 2b1072bbe8..fc5e9676f2 100644--- a/saleor/core/schedules.py+++ b/saleor/core/schedules.py@@ -3,6 +3,7 @@ from typing import NamedTuple, castfrom celery.utils.time import maybe_timedelta, remainingfrom django.db.models import F, Q+from django.utils import timezonefrom ..schedulers.customschedule import CustomSchedule@@ -125,4 +126,113 @@ class promotion_webhook_schedule(CustomSchedule):return schedstate(is_due, self.next_run.total_seconds())+class TimeBaseSchedule(CustomSchedule):+ """Base schedule for time-based periodic tasks.++ Arguments:+ import_path (str): Import path of the schedule.+ initial_timedelta (float, ~datetime.timedelta):+ Initial time interval in seconds.+ nowfun (Callable): Function returning the current date and time+ (:class:`~datetime.datetime`).+ app (Celery): Celery app instance.++ """++ class Meta:+ abstract = True++ def __init__(self, import_path: str, initial_timedelta, nowfun=None, app=None):+ self.initial_timedelta: datetime.timedelta = cast(+ datetime.timedelta, maybe_timedelta(initial_timedelta)+ )+ self.next_run: datetime.timedelta = self.initial_timedelta+ super().__init__(+ schedule=self,+ nowfun=nowfun,+ app=app,+ import_path=import_path,+ )++ def are_dirty(self) -> bool:+ raise NotImplementedError++ def remaining_estimate(self, last_run_at):+ """Estimate of next run time.++ Returns when the periodic task should run next as a timedelta.+ """+ return remaining(+ self.maybe_make_aware(last_run_at),+ self.next_run,+ self.maybe_make_aware(self.now()),+ )++ def is_due(self, last_run_at):+ """Return tuple of ``(is_due, next_time_to_run)``.++ Note:+ Next time to run is in seconds.++ """+ last_run_at = self.maybe_make_aware(last_run_at)+ rem_delta = self.remaining_estimate(last_run_at)+ remaining_s = max(rem_delta.total_seconds(), 0)+ if remaining_s == 0:+ remaining_s = self.initial_timedelta.total_seconds()++ are_marked_as_dirty = self.are_dirty()+ return schedstate(is_due=are_marked_as_dirty, next=remaining_s)+++class checkout_automatic_completion_schedule(TimeBaseSchedule):+ def __init__(self, initial_timedelta=60, nowfun=None, app=None):+ # initial_timedelta defaults to 60 seconds, as referencing settings.py variables+ # would require rebuilding the schedule. settings depends on this class instance,+ # leading to a circular import if accessed directly.+ import_path = (+ "saleor.core.schedules.initiated_checkout_automatic_completion_schedule"+ )+ super().__init__(import_path, initial_timedelta, nowfun, app)++ def are_dirty(self) -> bool:+ from django.conf import settings++ from ..channel.models import Channel+ from ..checkout import CheckoutAuthorizeStatus+ from ..checkout.models import Checkout++ channels = Channel.objects.filter(+ automatically_complete_fully_paid_checkouts=True+ )+ now = timezone.now()+ oldest_allowed_checkout = (+ now - settings.AUTOMATIC_CHECKOUT_COMPLETION_OLDEST_MODIFIED+ )+ for channel in channels:+ # calculate threshold time for automatic completion for given channel+ delay_minutes = channel.automatic_completion_delay or 0+ threshold_time = now - datetime.timedelta(minutes=float(delay_minutes))+ filter_kwargs = {+ "authorize_status": CheckoutAuthorizeStatus.FULL,+ "last_change__gte": oldest_allowed_checkout,+ "channel_id": channel.pk,+ "last_change__lt": threshold_time,+ }+ if cut_off_date := channel.automatic_completion_cut_off_date:+ filter_kwargs["created_at__gte"] = cut_off_date+ if (+ Checkout.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(+ **filter_kwargs,+ )+ .exists()+ ):+ return True+ return False++initiated_promotion_webhook_schedule = promotion_webhook_schedule()+initiated_checkout_automatic_completion_schedule = (+ checkout_automatic_completion_schedule()+)diff --git a/saleor/core/tests/test_schedules.py b/saleor/core/tests/test_schedules.pyindex 2babca0db7..bee62c0b9e 100644--- a/saleor/core/tests/test_schedules.py+++ b/saleor/core/tests/test_schedules.py@@ -5,8 +5,13 @@ from django.utils import timezonefrom django.utils.module_loading import import_stringfrom freezegun import freeze_time+from ...checkout import CheckoutAuthorizeStatus+from ...checkout.models import Checkoutfrom ...discount.models import Promotion-from ..schedules import promotion_webhook_schedule+from ..schedules import (+ checkout_automatic_completion_schedule,+ promotion_webhook_schedule,+)@freeze_time("2020-10-10 12:00:00")@@ -226,3 +231,138 @@ def test_promotion_webhook_schedule_import_path():# thenassert isinstance(scheduler_instance, BaseSchedule)+++@freeze_time("2020-10-10 12:00:00")+def test_automatic_completion_update_schedule_remaining_estimate_initial_state():+ # given+ schedule = checkout_automatic_completion_schedule()++ # when+ remaining = schedule.remaining_estimate(last_run_at=timezone.now())++ # then+ assert remaining == schedule.initial_timedelta+++@freeze_time("2020-10-10 12:00:00")+def test_automatic_completion_schedule_remaining_estimate():+ # given+ schedule = checkout_automatic_completion_schedule()+ time_delta = datetime.timedelta(seconds=30)++ # when+ remaining = schedule.remaining_estimate(last_run_at=timezone.now() - time_delta)++ # then+ assert remaining == schedule.initial_timedelta - time_delta+++def test_automatic_completion_schedule_are_dirty(checkout_with_prices, channel_USD):+ # given+ schedule = checkout_automatic_completion_schedule()+ channel_USD.automatically_complete_fully_paid_checkouts = True+ channel_USD.automatic_completion_delay = 5+ channel_USD.save(+ update_fields=[+ "automatically_complete_fully_paid_checkouts",+ "automatic_completion_delay",+ ]+ )+ Checkout.objects.update(+ authorize_status=CheckoutAuthorizeStatus.FULL,+ last_change=timezone.now() - datetime.timedelta(minutes=7),+ )++ # when+ is_due, next_run = schedule.is_due(timezone.now() - datetime.timedelta(minutes=1))++ # then+ assert is_due is True+ assert next_run == schedule.initial_timedelta.total_seconds()+++def test_automatic_completion_schedule_are_dirty_checkout_too_old(+ checkout_with_prices, channel_USD, settings+):+ # given+ schedule = checkout_automatic_completion_schedule()+ channel_USD.automatically_complete_fully_paid_checkouts = True+ channel_USD.automatic_completion_delay = 5+ channel_USD.save(+ update_fields=[+ "automatically_complete_fully_paid_checkouts",+ "automatic_completion_delay",+ ]+ )+ Checkout.objects.update(+ authorize_status=CheckoutAuthorizeStatus.FULL,+ last_change=timezone.now() - datetime.timedelta(days=60),+ )++ # when+ is_due, next_run = schedule.is_due(timezone.now() - datetime.timedelta(minutes=1))++ # then+ assert is_due is False+ assert next_run == schedule.initial_timedelta.total_seconds()+++def test_automatic_completion_schedule_are_dirty_checkout_not_in_cut_off_date(+ checkout_with_prices, channel_USD+):+ # given+ schedule = checkout_automatic_completion_schedule()+ channel_USD.automatically_complete_fully_paid_checkouts = True+ channel_USD.automatic_completion_delay = 5+ channel_USD.automatic_completion_cut_off_date = timezone.now() + datetime.timedelta(+ days=1+ )+ channel_USD.save(+ update_fields=[+ "automatically_complete_fully_paid_checkouts",+ "automatic_completion_delay",+ "automatic_completion_cut_off_date",+ ]+ )+ Checkout.objects.update(+ authorize_status=CheckoutAuthorizeStatus.FULL,+ last_change=timezone.now() - datetime.timedelta(minutes=7),+ )++ # when+ is_due, next_run = schedule.is_due(timezone.now() - datetime.timedelta(minutes=1))++ # then+ assert is_due is False+ assert next_run == schedule.initial_timedelta.total_seconds()+++def test_automatic_completion_schedule_are_dirty_checkout_in_cut_off_date(+ checkout_with_prices, channel_USD+):+ # given+ schedule = checkout_automatic_completion_schedule()+ channel_USD.automatically_complete_fully_paid_checkouts = True+ channel_USD.automatic_completion_delay = 5+ channel_USD.automatic_completion_cut_off_date = timezone.now() - datetime.timedelta(+ days=1+ )+ channel_USD.save(+ update_fields=[+ "automatically_complete_fully_paid_checkouts",+ "automatic_completion_delay",+ "automatic_completion_cut_off_date",+ ]+ )+ Checkout.objects.update(+ authorize_status=CheckoutAuthorizeStatus.FULL,+ last_change=timezone.now() - datetime.timedelta(minutes=7),+ )++ # when+ is_due, next_run = schedule.is_due(timezone.now() - datetime.timedelta(minutes=1))++ # then+ assert is_due is True+ assert next_run == schedule.initial_timedelta.total_seconds()diff --git a/saleor/graphql/channel/mutations/channel_create.py b/saleor/graphql/channel/mutations/channel_create.pyindex 9a7be869c7..abd63872fa 100644--- a/saleor/graphql/channel/mutations/channel_create.py+++ b/saleor/graphql/channel/mutations/channel_create.py@@ -1,4 +1,5 @@import graphene+from django.conf import settingsfrom django.utils.text import slugifyfrom ....channel import models@@ -12,6 +13,7 @@ from ...core.descriptions import (ADDED_IN_318,ADDED_IN_320,ADDED_IN_321,+ ADDED_IN_322,DEPRECATED_IN_3X_INPUT,PREVIEW_FEATURE,)@@ -55,6 +57,45 @@ class StockSettingsInput(BaseInputObjectType):doc_category = DOC_CATEGORY_PRODUCTS+class CheckoutAutoCompleteInput(BaseInputObjectType):+ enabled = 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."+ ),+ )+ delay = Minute(+ required=False,+ description=(+ "The time in minutes after which the fully paid checkout will be "+ "automatically completed. Default is "+ f"{settings.DEFAULT_AUTOMATIC_CHECKOUT_COMPLETION_DELAY}. "+ "Set to 0 for immediate completion. "+ "Should be less than the threshold for the oldest modified checkout "+ "eligible for automatic completion."+ ),+ )+ cut_off_date = DateTime(+ required=False,+ description=(+ "Specifies the earliest date on which fully paid checkouts can begin "+ "to be automatically completed. Fully paid checkouts dated before this "+ "cut-off will not be automatically completed. Must be less than the "+ "threshold of the oldest modified checkout eligible for automatic "+ "completion. Default is current date time."+ ),+ )++ class Meta:+ doc_category = DOC_CATEGORY_CHECKOUT++class CheckoutSettingsInput(BaseInputObjectType):use_legacy_error_flow = graphene.Boolean(description=(@@ -75,11 +116,18 @@ class CheckoutSettingsInput(BaseInputObjectType):"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 "+ "checkout `authorize_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+ + DEPRECATED_IN_3X_INPUT+ + " Use `automatic_completion` instead.")- + ADDED_IN_320,+ )+ automatic_completion = CheckoutAutoCompleteInput(+ description="Settings for automatic completion of fully paid checkouts."+ + ADDED_IN_322,+ required=False,)class Meta:diff --git a/saleor/graphql/channel/mutations/channel_update.py b/saleor/graphql/channel/mutations/channel_update.pyindex 7b1bb009a4..26bc43405d 100644--- a/saleor/graphql/channel/mutations/channel_update.py+++ b/saleor/graphql/channel/mutations/channel_update.py@@ -131,7 +131,7 @@ class ChannelUpdate(DeprecatedModelMutation):clean_input_order_settings(order_settings, cleaned_input, instance)if checkout_settings := cleaned_input.get("checkout_settings"):- clean_input_checkout_settings(checkout_settings, cleaned_input)+ clean_input_checkout_settings(checkout_settings, cleaned_input, instance)if payment_settings := cleaned_input.get("payment_settings"):clean_input_payment_settings(payment_settings, cleaned_input)diff --git a/saleor/graphql/channel/mutations/utils.py b/saleor/graphql/channel/mutations/utils.pyindex 2560d8daa0..f8082bb1d8 100644--- a/saleor/graphql/channel/mutations/utils.py+++ b/saleor/graphql/channel/mutations/utils.py@@ -1,6 +1,8 @@import datetime+from django.conf import settingsfrom django.core.exceptions import ValidationError+from django.utils import timezonefrom ....channel.models import Channelfrom ...core.enums import ChannelErrorCode@@ -107,14 +109,147 @@ def clean_input_order_settings()-def clean_input_checkout_settings(checkout_settings: dict, cleaned_input: dict):- 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_checkout_settings(+ checkout_settings: dict, cleaned_input: dict, instance: Channel | None = None+):+ clean_automatic_completion(checkout_settings, cleaned_input)++ # Handle legacy fields+ if "use_legacy_error_flow" in checkout_settings:+ cleaned_input["use_legacy_error_flow_for_checkout"] = checkout_settings[+ "use_legacy_error_flow"+ ]+++def clean_automatic_completion(checkout_settings: dict, cleaned_input: dict):+ # Validate that both old and new fields aren't provided together+ if (+ "automatically_complete_fully_paid_checkouts" in checkout_settings+ and "automatic_completion" in checkout_settings+ ):+ raise ValidationError(+ {+ "automatically_complete_fully_paid_checkouts": ValidationError(+ "Cannot provide both 'automaticallyCompleteFullyPaidCheckouts' "+ "and 'automaticCompletion'. Use 'automaticCompletion' instead.",+ code=ChannelErrorCode.INVALID.value,+ )+ }+ )++ # Handle the automatic_completion nested input+ if automatic_completion := checkout_settings.get("automatic_completion"):+ enabled = automatic_completion.get("enabled")+ delay = automatic_completion.get("delay")+ cut_off_date = automatic_completion.get("cut_off_date")++ cleaned_input["automatically_complete_fully_paid_checkouts"] = enabled+ clean_automatic_completion_delay(delay, enabled, cleaned_input)+ clean_automatic_completion_cut_off_date(cut_off_date, enabled, cleaned_input)+ # Handle deprecated field for backward compatibility+ elif "automatically_complete_fully_paid_checkouts" in checkout_settings:+ automatically_complete = checkout_settings[+ "automatically_complete_fully_paid_checkouts"+ ]+ cleaned_input["automatically_complete_fully_paid_checkouts"] = (+ automatically_complete+ )+ cleaned_input["automatic_completion_delay"] = (+ settings.DEFAULT_AUTOMATIC_CHECKOUT_COMPLETION_DELAY+ if automatically_complete is True+ else None+ )+ cleaned_input["automatic_completion_cut_off_date"] = (+ timezone.now() if automatically_complete else None+ )+++def clean_automatic_completion_delay(+ delay: int, automatic_completion_enabled: bool, cleaned_input: dict+):+ if automatic_completion_enabled is False:+ if delay is not None:+ raise ValidationError(+ {+ "delay": ValidationError(+ "The delay cannot be set when automatic completion is disabled.",+ code=ChannelErrorCode.INVALID.value,+ )+ }+ )+ # When disabled, clear the delay+ cleaned_input["automatic_completion_delay"] = None+ else:+ oldest_allowed_checkout = (+ settings.AUTOMATIC_CHECKOUT_COMPLETION_OLDEST_MODIFIED.total_seconds() // 60+ )+ if delay is not None:+ if delay < 0:+ raise ValidationError(+ {+ "delay": ValidationError(+ "The automatic completion delay must be greater than or equal to 0.",+ code=ChannelErrorCode.INVALID.value,+ )+ }+ )+ if delay >= oldest_allowed_checkout:+ raise ValidationError(+ {+ "delay": ValidationError(+ f"The automatic completion delay must be less than "+ f"{oldest_allowed_checkout}, that is the threshold for the "+ "oldest modified checkout eligible for automatic "+ "completion.",+ code=ChannelErrorCode.INVALID.value,+ )+ }+ )+ cleaned_input["automatic_completion_delay"] = delay+ else:+ # If enabled and delay is missing, set default+ cleaned_input["automatic_completion_delay"] = (+ settings.DEFAULT_AUTOMATIC_CHECKOUT_COMPLETION_DELAY+ )+++def clean_automatic_completion_cut_off_date(+ cut_off_date: datetime.datetime,+ automatic_completion_enabled: bool,+ cleaned_input: dict,+):+ if automatic_completion_enabled is False:+ if cut_off_date is not None:+ raise ValidationError(+ {+ "cut_off_date": ValidationError(+ "The cut-off date cannot be set when automatic completion is disabled.",+ code=ChannelErrorCode.INVALID.value,+ )+ }+ )+ # When disabled, clear the delay+ cleaned_input["automatic_completion_cut_off_date"] = None+ else:+ if cut_off_date is not None:+ if (+ cut_off_date+ < timezone.now()+ - settings.AUTOMATIC_CHECKOUT_COMPLETION_OLDEST_MODIFIED+ ):+ raise ValidationError(+ {+ "cut_off_date": ValidationError(+ "The cut-off date must be more recent than "+ "the threshold for the oldest modified checkout "+ "eligible for automatic completion.",+ code=ChannelErrorCode.INVALID.value,+ )+ }+ )+ cleaned_input["automatic_completion_cut_off_date"] = cut_off_date+ else:+ cleaned_input["automatic_completion_cut_off_date"] = timezone.now()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.pyindex 7ae6c627f5..9d1963b43f 100644--- a/saleor/graphql/channel/tests/mutations/test_channel_create.py+++ b/saleor/graphql/channel/tests/mutations/test_channel_create.py@@ -4,6 +4,8 @@ from unittest import mockimport grapheneimport pytest+from django.conf import settings+from django.utils import timezonefrom django.utils.functional import SimpleLazyObjectfrom django.utils.text import slugifyfrom freezegun import freeze_time@@ -53,6 +55,8 @@ CHANNEL_CREATE_MUTATION = """checkoutSettings {useLegacyErrorFlowautomaticallyCompleteFullyPaidCheckouts+ automaticCompletionDelay+ automaticCompletionCutOffDate}paymentSettings {defaultTransactionFlowStrategy@@ -136,6 +140,7 @@ def test_channel_create_mutation_as_staff_user()+@freeze_time("2022-05-12 12:00:00")def test_channel_create_mutation_as_app(permission_manage_channels,app_api_client,@@ -196,6 +201,14 @@ def test_channel_create_mutation_as_app(channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]is True)+ assert (+ channel_data["checkoutSettings"]["automaticCompletionDelay"]+ == settings.DEFAULT_AUTOMATIC_CHECKOUT_COMPLETION_DELAY+ )+ assert (+ channel_data["checkoutSettings"]["automaticCompletionCutOffDate"]+ == timezone.now().isoformat()+ )def test_channel_create_mutation_as_customer(user_api_client):@@ -917,7 +930,8 @@ 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(+@freeze_time("2022-05-12 12:00:00")+def test_channel_create_set_automatic_checkout_completion(permission_manage_channels,staff_api_client,):@@ -932,7 +946,9 @@ def test_channel_create_set_automatically_complete_fully_paid_checkouts("slug": slug,"currencyCode": currency_code,"defaultCountry": default_country,- "checkoutSettings": {"automaticallyCompleteFullyPaidCheckouts": True},+ "checkoutSettings": {+ "automaticallyCompleteFullyPaidCheckouts": True,+ },}}@@ -953,7 +969,444 @@ def test_channel_create_set_automatically_complete_fully_paid_checkouts(channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]is True)+ assert (+ channel_data["checkoutSettings"]["automaticCompletionDelay"]+ == settings.DEFAULT_AUTOMATIC_CHECKOUT_COMPLETION_DELAY+ )+ assert (+ channel_data["checkoutSettings"]["automaticCompletionCutOffDate"]+ == timezone.now().isoformat()+ )+assert channel.automatically_complete_fully_paid_checkouts is True+ assert (+ channel.automatic_completion_delay+ == settings.DEFAULT_AUTOMATIC_CHECKOUT_COMPLETION_DELAY+ )+ assert channel.automatic_completion_cut_off_date == timezone.now()+++def test_channel_create_set_automatic_checkout_completion_false(+ 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": False,+ },+ }+ }++ # 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 = Channel.objects.get()+ assert channel.automatically_complete_fully_paid_checkouts is False+ assert channel.automatic_completion_delay is None+ assert channel.automatic_completion_cut_off_date is None+++def test_channel_create_with_automatic_completion_delay_value_below_0(+ 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": {+ "automaticCompletion": {+ "enabled": True,+ "delay": -1,+ }+ },+ }+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_CREATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["channelCreate"]["errors"][0]+ assert error["field"] == "delay"+ assert error["code"] == ChannelErrorCode.INVALID.name+++def test_channel_create_with_delay_exceeding_threshold(+ permission_manage_channels,+ staff_api_client,+ settings,+):+ # given+ name = "testName"+ slug = "test_slug"+ currency_code = "USD"+ default_country = "US"+ oldest_allowed_checkout = (+ settings.AUTOMATIC_CHECKOUT_COMPLETION_OLDEST_MODIFIED.total_seconds() // 60+ )+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ "checkoutSettings": {+ "automaticCompletion": {+ "enabled": True,+ "delay": oldest_allowed_checkout + 1, # Exceeds threshold+ },+ },+ }+ }++ # 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 data["errors"]+ assert data["errors"][0]["field"] == "delay"+ assert data["errors"][0]["code"] == ChannelErrorCode.INVALID.name+++@freeze_time("2022-05-12 12:00:00")+def test_channel_create_with_new_automatic_completion_enabled_with_default_delay(+ 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": {+ "automaticCompletion": {+ "enabled": 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+ )+ default_delay = settings.DEFAULT_AUTOMATIC_CHECKOUT_COMPLETION_DELAY+ assert channel_data["checkoutSettings"]["automaticCompletionDelay"] == default_delay+ assert channel.automatically_complete_fully_paid_checkouts is True+ assert channel.automatic_completion_delay == default_delay+ assert channel.automatic_completion_cut_off_date == timezone.now()+++def test_channel_create_with_new_automatic_completion_enabled_with_custom_delay_and_cut_off(+ permission_manage_channels,+ staff_api_client,+):+ # given+ name = "testName"+ slug = "test_slug"+ currency_code = "USD"+ default_country = "US"+ delay = 15+ cut_off = timezone.now() + datetime.timedelta(days=2)+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ "checkoutSettings": {+ "automaticCompletion": {+ "enabled": True,+ "delay": delay,+ "cutOffDate": cut_off.isoformat(),+ }+ },+ }+ }++ # 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_data["checkoutSettings"]["automaticCompletionDelay"] == delay+ assert (+ channel_data["checkoutSettings"]["automaticCompletionCutOffDate"]+ == cut_off.isoformat()+ )+ assert channel.automatically_complete_fully_paid_checkouts is True+ assert channel.automatic_completion_delay == delay+ assert channel.automatic_completion_cut_off_date == cut_off+++def test_channel_create_with_automatic_completion_disabled(+ 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": {+ "automaticCompletion": {+ "enabled": False,+ }+ },+ }+ }++ # 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 = Channel.objects.get()+ assert channel.automatically_complete_fully_paid_checkouts is False+ assert channel.automatic_completion_delay is None+ assert channel.automatic_completion_cut_off_date is None+++def test_channel_create_with_automatic_completion_disabled_and_delay(+ 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": {+ "automaticCompletion": {+ "enabled": False,+ "delay": 10,+ }+ },+ }+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_CREATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["channelCreate"]["errors"][0]+ assert error["field"] == "delay"+ assert error["code"] == ChannelErrorCode.INVALID.name+++def test_channel_create_with_automatic_completion_disabled_and_cutoff(+ permission_manage_channels,+ staff_api_client,+):+ # given+ name = "testName"+ slug = "test_slug"+ currency_code = "USD"+ default_country = "US"+ cut_off = datetime.datetime(2022, 5, 20, 0, 0, 0, tzinfo=datetime.UTC)+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ "checkoutSettings": {+ "automaticCompletion": {+ "enabled": False,+ "cutOffDate": cut_off.isoformat(),+ }+ },+ }+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_CREATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["channelCreate"]["errors"][0]+ assert error["field"] == "cutOffDate"+ assert error["code"] == ChannelErrorCode.INVALID.name+++def test_channel_create_with_both_old_and_new_automatic_completion_fields(+ 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,+ "automaticCompletion": {+ "enabled": True,+ "delay": 10,+ },+ },+ }+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_CREATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["channelCreate"]["errors"][0]+ assert error["field"] == "automaticallyCompleteFullyPaidCheckouts"+ assert error["code"] == ChannelErrorCode.INVALID.name+++@freeze_time("2022-05-12 12:00:00")+def test_channel_create_with_cutoff_later_than_threshold(+ permission_manage_channels,+ staff_api_client,+ settings,+):+ # given+ name = "testName"+ slug = "test_slug"+ currency_code = "USD"+ default_country = "US"+ cutoff_date = (+ timezone.now()+ - settings.AUTOMATIC_CHECKOUT_COMPLETION_OLDEST_MODIFIED+ - datetime.timedelta(days=10)+ )+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ "checkoutSettings": {+ "automaticCompletion": {+ "enabled": True,+ "cutOffDate": cutoff_date.isoformat(),+ },+ },+ }+ }++ # 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 data["errors"]+ assert data["errors"][0]["field"] == "cutOffDate"+ assert data["errors"][0]["code"] == ChannelErrorCode.INVALID.name@pytest.mark.parametrize("allow_unpaid", [True, False])diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.pyindex e6bb0c67cb..52aae81a77 100644--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py@@ -4,6 +4,8 @@ from unittest.mock import call, patchimport grapheneimport pytest+from django.conf import settings+from django.utils import timezonefrom django.utils.functional import SimpleLazyObjectfrom django.utils.text import slugifyfrom freezegun import freeze_time@@ -1291,6 +1293,8 @@ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS = """checkoutSettings {useLegacyErrorFlowautomaticallyCompleteFullyPaidCheckouts+ automaticCompletionDelay+ automaticCompletionCutOffDate}}errors{@@ -1305,6 +1309,7 @@ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS = """"""+@freeze_time("2022-05-12 12:00:00")def test_channel_update_channel_settings(permission_manage_channels, staff_api_client, channel_USD):@@ -1342,12 +1347,472 @@ def test_channel_update_channel_settings(channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]== automatically_complete_fully_paid_checkouts)+ default_delay = 30+ assert channel_data["checkoutSettings"]["automaticCompletionDelay"] == default_delay+ assert (+ channel_data["checkoutSettings"]["automaticCompletionCutOffDate"]+ == timezone.now().isoformat()+ )+channel_USD.refresh_from_db()assert channel_USD.use_legacy_error_flow_for_checkout == use_legacy_error_flowassert (channel_USD.automatically_complete_fully_paid_checkouts== automatically_complete_fully_paid_checkouts)+ assert channel_USD.automatic_completion_delay == default_delay+ assert channel_USD.automatic_completion_cut_off_date == timezone.now()+++@freeze_time("2022-05-12 12:00:00")+def test_channel_update_set_automatic_checkout_completion(+ permission_manage_channels,+ staff_api_client,+ channel_USD,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": channel_id,+ "input": {+ "checkoutSettings": {+ "automaticallyCompleteFullyPaidCheckouts": True,+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelUpdate"]+ assert not data["errors"]+ channel_data = data["channel"]+ channel_USD.refresh_from_db()+ delay = settings.DEFAULT_AUTOMATIC_CHECKOUT_COMPLETION_DELAY+ assert (+ channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]+ is True+ )+ assert channel_data["checkoutSettings"]["automaticCompletionDelay"] == delay+ assert (+ channel_data["checkoutSettings"]["automaticCompletionCutOffDate"]+ == timezone.now().isoformat()+ )+ assert channel_USD.automatically_complete_fully_paid_checkouts is True+ assert channel_USD.automatic_completion_delay == delay+ assert channel_USD.automatic_completion_cut_off_date == timezone.now()+++def test_channel_update_set_automatic_checkout_completion_change_to_false(+ permission_manage_channels,+ staff_api_client,+ channel_USD,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ channel_USD.automatic_completion_delay = 10+ channel_USD.automatically_complete_fully_paid_checkouts = True+ channel_USD.save(+ update_fields=[+ "automatic_completion_delay",+ "automatically_complete_fully_paid_checkouts",+ ]+ )+ variables = {+ "id": channel_id,+ "input": {+ "checkoutSettings": {+ "automaticallyCompleteFullyPaidCheckouts": False,+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelUpdate"]+ assert not data["errors"]+ channel_data = data["channel"]+ channel_USD.refresh_from_db()+ assert channel_USD.automatically_complete_fully_paid_checkouts is False+ assert channel_USD.automatic_completion_delay is None+ assert channel_USD.automatic_completion_cut_off_date is None+ assert (+ channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]+ is False+ )+ assert channel_data["checkoutSettings"]["automaticCompletionDelay"] is None+ assert channel_data["checkoutSettings"]["automaticCompletionCutOffDate"] is None+++def test_channel_update_set_automatic_checkout_completion_false(+ permission_manage_channels,+ staff_api_client,+ channel_USD,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": channel_id,+ "input": {+ "checkoutSettings": {+ "automaticCompletion": {+ "enabled": False,+ },+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelUpdate"]+ assert not data["errors"]+ channel_data = data["channel"]+ channel_USD.refresh_from_db()+ assert channel_USD.automatically_complete_fully_paid_checkouts is False+ assert channel_USD.automatic_completion_delay is None+ assert channel_USD.automatic_completion_cut_off_date is None+ assert (+ channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]+ is False+ )+ assert channel_data["checkoutSettings"]["automaticCompletionDelay"] is None+ assert channel_data["checkoutSettings"]["automaticCompletionCutOffDate"] is None+++def test_channel_update_with_automatic_completion_delay_below_0(+ permission_manage_channels,+ staff_api_client,+ channel_USD,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": channel_id,+ "input": {+ "checkoutSettings": {+ "automaticCompletion": {+ "enabled": True,+ "delay": -1,+ }+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["channelUpdate"]["errors"][0]+ assert error["field"] == "delay"+ assert error["code"] == ChannelErrorCode.INVALID.name+++def test_channel_update_with_delay_exceeding_threshold(+ permission_manage_channels,+ staff_api_client,+ channel_USD,+ settings,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ oldest_allowed_checkout = (+ settings.AUTOMATIC_CHECKOUT_COMPLETION_OLDEST_MODIFIED.total_seconds() // 60+ )+ variables = {+ "id": channel_id,+ "input": {+ "checkoutSettings": {+ "automaticCompletion": {+ "enabled": True,+ "delay": oldest_allowed_checkout + 1, # Exceeds threshold+ },+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["channelUpdate"]["errors"]+ assert errors+ assert errors[0]["field"] == "delay"+ assert errors[0]["code"] == ChannelErrorCode.INVALID.name+++@freeze_time("2024-01-01 12:00:00")+def test_channel_update_with_new_automatic_completion_enabled_with_default_delay(+ permission_manage_channels,+ staff_api_client,+ channel_USD,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": channel_id,+ "input": {+ "checkoutSettings": {+ "automaticCompletion": {+ "enabled": True,+ }+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelUpdate"]+ assert not data["errors"]+ channel_data = data["channel"]+ channel_USD.refresh_from_db()+ assert (+ channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]+ is True+ )+ default_delay = settings.DEFAULT_AUTOMATIC_CHECKOUT_COMPLETION_DELAY+ assert channel_data["checkoutSettings"]["automaticCompletionDelay"] == default_delay+ assert channel_USD.automatically_complete_fully_paid_checkouts is True+ assert channel_USD.automatic_completion_delay == default_delay+ assert channel_USD.automatic_completion_cut_off_date == timezone.now()+++def test_channel_update_with_new_automatic_completion_enabled_with_custom_delay_and_cut_off(+ permission_manage_channels,+ staff_api_client,+ channel_USD,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ delay = 15+ cut_off = timezone.now() + datetime.timedelta(days=5)+ variables = {+ "id": channel_id,+ "input": {+ "checkoutSettings": {+ "automaticCompletion": {+ "enabled": True,+ "delay": delay,+ "cutOffDate": cut_off.isoformat(),+ }+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelUpdate"]+ assert not data["errors"]+ channel_data = data["channel"]+ channel_USD.refresh_from_db()+ assert (+ channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]+ is True+ )+ assert channel_data["checkoutSettings"]["automaticCompletionDelay"] == delay+ assert (+ channel_data["checkoutSettings"]["automaticCompletionCutOffDate"]+ == cut_off.isoformat()+ )+ assert channel_USD.automatically_complete_fully_paid_checkouts is True+ assert channel_USD.automatic_completion_delay == delay+ assert channel_USD.automatic_completion_cut_off_date == cut_off+++def test_channel_update_mutation_with_invalid_cutoff_date(+ permission_manage_channels,+ staff_api_client,+ channel_USD,+):+ # given+ invalid_cut_off_date = timezone.now() - datetime.timedelta(days=40)+ variables = {+ "id": graphene.Node.to_global_id("Channel", channel_USD.id),+ "input": {+ "checkoutSettings": {+ "automaticCompletion": {+ "enabled": True,+ "cutOffDate": invalid_cut_off_date.isoformat(),+ }+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelUpdate"]+ assert data["errors"]+ assert data["errors"][0]["field"] == "cutOffDate"+ assert data["errors"][0]["code"] == ChannelErrorCode.INVALID.name+++def test_channel_update_with_new_automatic_completion_disabled(+ permission_manage_channels,+ staff_api_client,+ channel_USD,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ # Set initial state+ channel_USD.automatically_complete_fully_paid_checkouts = True+ channel_USD.automatic_completion_delay = 10+ channel_USD.save(+ update_fields=[+ "automatically_complete_fully_paid_checkouts",+ "automatic_completion_delay",+ ]+ )++ variables = {+ "id": channel_id,+ "input": {+ "checkoutSettings": {+ "automaticCompletion": {+ "enabled": False,+ }+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelUpdate"]+ assert not data["errors"]+ channel_data = data["channel"]+ channel_USD.refresh_from_db()+ assert channel_USD.automatically_complete_fully_paid_checkouts is False+ assert channel_USD.automatic_completion_delay is None+ assert channel_USD.automatic_completion_cut_off_date is None+ assert (+ channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]+ is False+ )+ assert channel_data["checkoutSettings"]["automaticCompletionDelay"] is None+ assert channel_data["checkoutSettings"]["automaticCompletionCutOffDate"] is None+++def test_channel_update_with_new_automatic_completion_disabled_with_delay(+ permission_manage_channels,+ staff_api_client,+ channel_USD,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": channel_id,+ "input": {+ "checkoutSettings": {+ "automaticCompletion": {+ "enabled": False,+ "delay": 10,+ }+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["channelUpdate"]["errors"][0]+ assert error["field"] == "delay"+ assert error["code"] == ChannelErrorCode.INVALID.name+++def test_channel_update_with_both_old_and_new_automatic_completion_fields(+ permission_manage_channels,+ staff_api_client,+ channel_USD,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": channel_id,+ "input": {+ "checkoutSettings": {+ "automaticallyCompleteFullyPaidCheckouts": True,+ "automaticCompletion": {+ "enabled": True,+ "delay": 10,+ },+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["channelUpdate"]["errors"][0]+ assert error["field"] == "automaticallyCompleteFullyPaidCheckouts"+ assert error["code"] == ChannelErrorCode.INVALID.namedef test_channel_update_channel_settings_with_checkout_permission(diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.pyindex f81736b0d7..51a8658ca0 100644--- a/saleor/graphql/channel/types.py+++ b/saleor/graphql/channel/types.py@@ -21,6 +21,7 @@ from ..core.descriptions import (ADDED_IN_318,ADDED_IN_320,ADDED_IN_321,+ ADDED_IN_322,DEPRECATED_IN_3X_INPUT,PREVIEW_FEATURE,)@@ -91,6 +92,22 @@ class CheckoutSettings(ObjectType):)+ ADDED_IN_320,)+ automatic_completion_delay = Minute(+ required=False,+ description=(+ "The time in minutes to wait after a checkout is fully paid "+ "before automatically completing it."+ )+ + ADDED_IN_322,+ )+ automatic_completion_cut_off_date = DateTime(+ required=False,+ description=(+ "The date time defines the earliest checkout creation date on which "+ "fully paid checkouts can begin to be automatically completed. "+ )+ + ADDED_IN_322,+ )class Meta:description = "Represents the channel-specific checkout settings."@@ -510,6 +527,8 @@ class Channel(ModelObjectType):return CheckoutSettings(use_legacy_error_flow=root.use_legacy_error_flow_for_checkout,automatically_complete_fully_paid_checkouts=complete_paid_checkouts,+ automatic_completion_delay=root.automatic_completion_delay,+ automatic_completion_cut_off_date=root.automatic_completion_cut_off_date,)@staticmethoddiff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.pyindex 0b5a718cb8..0c17b898ec 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py@@ -9,7 +9,6 @@ from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatusfrom .....checkout.calculations import fetch_checkout_datafrom .....checkout.complete_checkout import create_order_from_checkoutfrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from .....checkout.models import Checkoutfrom .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderEvents, OrderStatusfrom .....order.models import Orderfrom .....order.utils import update_order_authorize_data, update_order_charge_data@@ -1255,70 +1254,6 @@ def test_transaction_create_for_checkout_fully_paid(mocked_automatic_checkout_completion_task.assert_not_called()-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")-def test_transaction_create_for_checkout_fully_paid_automatic_completion(- mocked_checkout_fully_paid,- mocked_checkout_fully_authorized,- 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())- mocked_checkout_fully_authorized.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_authorized")@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")@@ -1377,71 +1312,6 @@ def test_transaction_create_for_checkout_fully_authorized(mocked_automatic_checkout_completion_task.assert_not_called()-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")-def test_transaction_create_for_checkout_fully_authorized_automatic_completion(- mocked_checkout_fully_paid,- mocked_checkout_fully_authorized,- 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_authorized.assert_called_once_with(checkout, webhooks=set())- 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(("amount_field_name", "amount_db_field"),[diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.pyindex c0d2840529..4bfdafbbef 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py@@ -12,11 +12,9 @@ from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatusfrom .....checkout.calculations import fetch_checkout_datafrom .....checkout.complete_checkout import create_order_from_checkoutfrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from .....checkout.models import Checkoutfrom .....order import (OrderAuthorizeStatus,OrderChargeStatus,- OrderEvents,OrderGrantedRefundStatus,OrderStatus,)@@ -1391,13 +1389,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")@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")def test_transaction_event_updates_checkout_full_paid_with_charged_amount(mocked_fully_authorized,mocked_fully_paid,- mocked_automatic_checkout_completion_task,transaction_item_generator,app_api_client,permission_manage_payments,@@ -1411,8 +1407,6 @@ def test_transaction_event_updates_checkout_full_paid_with_charged_amount(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@@ -1461,16 +1455,13 @@ def test_transaction_event_updates_checkout_full_paid_with_charged_amount(assert checkout.authorize_status == CheckoutAuthorizeStatus.FULLmocked_fully_paid.assert_called_once_with(checkout, webhooks=set())mocked_fully_authorized.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")@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")def test_transaction_event_updates_checkout_full_paid_with_pending_charge_amount(mocked_fully_paid,mocked_fully_authorized,- mocked_automatic_checkout_completion_task,transaction_item_generator,app_api_client,permission_manage_payments,@@ -1531,172 +1522,13 @@ def test_transaction_event_updates_checkout_full_paid_with_pending_charge_amountassert checkout.authorize_status == CheckoutAuthorizeStatus.FULLmocked_fully_paid.assert_called_once_with(checkout, webhooks=set())mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())- mocked_automatic_checkout_completion_task.assert_not_called()-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")-def test_transaction_event_updates_checkout_full_paid_automatic_completion(- mocked_fully_paid,- checkout_fully_authorized,- 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()-- checkout_fully_authorized.assert_called_once_with(checkout, webhooks=set())- mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())---@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")-def test_transaction_event_updates_checkout_full_paid_pending_charge_automatic_complete(- mocked_fully_paid,- checkout_fully_authorized,- 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())- checkout_fully_authorized.assert_called_once_with(checkout, webhooks=set())---@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")def test_transaction_event_updates_checkout_fully_authorized(mocked_fully_authorized,mocked_fully_paid,- mocked_automatic_checkout_completion_task,transaction_item_generator,app_api_client,permission_manage_payments,@@ -1710,8 +1542,6 @@ def test_transaction_event_updates_checkout_fully_authorized(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@@ -1761,162 +1591,6 @@ def test_transaction_event_updates_checkout_fully_authorized(mocked_fully_paid.assert_not_called()mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())- mocked_automatic_checkout_completion_task.assert_not_called()---@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")-def test_transaction_event_updates_checkout_fully_authorized_automatic_complete(- mocked_fully_paid,- mocked_fully_authorized,- 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()- mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())---@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")-def test_transaction_event_updates_checkout_fully_authorized_pending_automatic_complete(- mocked_fully_paid,- mocked_fully_authorized,- 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()- mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())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.pyindex 65d99577b2..c392ca5ba6 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py@@ -14,9 +14,8 @@ from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatusfrom .....checkout.calculations import fetch_checkout_datafrom .....checkout.complete_checkout import create_order_from_checkoutfrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from .....checkout.models import Checkoutfrom .....core.prices import quantize_price-from .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderEvents, OrderStatus+from .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderStatusfrom .....order.models import Orderfrom .....payment import TransactionEventType, TransactionItemIdempotencyUniqueErrorfrom .....payment.interface import (@@ -1829,7 +1828,6 @@ 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.checkout_fully_authorized")@mock.patch("saleor.plugins.manager.PluginsManager.transaction_initialize_session")@@ -1837,7 +1835,6 @@ def test_checkout_fully_paid(mocked_initialize,mocked_fully_authorized,mocked_fully_paid,- mocked_automatic_checkout_completion_task,result,user_api_client,checkout_with_prices,@@ -1854,8 +1851,6 @@ def test_checkout_fully_paid(webhook_app.identifier = expected_app_identifierwebhook_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)@@ -1881,7 +1876,6 @@ def test_checkout_fully_paid(checkout.refresh_from_db()mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())- mocked_automatic_checkout_completion_task.assert_not_called()assert checkout.charge_status == CheckoutChargeStatus.FULLassert checkout.authorize_status == CheckoutAuthorizeStatus.FULL@@ -1889,7 +1883,7 @@ def test_checkout_fully_paid(@mock.patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")@mock.patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")@mock.patch("saleor.plugins.manager.PluginsManager.transaction_initialize_session")-def test_checkout_fully_paid_automatic_completion(+def test_checkout_fully_paid_pending_charge(mocked_initialize,mocked_fully_paid,mocked_fully_authorized,@@ -1901,7 +1895,6 @@ def test_checkout_fully_paid_automatic_completion():# givencheckout = checkout_with_prices- checkout_token = checkout.tokenlines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)@@ -1909,72 +1902,6 @@ def test_checkout_fully_paid_automatic_completion(webhook_app.identifier = expected_app_identifierwebhook_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())- mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())--[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")[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,- mocked_fully_authorized,- 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)@@ -1997,14 +1924,11 @@ def test_checkout_fully_paid_pending_charge_automatic_completion(# thencontent = 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+ checkout.refresh_from_db()mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())+ assert checkout.charge_status == CheckoutChargeStatus.FULL+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL@pytest.mark.parametrize(@@ -2014,7 +1938,6 @@ def test_checkout_fully_paid_pending_charge_automatic_completion(TransactionEventType.AUTHORIZATION_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.checkout_fully_authorized")@mock.patch("saleor.plugins.manager.PluginsManager.transaction_initialize_session")@@ -2022,7 +1945,6 @@ def test_checkout_fully_authorized(mocked_initialize,mocked_fully_authorized,mocked_fully_paid,- mocked_automatic_checkout_completion_task,result,user_api_client,checkout_with_prices,@@ -2039,8 +1961,6 @@ def test_checkout_fully_authorized(webhook_app.identifier = expected_app_identifierwebhook_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)@@ -2066,7 +1986,6 @@ def test_checkout_fully_authorized(checkout.refresh_from_db()assert checkout.charge_status == CheckoutChargeStatus.NONEassert checkout.authorize_status == CheckoutAuthorizeStatus.FULL- mocked_automatic_checkout_completion_task.assert_not_called()mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())mocked_fully_paid.assert_not_called()@@ -2074,7 +1993,7 @@ def test_checkout_fully_authorized(@mock.patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")@mock.patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")@mock.patch("saleor.plugins.manager.PluginsManager.transaction_initialize_session")-def test_checkout_fully_authorized_automatic_completion(+def test_checkout_fully_authorized_pending_authorization(mocked_initialize,mocked_fully_paid,mocked_fully_authorized,@@ -2086,69 +2005,6 @@ def test_checkout_fully_authorized_automatic_completion():# givencheckout = 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()- mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())--[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")[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,- mocked_fully_authorized,- user_api_client,- checkout_with_prices,- webhook_app,- transaction_session_response,- plugins_manager,-):- # given- checkout = checkout_with_prices- checkout_token = checkout.tokenlines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)@@ -2182,14 +2038,11 @@ def test_checkout_fully_authorizaed_pending_authorization_automatic_completion(# thencontent = 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()+ checkout.refresh_from_db()+ assert checkout.charge_status == CheckoutChargeStatus.NONE+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULLmocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())+ mocked_fully_paid.assert_not_called()def test_user_missing_permission_for_customer_ip_address(diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.pyindex c4539dd785..1f1d54fdaa 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py@@ -13,9 +13,8 @@ from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatusfrom .....checkout.calculations import fetch_checkout_datafrom .....checkout.complete_checkout import create_order_from_checkoutfrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from .....checkout.models import Checkoutfrom .....core.prices import quantize_price-from .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderEvents, OrderStatus+from .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderStatusfrom .....order.models import Orderfrom .....payment import FAILED_TRANSACTION_EVENTS, TransactionEventTypefrom .....payment.interface import (@@ -1125,7 +1124,6 @@ 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.checkout_fully_authorized")@mock.patch("saleor.plugins.manager.PluginsManager.transaction_process_session")@@ -1133,7 +1131,6 @@ def test_checkout_fully_paid(mocked_process,mocked_fully_authorized,mocked_fully_paid,- mocked_automatic_checkout_completion_task,result,user_api_client,checkout_with_prices,@@ -1189,7 +1186,6 @@ def test_checkout_fully_paid(checkout.refresh_from_db()mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())- mocked_automatic_checkout_completion_task.assert_not_called()assert checkout.charge_status == CheckoutChargeStatus.FULLassert checkout.authorize_status == CheckoutAuthorizeStatus.FULL@@ -1197,7 +1193,7 @@ def test_checkout_fully_paid(@mock.patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")@mock.patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")@mock.patch("saleor.plugins.manager.PluginsManager.transaction_process_session")-def test_checkout_fully_paid_automatic_completion(+def test_checkout_fully_paid_pending(mocked_process,mocked_fully_authorized,mocked_fully_paid,@@ -1210,81 +1206,6 @@ def test_checkout_fully_paid_automatic_completion():# givencheckout = 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_authorized.assert_called_once_with(checkout, webhooks=set())- 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.checkout_fully_authorized")[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")-def test_checkout_fully_paid_pending_automatic_completion(- mocked_process,- mocked_fully_authorized,- 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.tokenlines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)@@ -1328,15 +1249,11 @@ def test_checkout_fully_paid_pending_automatic_completion(# thencontent = 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+ checkout.refresh_from_db()mocked_fully_paid.assert_called_once_with(checkout, webhooks=set())mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())+ assert checkout.charge_status == CheckoutChargeStatus.FULL+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL@pytest.mark.parametrize(@@ -1346,7 +1263,6 @@ def test_checkout_fully_paid_pending_automatic_completion(TransactionEventType.AUTHORIZATION_SUCCESS,],)[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.delay")@mock.patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")@mock.patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")@mock.patch("saleor.plugins.manager.PluginsManager.transaction_process_session")@@ -1354,7 +1270,6 @@ def test_checkout_fully_authorized(mocked_process,mocked_fully_paid,mocked_fully_authorized,- mocked_automatic_checkout_completion_task,result,user_api_client,checkout_with_prices,@@ -1409,7 +1324,6 @@ def test_checkout_fully_authorized(checkout.refresh_from_db()mocked_fully_paid.assert_not_called()- mocked_automatic_checkout_completion_task.assert_not_called()mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())assert checkout.charge_status == CheckoutChargeStatus.NONEassert checkout.authorize_status == CheckoutAuthorizeStatus.FULL@@ -1418,7 +1332,7 @@ def test_checkout_fully_authorized(@mock.patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")@mock.patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")@mock.patch("saleor.plugins.manager.PluginsManager.transaction_process_session")-def test_checkout_fully_authorized_automatic_completion(+def test_checkout_fully_authorized_pending(mocked_process,mocked_fully_authorized,mocked_fully_paid,@@ -1431,81 +1345,6 @@ def test_checkout_fully_authorized_automatic_completion():# givencheckout = 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()- mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())--[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")-def test_checkout_fully_authorized_pending_automatic_completion(- mocked_process,- mocked_fully_authorized,- 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.tokenlines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)@@ -1549,15 +1388,11 @@ def test_checkout_fully_authorized_pending_automatic_completion(# thencontent = 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+ checkout.refresh_from_db()mocked_fully_paid.assert_not_called()mocked_fully_authorized.assert_called_once_with(checkout, webhooks=set())+ assert checkout.charge_status == CheckoutChargeStatus.NONE+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULLdef test_transaction_process_doesnt_accept_old_id(diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.pyindex 2b12c324d0..dfb04a7519 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py@@ -9,7 +9,6 @@ from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatusfrom .....checkout.calculations import fetch_checkout_datafrom .....checkout.complete_checkout import create_order_from_checkoutfrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from .....checkout.models import Checkoutfrom .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderEvents, OrderStatusfrom .....order.models import Orderfrom .....payment import PaymentMethodType, TransactionEventType@@ -2691,13 +2690,11 @@ def test_transaction_update_for_checkout_updates_payment_statuses(assert checkout_with_prices.authorize_status == CheckoutAuthorizeStatus.PARTIAL-@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")def test_transaction_update_for_checkout_fully_paid(mocked_checkout_fully_authorized,mocked_checkout_fully_paid,- mocked_automatic_checkout_completion_task,checkout_with_prices,permission_manage_payments,app_api_client,@@ -2720,8 +2717,6 @@ 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": {@@ -2744,69 +2739,6 @@ def test_transaction_update_for_checkout_fully_paid(mocked_checkout_fully_paid.assert_called_once_with(checkout, webhooks=set())mocked_checkout_fully_authorized.assert_called_once_with(checkout, webhooks=set())- mocked_automatic_checkout_completion_task.assert_not_called()---@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")-def test_transaction_update_for_checkout_fully_paid_automatic_completion(- mocked_checkout_fully_authorized,- 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())- mocked_checkout_fully_authorized.assert_called_once_with(checkout, webhooks=set())@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")@@ -2838,8 +2770,6 @@ def test_transaction_update_for_checkout_fully_authorized(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": {@@ -2865,66 +2795,6 @@ def test_transaction_update_for_checkout_fully_authorized(mocked_automatic_checkout_completion_task.assert_not_called()-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")-def test_transaction_update_for_checkout_fully_authorized_automatic_completion(- mocked_checkout_fully_authorized,- 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()- mocked_checkout_fully_authorized.assert_called_once_with(checkout, webhooks=set())--def test_transaction_update_accepts_old_id_for_old_transaction(transaction_item_generator, permission_manage_payments, app_api_client):diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex aa0321e324..662c972493 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -5446,6 +5446,20 @@ type CheckoutSettings {Added in Saleor 3.20."""automaticallyCompleteFullyPaidCheckouts: Boolean!++ """+ The time in minutes to wait after a checkout is fully paid before automatically completing it.++ Added in Saleor 3.22.+ """+ automaticCompletionDelay: Minute++ """+ The date time defines the earliest checkout creation date on which fully paid checkouts can begin to be automatically completed.++ Added in Saleor 3.22.+ """+ automaticCompletionCutOffDate: DateTime}"""Represents the channel-specific payment settings."""@@ -28849,11 +28863,35 @@ input CheckoutSettingsInput @doc(category: "Checkout") {useLegacyErrorFlow: Boolean @deprecated"""- 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.+ 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 `authorize_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+ automaticallyCompleteFullyPaidCheckouts: Boolean @deprecated(reason: "Use `automatic_completion` instead.")++ """+ Settings for automatic completion of fully paid checkouts.++ Added in Saleor 3.22.+ """+ automaticCompletion: CheckoutAutoCompleteInput+}++input CheckoutAutoCompleteInput @doc(category: "Checkout") {+ """+ 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.+ """+ enabled: Boolean!++ """+ The time in minutes after which the fully paid checkout will be automatically completed. Default is 30. Set to 0 for immediate completion. Should be less than the threshold for the oldest modified checkout eligible for automatic completion.+ """+ delay: Minute++ """+ Specifies the earliest date on which fully paid checkouts can begin to be automatically completed. Fully paid checkouts dated before this cut-off will not be automatically completed. Must be less than the threshold of the oldest modified checkout eligible for automatic completion. Default is current date time.+ """+ cutOffDate: DateTime}input PaymentSettingsInput @doc(category: "Payments") {diff --git a/saleor/payment/tests/test_utils/test_create_transaction_event_for_transaction_session.py b/saleor/payment/tests/test_utils/test_create_transaction_event_for_transaction_session.pyindex cb1f43aee4..fc81ac3576 100644--- a/saleor/payment/tests/test_utils/test_create_transaction_event_for_transaction_session.py+++ b/saleor/payment/tests/test_utils/test_create_transaction_event_for_transaction_session.py@@ -6,8 +6,6 @@ from unittest.mock import patchimport pytestfrom freezegun import freeze_time-from ....checkout import CheckoutAuthorizeStatus-from ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....order import OrderAuthorizeStatusfrom ... import TransactionEventTypefrom ...models import TransactionEvent@@ -914,63 +912,6 @@ def test_create_transaction_event_with_invalid_message() in (record.message for record in caplog.records)-@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")-def test_create_transaction_event_from_session_when_authorized_triggers_checkout_completion(- mocked_checkout_fully_authorized,- mocked_checkout_fully_paid,- mocked_automatic_checkout_completion_task,- transaction_item_generator,- app,- checkout_with_prices,- plugins_manager,- django_capture_on_commit_callbacks,-):- # 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- with django_capture_on_commit_callbacks(execute=True):- create_transaction_event_for_transaction_session(- request_event, app, plugins_manager, response_data- )-- # then- checkout.refresh_from_db()- assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL- mocked_checkout_fully_paid.assert_not_called()- mocked_checkout_fully_authorized.assert_called_once_with(checkout, webhooks=set())- 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/tests/test_utils/test_utils.py b/saleor/payment/tests/test_utils/test_utils.pyindex b43cc28ceb..7d0d837d40 100644--- a/saleor/payment/tests/test_utils/test_utils.py+++ b/saleor/payment/tests/test_utils/test_utils.py@@ -928,63 +928,6 @@ def test_create_transaction_event_from_request_when_authorized_logs_warnning(assert len(mocked_logger.call_args) == 2-@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")-@patch("saleor.plugins.manager.PluginsManager.checkout_fully_authorized")-def test_create_transaction_event_from_request_when_paid_triggers_checkout_completion(- mocked_checkout_fully_paid,- mocked_checkout_fully_authorized,- mocked_automatic_checkout_completion_task,- transaction_item_generator,- app,- checkout_with_prices,- plugins_manager,- django_capture_on_commit_callbacks,-):- # 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- with django_capture_on_commit_callbacks(execute=True):- create_transaction_event_from_request_and_webhook_response(- request_event, app, response_data- )-- # then- checkout.refresh_from_db()- assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL- mocked_checkout_fully_paid.assert_called_once_with(checkout, webhooks=set())- mocked_checkout_fully_authorized.assert_called_once_with(checkout, webhooks=set())- mocked_automatic_checkout_completion_task.assert_called_once_with(- checkout.pk, None, app.id- )--@pytest.mark.parametrize(("first_event_amount", "second_event_amount"),[(12.02, 12.02), ("12.02", 12.02), (12.02, "12.02"), ("12.02", "12.02")],diff --git a/saleor/settings.py b/saleor/settings.pyindex ec944e4e31..70e1dcdd14 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -31,7 +31,10 @@ from .account.i18n_rules_override import i18n_rules_overridefrom .core.db.patch import patch_dbfrom .core.languages import LANGUAGES as CORE_LANGUAGESfrom .core.rlimit import validate_and_set_rlimit-from .core.schedules import initiated_promotion_webhook_schedule+from .core.schedules import (+ initiated_checkout_automatic_completion_schedule,+ initiated_promotion_webhook_schedule,+)from .graphql.executor import patch_executorfrom .graphql.promise import patch_promisefrom .patch_local import patch_local@@ -734,6 +737,12 @@ CELERY_BEAT_SCHEDULE = {"schedule": datetime.timedelta(seconds=BEAT_PRICE_RECALCULATION_SCHEDULE),"options": {"expires": BEAT_PRICE_RECALCULATION_SCHEDULE_EXPIRE_AFTER_SEC},},+ "checkout-automatic-completion": {+ # Scheduled task that runs every 60 seconds to check for checkout+ # readiness for automatic completion.+ "task": "saleor.checkout.tasks.trigger_automatic_checkout_completion_task",+ "schedule": initiated_checkout_automatic_completion_schedule,+ },}# The maximum wait time between each is_due() call on schedulers@@ -943,6 +952,13 @@ CHECKOUT_TTL_BEFORE_RELEASING_FUNDS = datetime.timedelta(TRANSACTION_BATCH_FOR_RELEASING_FUNDS = os.environ.get("TRANSACTION_BATCH_FOR_RELEASING_FUNDS", 60)+# Oldest checkout modification for automatic completion. Older checkouts will not be+# processed.+AUTOMATIC_CHECKOUT_COMPLETION_OLDEST_MODIFIED = datetime.timedelta(+ seconds=parse(+ os.environ.get("AUTOMATIC_CHECKOUT_COMPLETION_OLDEST_MODIFIED", "30 days")+ )+)# The maximum SearchVector expression count allowed per index SQL statement@@ -1051,6 +1067,11 @@ ORDER_RULES_LIMIT = os.environ.get("ORDER_RULES_LIMIT", 100)# The max number of gits assigned to promotion ruleGIFTS_LIMIT_PER_RULE = os.environ.get("GIFTS_LIMIT_PER_RULE", 500)+# Default automatic completion delay for checkout in minutes.+DEFAULT_AUTOMATIC_CHECKOUT_COMPLETION_DELAY = int(+ os.environ.get("AUTOMATIC_CHECKOUT_COMPLETION_DELAY", 30)+)+# Whether to enable the comparison of pre-save and post-save webhook payloads in# mutations, in order to limit sending webhooks where the payload has not changed as# a result of the mutation. Note: this works only for subscriptions webhooks; legacydiff --git a/saleor/tests/e2e/checkout/test_checkout_automatic_completion_authorize_flow.py b/saleor/tests/e2e/checkout/test_checkout_automatic_completion_authorize_flow.pydeleted file mode 100644index 1a03fb80f5..0000000000--- a/saleor/tests/e2e/checkout/test_checkout_automatic_completion_authorize_flow.py+++ /dev/null@@ -1,126 +0,0 @@-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,- email="[email protected]",- )- 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_typesdiff --git a/saleor/tests/e2e/checkout/test_checkout_automatic_completion_charge_flow.py b/saleor/tests/e2e/checkout/test_checkout_automatic_completion_charge_flow.pydeleted file mode 100644index cdf1e1bc5b..0000000000--- a/saleor/tests/e2e/checkout/test_checkout_automatic_completion_charge_flow.py+++ /dev/null@@ -1,141 +0,0 @@-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,- email="[email protected]",- )- 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_typesdiff --git a/saleor/webhook/transport/tests/test_utils.py b/saleor/webhook/transport/tests/test_utils.pyindex 5b600b15f4..342a024aea 100644--- a/saleor/webhook/transport/tests/test_utils.py+++ b/saleor/webhook/transport/tests/test_utils.py@@ -374,3 +374,9 @@ def test_get_sqs_message_group_id(app, app_identifier, expected_slug):message_group_id = get_sqs_message_group_id("example.com", app)assert message_group_id == f"example.com:{expected_slug or app.id}"+++def test_get_sqs_message_group_id_no_app():+ message_group_id = get_sqs_message_group_id("example.com", None)++ assert message_group_id == "example.com"diff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.pyindex 634839e2ef..1e6c116b3d 100644--- a/saleor/webhook/transport/utils.py+++ b/saleor/webhook/transport/utils.py@@ -661,7 +661,10 @@ def to_payment_app_id(app: "App", external_id: str) -> "str":return f"{APP_ID_PREFIX}:{app_identifier}:{external_id}"-def get_sqs_message_group_id(domain: str, app: "App") -> str:- identifier = slugify(app.identifier) if app.identifier else app.id- group_id = f"{domain}:{identifier}"+def get_sqs_message_group_id(domain: str, app: App | None = None) -> str:+ if app is None:+ group_id = domain+ else:+ identifier = slugify(app.identifier) if app.identifier else app.id+ group_id = f"{domain}:{identifier}"return group_id[:128] # SQS MessageGroupId max length is 128 chars