Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Move ability to control checkout funds release to channel api (#17944)
Krzysztof Waliczek7117d6e688fa
diff --git a/saleor/channel/migrations/0019_auto_20250625_1048.py b/saleor/channel/migrations/0019_auto_20250625_1048.pynew file mode 100644index 0000000000..8418464022--- /dev/null+++ b/saleor/channel/migrations/0019_auto_20250625_1048.py@@ -0,0 +1,41 @@+# Generated by Django 3.2.25 on 2025-06-25 10:48++import datetime++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("channel", "0018_channel_automatically_complete_paid_checkouts"),+ ]++ operations = [+ migrations.AddField(+ model_name="channel",+ name="checkout_release_funds_cut_off_date",+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="channel",+ name="checkout_ttl_before_releasing_funds",+ field=models.DurationField(default=datetime.timedelta(seconds=21600)),+ ),+ migrations.AddField(+ model_name="channel",+ name="release_funds_for_expired_checkouts",+ field=models.BooleanField(default=False),+ ),+ migrations.RunSQL(+ "ALTER TABLE channel_channel "+ "ALTER COLUMN checkout_ttl_before_releasing_funds "+ "SET DEFAULT '0 days 21600.000000 seconds'::interval;",+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "ALTER TABLE channel_channel "+ "ALTER COLUMN release_funds_for_expired_checkouts "+ "SET DEFAULT False;",+ reverse_sql=migrations.RunSQL.noop,+ ),+ ]diff --git a/saleor/channel/migrations/0020_migrate_checkout_ttl_release_funds.py b/saleor/channel/migrations/0020_migrate_checkout_ttl_release_funds.pynew file mode 100644index 0000000000..b3127554a8--- /dev/null+++ b/saleor/channel/migrations/0020_migrate_checkout_ttl_release_funds.py@@ -0,0 +1,61 @@+# Generated by Django 3.2.25 on 2025-06-25 10:48++from django.conf import settings+from django.db import migrations, transaction+from django.db.models import Q++BATCH_SIZE = 5000+++def queryset_in_batches(queryset):+ """Slice a queryset into batches.++ Input queryset should be sorted be pk.+ """+ start_pk = 0++ while True:+ qs = queryset.filter(pk__gt=start_pk)[:BATCH_SIZE]+ pks = list(qs.values_list("pk", flat=True))++ if not pks:+ break++ yield pks++ start_pk = pks[-1]+++def migrate_env_variable_setting_to_channels(apps, _schema_editor):+ Channel = apps.get_model("channel", "Channel")+ turn_on = int(settings.TRANSACTION_BATCH_FOR_RELEASING_FUNDS) > 0+ channels = Channel.objects.order_by("pk").filter(+ ~Q(+ checkout_ttl_before_releasing_funds=settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS+ )+ | ~Q(release_funds_for_expired_checkouts=turn_on)+ )++ for ids in queryset_in_batches(channels):+ qs = Channel.objects.filter(pk__in=ids).order_by("pk")+ if ids:+ with transaction.atomic():+ # lock the batch of objects+ _channels = list(qs.select_for_update(of=(["self"])))+ qs.update(+ checkout_ttl_before_releasing_funds=settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS,+ release_funds_for_expired_checkouts=turn_on,+ )+++class Migration(migrations.Migration):+ dependencies = [+ ("channel", "0019_auto_20250625_1048"),+ ]++ operations = [+ migrations.RunPython(+ migrate_env_variable_setting_to_channels,+ reverse_code=migrations.RunPython.noop,+ ),+ ]diff --git a/saleor/channel/migrations/0022_merge_20250708_1220.py b/saleor/channel/migrations/0022_merge_20250708_1220.pynew file mode 100644index 0000000000..6de9280fd2--- /dev/null+++ b/saleor/channel/migrations/0022_merge_20250708_1220.py@@ -0,0 +1,15 @@+# Generated by Django 4.2.20 on 2025-07-08 12:20++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("channel", "0020_migrate_checkout_ttl_release_funds"),+ (+ "channel",+ "0021_rename_use_legacy_line_voucher_propagation_for_order_channel_use_legacy_line_discount_propagation_fo",+ ),+ ]++ operations = []diff --git a/saleor/channel/migrations/0023_merge_20250709_1453.py b/saleor/channel/migrations/0023_merge_20250709_1453.pynew file mode 100644index 0000000000..eeed683a64--- /dev/null+++ b/saleor/channel/migrations/0023_merge_20250709_1453.py@@ -0,0 +1,12 @@+# Generated by Django 5.2.1 on 2025-07-09 14:53++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("channel", "0022_merge_20250527_1210"),+ ("channel", "0022_merge_20250708_1220"),+ ]++ operations = []diff --git a/saleor/channel/models.py b/saleor/channel/models.pyindex 207eaebcec..4346d13d39 100644--- a/saleor/channel/models.py+++ b/saleor/channel/models.py@@ -56,7 +56,13 @@ class Channel(ModelWithMetadata):# line lvl discounts for orders created from checkout are stored as# OrderLineDiscount. This flag controls how we should return it via API.+use_legacy_line_discount_propagation_for_order = models.BooleanField(default=True)+ release_funds_for_expired_checkouts = models.BooleanField(default=False)+ checkout_ttl_before_releasing_funds = models.DurationField(+ default=datetime.timedelta(hours=6)+ )+ checkout_release_funds_cut_off_date = models.DateTimeField(null=True, blank=True)class Meta(ModelWithMetadata.Meta):ordering = ("slug",)diff --git a/saleor/channel/tests/fixtures/channel.py b/saleor/channel/tests/fixtures/channel.pyindex 5b6df27037..87d3c7ee94 100644--- a/saleor/channel/tests/fixtures/channel.py+++ b/saleor/channel/tests/fixtures/channel.py@@ -18,6 +18,7 @@ def channel_USD(db):default_country="US",is_active=True,allocation_strategy=AllocationStrategy.PRIORITIZE_HIGH_STOCK,+ release_funds_for_expired_checkouts=True,)create_channel_tax_configuration(channel)return channel@@ -60,6 +61,7 @@ def channel_JPY(db):default_country="JP",is_active=True,allocation_strategy=AllocationStrategy.PRIORITIZE_HIGH_STOCK,+ release_funds_for_expired_checkouts=True,)create_channel_tax_configuration(channel)return channeldiff --git a/saleor/graphql/channel/mutations/channel_create.py b/saleor/graphql/channel/mutations/channel_create.pyindex 425429e933..f91796f4cf 100644--- a/saleor/graphql/channel/mutations/channel_create.py+++ b/saleor/graphql/channel/mutations/channel_create.py@@ -23,7 +23,7 @@ from ...core.doc_category import (DOC_CATEGORY_PRODUCTS,)from ...core.mutations import DeprecatedModelMutation-from ...core.scalars import Day, Hour, Minute+from ...core.scalars import DateTime, Day, Hour, Minutefrom ...core.types import BaseInputObjectType, ChannelError, NonNullListfrom ...core.types import common as common_typesfrom ...core.utils import WebhookEventInfo@@ -183,6 +183,29 @@ class PaymentSettingsInput(BaseInputObjectType):"requested action for the transaction."),)+ release_funds_for_expired_checkouts = graphene.Boolean(+ required=False,+ description=(+ "Determine if the funds for expired checkouts should be released automatically."+ + ADDED_IN_320+ ),+ )+ checkout_ttl_before_releasing_funds = Hour(+ required=False,+ description=(+ "The time in hours after which funds for expired checkouts will be released."+ + ADDED_IN_320+ ),+ )+ checkout_release_funds_cut_off_date = DateTime(+ required=False,+ description=(+ "Specifies the earliest date on which funds for expired checkouts can begin "+ "to be released. Expired checkouts dated before this cut-off will not have their "+ "funds released. Additionally, no funds will be released for checkouts that are "+ "more than one year old, regardless of the cut-off date." + ADDED_IN_320+ ),+ )class Meta:doc_category = DOC_CATEGORY_PAYMENTSdiff --git a/saleor/graphql/channel/mutations/utils.py b/saleor/graphql/channel/mutations/utils.pyindex 877a55ecdb..2560d8daa0 100644--- a/saleor/graphql/channel/mutations/utils.py+++ b/saleor/graphql/channel/mutations/utils.py@@ -42,6 +42,21 @@ def clean_delete_expired_orders_after(return datetime.timedelta(days=delete_expired_orders_after)+def clean_checkout_ttl_before_releasing_funds(+ checkout_ttl_before_releasing_funds: int,+) -> datetime.timedelta:+ if checkout_ttl_before_releasing_funds <= 0:+ raise ValidationError(+ {+ "checkout_ttl_before_releasing_funds": ValidationError(+ "The time in hours after which funds for expired checkouts will be released must be greater than 0.",+ code=ChannelErrorCode.INVALID.value,+ )+ }+ )+ return datetime.timedelta(hours=checkout_ttl_before_releasing_funds)++def clean_input_order_settings(order_settings: dict, cleaned_input: dict, instance: Channel):@@ -109,3 +124,30 @@ def clean_input_payment_settings(payment_settings: dict, cleaned_input: dict):cleaned_input["default_transaction_flow_strategy"] = (default_transaction_strategy)+ if (+ release_funds_for_expired_checkouts := payment_settings.get(+ "release_funds_for_expired_checkouts"+ )+ ) is not None:+ cleaned_input["release_funds_for_expired_checkouts"] = (+ release_funds_for_expired_checkouts+ )++ if (+ checkout_ttl_before_releasing_funds := payment_settings.get(+ "checkout_ttl_before_releasing_funds"+ )+ ) is not None:+ cleaned_input["checkout_ttl_before_releasing_funds"] = (+ clean_checkout_ttl_before_releasing_funds(+ checkout_ttl_before_releasing_funds+ )+ )++ if "checkout_release_funds_cut_off_date" in payment_settings:+ checkout_release_funds_cut_off_date = payment_settings[+ "checkout_release_funds_cut_off_date"+ ]+ cleaned_input["checkout_release_funds_cut_off_date"] = (+ checkout_release_funds_cut_off_date+ )diff --git a/saleor/graphql/channel/tests/mutations/test_channel_create.py b/saleor/graphql/channel/tests/mutations/test_channel_create.pyindex 9485fc77cf..7ae6c627f5 100644--- a/saleor/graphql/channel/tests/mutations/test_channel_create.py+++ b/saleor/graphql/channel/tests/mutations/test_channel_create.py@@ -56,6 +56,9 @@ CHANNEL_CREATE_MUTATION = """}paymentSettings {defaultTransactionFlowStrategy+ releaseFundsForExpiredCheckouts+ checkoutTtlBeforeReleasingFunds+ checkoutReleaseFundsCutOffDate}}errors{@@ -709,6 +712,100 @@ def test_channel_create_set_default_transaction_flow_strategy()+def test_channel_create_set_checkout_release_settings(+ permission_manage_channels,+ staff_api_client,+):+ # given+ name = "testName"+ slug = "test_slug"+ currency_code = "USD"+ default_country = "US"++ date = datetime.datetime(2022, 5, 12, 0, 0, 0, tzinfo=datetime.UTC)+ ttl_before_releasing_funds = 7+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ "paymentSettings": {+ "releaseFundsForExpiredCheckouts": False,+ "checkoutTtlBeforeReleasingFunds": ttl_before_releasing_funds,+ "checkoutReleaseFundsCutOffDate": date,+ },+ }+ }++ # 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 not channel_data["paymentSettings"]["releaseFundsForExpiredCheckouts"]+ assert (+ channel_data["paymentSettings"]["checkoutTtlBeforeReleasingFunds"]+ == ttl_before_releasing_funds+ )+ assert (+ channel_data["paymentSettings"]["checkoutReleaseFundsCutOffDate"]+ == "2022-05-12T00:00:00+00:00"+ )++ assert not channel.release_funds_for_expired_checkouts+ assert channel.checkout_ttl_before_releasing_funds == datetime.timedelta(+ hours=ttl_before_releasing_funds+ )+ assert channel.checkout_release_funds_cut_off_date == date+++def test_channel_create_set_incorect_checkout_ttl_before_releasing_funds(+ permission_manage_channels,+ staff_api_client,+):+ # given+ name = "testName"+ slug = "test_slug"+ currency_code = "USD"+ default_country = "US"++ ttl_before_releasing_funds = 0+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ "paymentSettings": {+ "checkoutTtlBeforeReleasingFunds": ttl_before_releasing_funds,+ },+ }+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_CREATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["channelCreate"]["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "checkoutTtlBeforeReleasingFunds"+ assert errors[0]["code"] == ChannelErrorCode.INVALID.name++def test_channel_create_set_delete_expired_orders_after(permission_manage_channels,staff_api_client,diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.pyindex e737fe79f3..e6bb0c67cb 100644--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py@@ -1536,6 +1536,9 @@ CHANNEL_UPDATE_MUTATION_WITH_PAYMENT_SETTINGS = """currencyCodepaymentSettings {defaultTransactionFlowStrategy+ releaseFundsForExpiredCheckouts+ checkoutTtlBeforeReleasingFunds+ checkoutReleaseFundsCutOffDate}}errors{@@ -1591,6 +1594,88 @@ def test_channel_update_default_transaction_flow_strategy()+def test_channel_update_checkout_release_settings(+ permission_manage_channels,+ staff_api_client,+ channel_USD,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ date = datetime.datetime(2022, 5, 12, 0, 0, 0, tzinfo=datetime.UTC)+ ttl_before_releasing_funds = 7+ variables = {+ "id": channel_id,+ "input": {+ "paymentSettings": {+ "releaseFundsForExpiredCheckouts": False,+ "checkoutTtlBeforeReleasingFunds": ttl_before_releasing_funds,+ "checkoutReleaseFundsCutOffDate": date,+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_PAYMENT_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"]+ assert not channel_data["paymentSettings"]["releaseFundsForExpiredCheckouts"]+ assert (+ channel_data["paymentSettings"]["checkoutTtlBeforeReleasingFunds"]+ == ttl_before_releasing_funds+ )+ assert (+ channel_data["paymentSettings"]["checkoutReleaseFundsCutOffDate"]+ == "2022-05-12T00:00:00+00:00"+ )++ channel_USD.refresh_from_db()+ assert not channel_USD.release_funds_for_expired_checkouts+ assert channel_USD.checkout_ttl_before_releasing_funds == datetime.timedelta(+ hours=ttl_before_releasing_funds+ )+ assert channel_USD.checkout_release_funds_cut_off_date == date+++def test_channel_create_set_incorect_checkout_ttl_before_releasing_funds(+ permission_manage_channels,+ staff_api_client,+ channel_USD,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ ttl_before_releasing_funds = 0+ variables = {+ "id": channel_id,+ "input": {+ "paymentSettings": {+ "checkoutTtlBeforeReleasingFunds": ttl_before_releasing_funds,+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_PAYMENT_SETTINGS,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["channelUpdate"]["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "checkoutTtlBeforeReleasingFunds"+ assert errors[0]["code"] == ChannelErrorCode.INVALID.name++def test_channel_update_default_transaction_flow_strategy_with_payment_permission(permission_manage_payments,staff_api_client,diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.pyindex 92e83f74a3..145dee2ed9 100644--- a/saleor/graphql/channel/types.py+++ b/saleor/graphql/channel/types.py@@ -32,7 +32,7 @@ from ..core.doc_category import (DOC_CATEGORY_TAXES,)from ..core.fields import PermissionsField-from ..core.scalars import Day, Hour, Minute+from ..core.scalars import DateTime, Day, Hour, Minutefrom ..core.types import BaseObjectType, CountryDisplay, ModelObjectType, NonNullListfrom ..meta.types import ObjectWithMetadatafrom ..tax.dataloaders import TaxConfigurationByChannelId@@ -191,6 +191,29 @@ class PaymentSettings(ObjectType):"requested action for the transaction."),)+ release_funds_for_expired_checkouts = graphene.Boolean(+ required=False,+ description=(+ "Determine if the funds for expired checkouts should be released automatically."+ + ADDED_IN_320+ ),+ )+ checkout_ttl_before_releasing_funds = Hour(+ required=False,+ description=(+ "The time in hours after which funds for expired checkouts will be released."+ + ADDED_IN_320+ ),+ )+ checkout_release_funds_cut_off_date = DateTime(+ required=False,+ description=(+ "Specifies the earliest date on which funds for expired checkouts can begin "+ "to be released. Expired checkouts dated before this cut-off will not have their "+ "funds released. Additionally, no funds will be released for checkouts that are "+ "more than one year old, regardless of the cut-off date." + ADDED_IN_320+ ),+ )class Meta:description = "Represents the channel-specific payment settings."@@ -493,4 +516,8 @@ class Channel(ModelObjectType):def resolve_payment_settings(root: models.Channel, _info):return PaymentSettings(default_transaction_flow_strategy=root.default_transaction_flow_strategy,+ release_funds_for_expired_checkouts=root.release_funds_for_expired_checkouts,+ checkout_ttl_before_releasing_funds=root.checkout_ttl_before_releasing_funds.seconds+ // 3600,+ checkout_release_funds_cut_off_date=root.checkout_release_funds_cut_off_date,)diff --git a/saleor/graphql/core/scalars.py b/saleor/graphql/core/scalars.pyindex 019cc18ac3..8e8b216654 100644--- a/saleor/graphql/core/scalars.py+++ b/saleor/graphql/core/scalars.py@@ -203,9 +203,9 @@ class Minute(graphene.Int):"""The `Minute` scalar type represents number of minutes by integer value."""-class Day(graphene.Int):- """The `Day` scalar type represents number of days by integer value."""--class Hour(graphene.Int):"""The `Hour` scalar type represents number of hours by integer value."""+++class Day(graphene.Int):+ """The `Day` scalar type represents number of days by integer value."""diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex e8ee7bc6e7..bdc7c819c9 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -5390,6 +5390,27 @@ type PaymentSettings {Determine the transaction flow strategy to be used. Include the selected option in the payload sent to the payment app, as a requested action for the transaction."""defaultTransactionFlowStrategy: TransactionFlowStrategyEnum!++ """+ Determine if the funds for expired checkouts should be released automatically.++ Added in Saleor 3.20.+ """+ releaseFundsForExpiredCheckouts: Boolean++ """+ The time in hours after which funds for expired checkouts will be released.++ Added in Saleor 3.20.+ """+ checkoutTtlBeforeReleasingFunds: Hour++ """+ Specifies the earliest date on which funds for expired checkouts can begin to be released. Expired checkouts dated before this cut-off will not have their funds released. Additionally, no funds will be released for checkouts that are more than one year old, regardless of the cut-off date.++ Added in Saleor 3.20.+ """+ checkoutReleaseFundsCutOffDate: DateTime}"""@@ -28432,6 +28453,27 @@ input PaymentSettingsInput @doc(category: "Payments") {Determine the transaction flow strategy to be used. Include the selected option in the payload sent to the payment app, as a requested action for the transaction."""defaultTransactionFlowStrategy: TransactionFlowStrategyEnum++ """+ Determine if the funds for expired checkouts should be released automatically.++ Added in Saleor 3.20.+ """+ releaseFundsForExpiredCheckouts: Boolean++ """+ The time in hours after which funds for expired checkouts will be released.++ Added in Saleor 3.20.+ """+ checkoutTtlBeforeReleasingFunds: Hour++ """+ Specifies the earliest date on which funds for expired checkouts can begin to be released. Expired checkouts dated before this cut-off will not have their funds released. Additionally, no funds will be released for checkouts that are more than one year old, regardless of the cut-off date.++ Added in Saleor 3.20.+ """+ checkoutReleaseFundsCutOffDate: DateTime}"""diff --git a/saleor/payment/tasks.py b/saleor/payment/tasks.pyindex 2913df3945..47571b96f5 100644--- a/saleor/payment/tasks.py+++ b/saleor/payment/tasks.py@@ -5,7 +5,7 @@ import uuidimport graphenefrom django.conf import settingsfrom django.db import transaction-from django.db.models import Exists, OuterRef, Q+from django.db.models import DateTimeField, Exists, ExpressionWrapper, OuterRef, Qfrom ..celeryconf import appfrom ..channel.models import Channel@@ -27,17 +27,43 @@ def transactions_to_release_funds():predefined TTL. It then fetches related transactions that are authorized or charged,ready for fund release."""- expired_checkouts_time = (- datetime.datetime.now(tz=datetime.UTC)- - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS+ now = datetime.datetime.now(datetime.UTC)+ channels = (+ Channel.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .annotate(+ last_transaction_modified_at=ExpressionWrapper(+ OuterRef(+ "last_transaction_modified_at",+ ),+ output_field=DateTimeField(),+ )+ )+ .filter(+ Q(release_funds_for_expired_checkouts=True)+ & Q(+ checkout_ttl_before_releasing_funds__lt=now - OuterRef("last_change") # type: ignore[operator]+ )+ & (+ Q(last_transaction_modified_at__isnull=True)+ | Q(+ checkout_ttl_before_releasing_funds__lt=now+ - OuterRef("last_transaction_modified_at") # type: ignore[operator]+ )+ )+ & Q(pk=OuterRef("channel_id"))+ & (+ Q(checkout_release_funds_cut_off_date__isnull=True)+ | Q(checkout_release_funds_cut_off_date__lt=OuterRef("created_at"))+ )+ ))checkouts = Checkout.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).filter(+ Exists(channels),+ created_at__gt=now - datetime.timedelta(days=365),automatically_refundable=True,- last_change__lt=expired_checkouts_time,- last_transaction_modified_at__lt=expired_checkouts_time,authorize_status__in=[CheckoutAuthorizeStatus.PARTIAL,CheckoutAuthorizeStatus.FULL,diff --git a/saleor/payment/tests/fixtures/transaction_item.py b/saleor/payment/tests/fixtures/transaction_item.pyindex ebf7763638..c31084f9fb 100644--- a/saleor/payment/tests/fixtures/transaction_item.py+++ b/saleor/payment/tests/fixtures/transaction_item.py@@ -33,6 +33,7 @@ def transaction_item_generator():cc_exp_month=None,cc_exp_year=None,metadata=None,+ currency="USD",):if available_actions is None:available_actions = []@@ -44,7 +45,7 @@ def transaction_item_generator():message=message,psp_reference=psp_reference,available_actions=available_actions,- currency="USD",+ currency=currency,order_id=order_id,checkout_id=checkout_id,app_identifier=app.identifier if app else None,diff --git a/saleor/payment/tests/test_tasks.py b/saleor/payment/tests/test_tasks.pyindex 60b6a9c0a1..f064f1a8aa 100644--- a/saleor/payment/tests/test_tasks.py+++ b/saleor/payment/tests/test_tasks.py@@ -7,7 +7,10 @@ from freezegun import freeze_timefrom ...checkout import CheckoutAuthorizeStatus, CheckoutChargeStatusfrom ...checkout.actions import transaction_amounts_for_checkout_updatedfrom .. import TransactionAction, TransactionEventType-from ..tasks import transaction_release_funds_for_checkout_task+from ..tasks import (+ transaction_release_funds_for_checkout_task,+ transactions_to_release_funds,+)@mock.patch("saleor.payment.tasks.request_cancelation_action")@@ -22,10 +25,7 @@ def test_transaction_release_funds_for_checkout_task_checkout_with_new_last_chanplugins_manager,):# given- ttl_time = (- datetime.datetime.now(tz=datetime.UTC)- - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS- )+ ttl_time = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(hours=6)time_before_ttl = ttl_time + datetime.timedelta(seconds=1)time_after_ttl = ttl_time - datetime.timedelta(seconds=1)with freeze_time(time_after_ttl):@@ -63,10 +63,7 @@ def test_transaction_release_funds_for_checkout_task_checkout_not_refundable(plugins_manager,):# given- ttl_time = (- datetime.datetime.now(tz=datetime.UTC)- - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS- )+ ttl_time = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(hours=6)time_after_ttl = ttl_time - datetime.timedelta(seconds=1)with freeze_time(time_after_ttl):transaction_item = transaction_item_generator(@@ -101,10 +98,7 @@ def test_transaction_release_funds_for_checkout_task_checkout_with_new_tr_modifiplugins_manager,):# given- ttl_time = (- datetime.datetime.now(tz=datetime.UTC)- - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS- )+ ttl_time = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(hours=6)time_before_ttl = ttl_time + datetime.timedelta(seconds=1)time_after_ttl = ttl_time - datetime.timedelta(seconds=1)with freeze_time(time_before_ttl):@@ -142,10 +136,7 @@ def test_transaction_release_funds_for_checkout_task_checkout_with_none_status(plugins_manager,):# given- ttl_time = (- datetime.datetime.now(tz=datetime.UTC)- - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS- )+ ttl_time = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(hours=6)time_after_ttl = ttl_time - datetime.timedelta(seconds=1)with freeze_time(time_after_ttl):transaction_item = transaction_item_generator(@@ -181,10 +172,7 @@ def test_transaction_release_funds_for_checkout_task_not_valid_checkout(plugins_manager,):# given- ttl_time = (- datetime.datetime.now(tz=datetime.UTC)- - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS- )+ ttl_time = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(hours=6)time_after_ttl = ttl_time - datetime.timedelta(seconds=1)with freeze_time(time_after_ttl):transaction_item_generator(@@ -211,10 +199,7 @@ def test_transaction_release_funds_for_checkout_task_transaction_for_order(plugins_manager,):# given- ttl_time = (- datetime.datetime.now(tz=datetime.UTC)- - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS- )+ ttl_time = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(hours=6)time_after_ttl = ttl_time - datetime.timedelta(seconds=1)with freeze_time(time_after_ttl):transaction_item_generator(@@ -242,10 +227,7 @@ def test_transaction_release_funds_for_checkout_task_without_transaction(plugins_manager,):# given- ttl_time = (- datetime.datetime.now(tz=datetime.UTC)- - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS- )+ ttl_time = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(hours=6)time_after_ttl = ttl_time - datetime.timedelta(seconds=1)with freeze_time(time_after_ttl):checkout.authorize_status = CheckoutAuthorizeStatus.FULL@@ -280,10 +262,7 @@ def test_transaction_release_funds_for_checkout_task_refund_already_requested(plugins_manager,):# given- ttl_time = (- datetime.datetime.now(tz=datetime.UTC)- - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS- )+ ttl_time = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(hours=6)time_after_ttl = ttl_time - datetime.timedelta(seconds=1)with freeze_time(time_after_ttl):transaction_item = transaction_item_generator(@@ -320,10 +299,7 @@ def test_transaction_release_funds_for_checkout_task_cancel_already_requested(plugins_manager,):# given- ttl_time = (- datetime.datetime.now(tz=datetime.UTC)- - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS- )+ ttl_time = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(hours=6)time_after_ttl = ttl_time - datetime.timedelta(seconds=1)with freeze_time(time_after_ttl):transaction_item = transaction_item_generator(@@ -360,10 +336,7 @@ def test_transaction_release_funds_for_checkout_task_transaction_with_authorizatplugins_manager,):# given- ttl_time = (- datetime.datetime.now(tz=datetime.UTC)- - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS- )+ ttl_time = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(hours=6)time_after_ttl = ttl_time - datetime.timedelta(seconds=1)with freeze_time(time_after_ttl):transaction_item = transaction_item_generator(@@ -411,10 +384,7 @@ def test_transaction_release_funds_for_checkout_task_transaction_with_charge(plugins_manager,):# given- ttl_time = (- datetime.datetime.now(tz=datetime.UTC)- - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS- )+ ttl_time = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(hours=6)time_after_ttl = ttl_time - datetime.timedelta(seconds=1)with freeze_time(time_after_ttl):transaction_item = transaction_item_generator(@@ -447,3 +417,77 @@ def test_transaction_release_funds_for_checkout_task_transaction_with_charge()transaction_item.refresh_from_db()assert transaction_item.last_refund_success is False+++@freeze_time("2021-03-18 12:00:00")+def test_transactions_to_release_funds_setting_toogle(+ channel_USD,+ channel_JPY,+ checkout,+ checkout_JPY,+ settings,+ transaction_item_generator,+ plugins_manager,+):+ # given+ channel_USD.release_funds_for_expired_checkouts = False+ channel_USD.save()+ channel_JPY.release_funds_for_expired_checkouts = True+ channel_JPY.save()++ ttl_time = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(hours=6)+ time_after_ttl = ttl_time - datetime.timedelta(seconds=1)+ with freeze_time(time_after_ttl):+ transactions_for_checkout = {}+ for current_checkout in (checkout, checkout_JPY):+ transaction_item = transaction_item_generator(+ checkout_id=current_checkout.pk,+ charged_value=Decimal(100),+ currency=current_checkout.channel.currency_code,+ )+ transaction_amounts_for_checkout_updated(+ transaction_item, plugins_manager, user=None, app=None+ )+ current_checkout.automatically_refundable = True+ current_checkout.save(+ update_fields=["automatically_refundable", "last_change"]+ )+ transactions_for_checkout[current_checkout.pk] = transaction_item++ # when+ transactions = transactions_to_release_funds()++ # then+ assert len(transactions) == 1+ assert transactions[0].id == transactions_for_checkout[checkout_JPY.pk].id+++@freeze_time("2021-03-18 12:00:00")+def test_transactions_to_release_funds_after_year(+ channel_USD,+ checkout,+ checkout_JPY,+ settings,+ transaction_item_generator,+ plugins_manager,+):+ # given+ ttl_time = datetime.datetime.now(tz=datetime.UTC)+ time_after_ttl = ttl_time - datetime.timedelta(seconds=1)+ with freeze_time(time_after_ttl):+ transaction_item = transaction_item_generator(+ checkout_id=checkout.pk,+ charged_value=Decimal(100),+ )+ transaction_amounts_for_checkout_updated(+ transaction_item, plugins_manager, user=None, app=None+ )+ checkout.automatically_refundable = True+ checkout.created_at = ttl_time - datetime.timedelta(days=366)+ checkout.save(update_fields=["automatically_refundable", "last_change"])++ # when+ transactions = transactions_to_release_funds()++ # then+ assert len(transactions) == 0