Skip to content

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

Release funds for abandoned checkouts (#14870)

Maciej Korycinski76c916269713
diff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.py
index 5dcd69141f..8f2f4e055d 100644
--- a/saleor/checkout/actions.py
+++ b/saleor/checkout/actions.py
@@ -1,3 +1,4 @@
+from decimal import Decimal
from typing import cast
from ..core.utils.events import call_event
@@ -7,6 +8,7 @@ from . import CheckoutChargeStatus
from .calculations import fetch_checkout_data
from .fetch import fetch_checkout_info, fetch_checkout_lines
from .models import Checkout
+from .payment_utils import update_refundable_for_checkout
def transaction_amounts_for_checkout_updated(
@@ -28,5 +30,23 @@ def transaction_amounts_for_checkout_updated(
CheckoutChargeStatus.FULL,
CheckoutChargeStatus.OVERCHARGED,
]
+
+ if (
+ not checkout.last_transaction_modified_at
+ or checkout.last_transaction_modified_at < transaction.modified_at
+ ):
+ checkout.last_transaction_modified_at = transaction.modified_at
+ checkout.save(update_fields=["last_transaction_modified_at"])
+
+ refundable = transaction.last_refund_success and (
+ transaction.authorized_value > Decimal(0)
+ or transaction.charged_value > Decimal(0)
+ )
+ if refundable != checkout.automatically_refundable:
+ # if last_refund_status is different than automatically_refundable
+ # we need to recalculate automatically_refundable based on the rest of
+ # checkout's transactions
+ update_refundable_for_checkout(checkout.pk)
+
if not previous_charge_status_is_fully_paid and current_status_is_fully_paid:
call_event(manager.checkout_fully_paid, checkout_info.checkout)
diff --git a/saleor/checkout/migrations/0060_fix_charge_and_authorize_status_for_empty_checkouts.py b/saleor/checkout/migrations/0060_fix_charge_and_authorize_status_for_empty_checkouts.py
index a99f86beed..4546631ce1 100644
--- a/saleor/checkout/migrations/0060_fix_charge_and_authorize_status_for_empty_checkouts.py
+++ b/saleor/checkout/migrations/0060_fix_charge_and_authorize_status_for_empty_checkouts.py
@@ -144,6 +144,7 @@ def fix_charge_status_for_empty_checkouts(apps, _schema_editor):
class Migration(migrations.Migration):
dependencies = [
("checkout", "0059_merge_0058"),
+ ("payment", "0049_auto_20230322_0634"),
]
operations = [
migrations.RunPython(
diff --git a/saleor/checkout/migrations/0061_checkout_last_transaction_modified_at_and_refundable.py b/saleor/checkout/migrations/0061_checkout_last_transaction_modified_at_and_refundable.py
new file mode 100644
index 0000000000..a58100b3b1
--- /dev/null
+++ b/saleor/checkout/migrations/0061_checkout_last_transaction_modified_at_and_refundable.py
@@ -0,0 +1,29 @@
+# Generated by Django 3.2.22 on 2023-11-15 08:30
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0060_fix_charge_and_authorize_status_for_empty_checkouts"),
+ ("payment", "0049_auto_20230322_0634"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="checkout",
+ name="last_transaction_modified_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="checkout",
+ name="automatically_refundable",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE checkout_checkout ALTER COLUMN automatically_refundable
+ SET DEFAULT false;
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/checkout/migrations/0062_update_checkout_last_transaction_modified_at_and_refundable.py b/saleor/checkout/migrations/0062_update_checkout_last_transaction_modified_at_and_refundable.py
new file mode 100644
index 0000000000..c105c318ee
--- /dev/null
+++ b/saleor/checkout/migrations/0062_update_checkout_last_transaction_modified_at_and_refundable.py
@@ -0,0 +1,65 @@
+from django.db import migrations
+from django.db.models import Exists, OuterRef, Q, Subquery
+
+# It takes less that a second to process the batch.
+# The memory usage peak on celery worker was around 40MB.
+BATCH_SIZE = 2000
+
+
+def add_transaction_modified_at_to_checkouts(apps, _schema_editor):
+ Checkout = apps.get_model("checkout", "Checkout")
+ TransactionItem = apps.get_model("payment", "TransactionItem")
+
+ while True:
+ checkouts_without_modified_at = Checkout.objects.filter(
+ Exists(TransactionItem.objects.filter(checkout_id=OuterRef("pk"))),
+ last_transaction_modified_at__isnull=True,
+ ).values_list("pk", flat=True)[:BATCH_SIZE]
+ if not checkouts_without_modified_at:
+ break
+ transaction_subquery = TransactionItem.objects.filter(
+ checkout_id=OuterRef("pk")
+ ).order_by("-modified_at")
+ Checkout.objects.filter(pk__in=checkouts_without_modified_at).update(
+ last_transaction_modified_at=Subquery(
+ transaction_subquery.values("modified_at")[:1]
+ )
+ )
+
+
+def calculate_checkout_refundable(apps, _schema_editor):
+ Checkout = apps.get_model("checkout", "Checkout")
+ TransactionItem = apps.get_model("payment", "TransactionItem")
+
+ with_transactions = TransactionItem.objects.filter(
+ Q(checkout_id=OuterRef("pk"))
+ & (Q(authorized_value__gt=0) | Q(charged_value__gt=0))
+ )
+
+ while True:
+ checkout_to_update = Checkout.objects.filter(
+ Exists(with_transactions), automatically_refundable=False
+ ).values_list("pk", flat=True)[:BATCH_SIZE]
+ if not checkout_to_update:
+ break
+
+ Checkout.objects.filter(pk__in=checkout_to_update).update(
+ automatically_refundable=True
+ )
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0061_checkout_last_transaction_modified_at_and_refundable"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ add_transaction_modified_at_to_checkouts,
+ reverse_code=migrations.RunPython.noop,
+ ),
+ migrations.RunPython(
+ calculate_checkout_refundable,
+ reverse_code=migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/checkout/migrations/tasks/saleor3_14.py b/saleor/checkout/migrations/tasks/saleor3_14.py
new file mode 100644
index 0000000000..1874a54c45
--- /dev/null
+++ b/saleor/checkout/migrations/tasks/saleor3_14.py
@@ -0,0 +1,61 @@
+from django.db import transaction
+from django.db.models.expressions import Exists, OuterRef, Q
+
+from ....celeryconf import app
+from ....payment.models import TransactionItem
+from ...models import Checkout
+
+# It takes less that a second to process the batch.
+# The memory usage peak on celery worker was around 40MB.
+BATCH_SIZE = 2000
+
+
+def update_transaction_modified_at_in_checkouts():
+ checkouts_without_modified_at = Checkout.objects.filter(
+ Exists(TransactionItem.objects.filter(checkout_id=OuterRef("pk"))),
+ last_transaction_modified_at__isnull=True,
+ ).values_list("pk", flat=True)[:BATCH_SIZE]
+
+ if checkouts_without_modified_at:
+ checkouts = Checkout.objects.filter(
+ pk__in=checkouts_without_modified_at
+ ).prefetch_related("payment_transactions")
+ checkouts_to_update = []
+ for checkout in checkouts:
+ payment_transactions = list(checkout.payment_transactions.all())
+ last_transaction = sorted(
+ payment_transactions, key=lambda t: t.modified_at
+ )[-1]
+ checkout.last_transaction_modified_at = last_transaction.modified_at
+ checkouts_to_update.append(checkout)
+ with transaction.atomic():
+ # lock the batch of objects
+ # multiple celery migration tasks called for the same model can cause
+ # deadlock. Before updating the objects we need to lock them.
+ _checkouts_lock = list(checkouts.select_for_update(of=(["self"])))
+ Checkout.objects.bulk_update(
+ checkouts_to_update, ["last_transaction_modified_at"]
+ )
+ update_transaction_modified_at_in_checkouts.delay()
+
+
+def update_checkout_refundable():
+ with_transactions = TransactionItem.objects.filter(
+ Q(checkout_id=OuterRef("pk"))
+ & (Q(authorized_value__gt=0) | Q(charged_value__gt=0))
+ )
+ checkout_to_update = Checkout.objects.filter(
+ Exists(with_transactions), automatically_refundable=False
+ ).values_list("pk", flat=True)[:BATCH_SIZE]
+
+ if checkout_to_update:
+ with transaction.atomic():
+ # lock the batch of objects
+ # multiple celery migration tasks called for the same model can cause
+ # deadlock. Before updating the objects we need to lock them.
+ _checkout_lock = list(checkout_to_update.select_for_update(of=(["self"])))
+ checkout_to_update.update(automatically_refundable=True)
+
+ update_checkout_refundable.delay()
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index ec202e70eb..601585494a 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -42,6 +42,12 @@ class Checkout(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
last_change = models.DateTimeField(auto_now=True, db_index=True)
+
+ # Denormalized modified_at for the latest modified transactionItem assigned to
+ # checkout
+ last_transaction_modified_at = models.DateTimeField(null=True, blank=True)
+ automatically_refundable = models.BooleanField(default=False)
+
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
blank=True,
diff --git a/saleor/checkout/payment_utils.py b/saleor/checkout/payment_utils.py
index a95ee460b2..b9c6ca46f4 100644
--- a/saleor/checkout/payment_utils.py
+++ b/saleor/checkout/payment_utils.py
@@ -1,16 +1,15 @@
"""Checkout-related utility functions."""
from collections.abc import Iterable
-from typing import TYPE_CHECKING, Optional
+from typing import Optional
+from django.db.models import Exists, Q
from prices import Money
from ..core.taxes import zero_money
+from ..payment.models import TransactionItem
from . import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .models import Checkout
-if TYPE_CHECKING:
- from ..payment.models import TransactionItem
-
def _update_charge_status(
checkout: Checkout,
@@ -112,3 +111,19 @@ def update_checkout_payment_statuses(
if fields_to_update:
fields_to_update.append("last_change")
checkout.save(update_fields=fields_to_update)
+
+
+def update_refundable_for_checkout(checkout_pk):
+ """Update automatically refundable status for checkout.
+
+ The refundable status is calculated based on the transaction. If transaction is
+ not refundable or doesn't have enough funds to refund, the function will calculate
+ the status based on the rest of transactions for the checkout.
+ """
+ transactions_subquery = TransactionItem.objects.filter(
+ Q(checkout_id=checkout_pk, last_refund_success=True)
+ & (Q(authorized_value__gt=0) | Q(charged_value__gt=0))
+ )
+ Checkout.objects.filter(pk=checkout_pk).update(
+ automatically_refundable=Exists(transactions_subquery)
+ )
diff --git a/saleor/checkout/tests/test_actions.py b/saleor/checkout/tests/test_actions.py
index 05b69826d8..7d77ffe36f 100644
--- a/saleor/checkout/tests/test_actions.py
+++ b/saleor/checkout/tests/test_actions.py
@@ -1,5 +1,11 @@
+import datetime
+from decimal import Decimal
from unittest.mock import patch
+import pytest
+import pytz
+from freezegun import freeze_time
+
from ...tests.utils import flush_post_commit_hooks
from .. import CheckoutAuthorizeStatus, CheckoutChargeStatus
from ..actions import transaction_amounts_for_checkout_updated
@@ -60,3 +66,224 @@ def test_transaction_amounts_for_checkout_updated_with_already_fully_paid(
assert checkout.charge_status == CheckoutChargeStatus.OVERCHARGED
assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
assert not mocked_fully_paid.called
+
+
+ "previous_modified_at",
+ [None, datetime.datetime(2018, 5, 31, 12, 0, 0, tzinfo=pytz.UTC)],
+)
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+@freeze_time("2023-05-31 12:00:01")
+def test_transaction_amounts_for_checkout_updated_updates_last_transaction_modified_at(
+ mocked_fully_paid,
+ previous_modified_at,
+ checkout_with_items,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_items
+ checkout.last_transaction_modified_at = previous_modified_at
+ checkout.save(update_fields=["last_transaction_modified_at"])
+
+ 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
+ )
+
+ # when
+ transaction_amounts_for_checkout_updated(transaction, manager=plugins_manager)
+
+ # then
+ flush_post_commit_hooks()
+ checkout.refresh_from_db()
+ assert checkout.last_transaction_modified_at == transaction.modified_at
+ mocked_fully_paid.assert_called_with(checkout)
+
+
+def test_get_checkout_refundable_with_transaction_and_last_refund_success(
+ checkout_with_items,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # 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=Decimal(10.0)
+ )
+
+ # when
+ transaction_amounts_for_checkout_updated(transaction, manager=plugins_manager)
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.automatically_refundable is True
+
+
+def test_get_checkout_refundable_with_transaction_and_last_refund_failure(
+ checkout_with_items,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_items
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable"])
+
+ 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=Decimal(10.0), last_refund_success=False
+ )
+
+ # when
+ transaction_amounts_for_checkout_updated(transaction, manager=plugins_manager)
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.automatically_refundable is False
+
+
+def test_get_checkout_refundable_with_transaction_without_funds(
+ checkout_with_items,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_items
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable"])
+
+ 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=Decimal(0)
+ )
+
+ # when
+ transaction_amounts_for_checkout_updated(transaction, manager=plugins_manager)
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.automatically_refundable is False
+
+
+def test_get_checkout_refundable_with_multiple_transactions_without_funds(
+ checkout_with_items,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_items
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable"])
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info,
+ plugins_manager,
+ lines,
+ )
+ first_transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=Decimal(0)
+ )
+ transaction_item_generator(checkout_id=checkout.pk, charged_value=Decimal(0))
+
+ # when
+ transaction_amounts_for_checkout_updated(first_transaction, manager=plugins_manager)
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.automatically_refundable is False
+
+
+def test_get_checkout_refundable_with_multiple_transactions_with_failure_refund(
+ checkout_with_items,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_items
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable"])
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info,
+ plugins_manager,
+ lines,
+ )
+ first_transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=Decimal(10), last_refund_success=False
+ )
+ transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=Decimal(10), last_refund_success=False
+ )
+
+ # when
+ transaction_amounts_for_checkout_updated(first_transaction, manager=plugins_manager)
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.automatically_refundable is False
+
+
+def test_get_checkout_refundable_with_multiple_active_transactions(
+ checkout_with_items,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_items
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable"])
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info,
+ plugins_manager,
+ lines,
+ )
+ first_transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=Decimal(10), last_refund_success=False
+ )
+ transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=Decimal(10), last_refund_success=True
+ )
+ transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=Decimal(10), last_refund_success=True
+ )
+
+ # when
+ transaction_amounts_for_checkout_updated(first_transaction, manager=plugins_manager)
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.automatically_refundable is True
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
index 4c445dce6d..63815869db 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
@@ -126,6 +126,7 @@ class TransactionEventReport(ModelMutation):
"charge_pending_value",
"refund_pending_value",
"cancel_pending_value",
+ "modified_at",
]
if (
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
index fad227378b..7aaa7e9080 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -3,6 +3,7 @@ from unittest.mock import patch
import graphene
import pytest
+from freezegun import freeze_time
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
@@ -1865,3 +1866,35 @@ def test_transaction_create_for_order_triggers_webhook_when_partially_refunded(
assert not mock_order_fully_refunded.called
mock_order_updated.assert_called_once_with(order_with_lines)
mock_order_refunded.assert_called_once_with(order_with_lines)
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_transaction_create_for_checkout_updates_last_transaction_modified_at(
+ checkout_with_items, permission_manage_payments, app_api_client
+):
+ # given
+ assert checkout_with_items.last_transaction_modified_at is None
+ psp_reference = "PSP reference - 123"
+ authorized_value = Decimal("10")
+
+ variables = {
+ "id": graphene.Node.to_global_id("Checkout", checkout_with_items.pk),
+ "transaction": {
+ "pspReference": psp_reference,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+ transaction = checkout_with_items.payment_transactions.first()
+
+ assert checkout_with_items.last_transaction_modified_at == transaction.modified_at
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
index 8ba6faa97d..4df49549d4 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -1,10 +1,13 @@
+from datetime import datetime
from decimal import Decimal
from unittest.mock import patch
from uuid import uuid4
import graphene
import pytest
+import pytz
from django.utils import timezone
+from freezegun import freeze_time
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
@@ -1123,6 +1126,69 @@ def test_transaction_event_updates_checkout_payment_statuses(
assert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+ "current_last_transaction_modified_at",
+ [None, datetime(2000, 5, 31, 12, 0, 0, tzinfo=pytz.UTC)],
+)
+@freeze_time("2018-05-31 12:00:01")
+def test_transaction_event_updates_checkout_last_transaction_modified_at(
+ current_last_transaction_modified_at,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ checkout_with_items,
+):
+ # given
+ checkout = checkout_with_items
+ checkout.last_transaction_modified_at = current_last_transaction_modified_at
+ checkout.save()
+
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ transaction = 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": amount,
+ "pspReference": psp_reference,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+ checkout.refresh_from_db()
+ transaction.refresh_from_db()
+
+ assert checkout.last_transaction_modified_at != current_last_transaction_modified_at
+ assert checkout.last_transaction_modified_at == transaction.modified_at
+
+
@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
def test_transaction_event_updates_checkout_full_paid_with_charged_amount(
mocked_fully_paid,
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
index 308eb0acfa..34e497c53d 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
@@ -1,7 +1,9 @@
+import datetime
from decimal import Decimal
from unittest import mock
import pytest
+from freezegun import freeze_time
from .....channel import TransactionFlowStrategy
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
@@ -943,7 +945,6 @@ def test_app_with_action_field(
webhook_app,
transaction_session_response,
transaction_item_generator,
- permission_manage_payments,
):
# given
checkout = checkout_with_prices
@@ -987,9 +988,7 @@ def test_customer_with_action_field(
app_api_client,
checkout_with_prices,
webhook_app,
- transaction_session_response,
transaction_item_generator,
- permission_manage_payments,
):
# given
checkout = checkout_with_prices
@@ -1022,9 +1021,7 @@ def test_incorrect_source_object_id(
user_api_client,
checkout_with_prices,
webhook_app,
- transaction_session_response,
transaction_item_generator,
- permission_manage_payments,
product,
):
# given
@@ -1442,3 +1439,66 @@ def test_customer_ip_address_ipv6(
),
)
)
+
+
+@freeze_time("2023-03-18 12:00:00")
+ "previous_last_transaction_modified_at",
+ [None, datetime.datetime(2020, 1, 1)],
+)
[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_updates_checkout_last_transaction_modified_at(
+ mocked_initialize,
+ mocked_fully_paid,
+ previous_last_transaction_modified_at,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ checkout.last_transaction_modified_at = previous_last_transaction_modified_at
+ checkout.save()
+
+ 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()
+
+ 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"]
+ checkout.refresh_from_db()
+ transaction = checkout.payment_transactions.first()
+ assert checkout.last_transaction_modified_at == transaction.modified_at
+ assert (
+ checkout.last_transaction_modified_at != previous_last_transaction_modified_at
+ )
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
index 2e6f9f8ee3..ea0d42d7d2 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
@@ -1,8 +1,11 @@
+import datetime
from decimal import Decimal
from unittest import mock
import graphene
import pytest
+import pytz
+from freezegun import freeze_time
from .....channel import TransactionFlowStrategy
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
@@ -1288,3 +1291,77 @@ def test_customer_ip_address_ipv6(
),
)
)
+
+
+@freeze_time("2023-03-18 12:00:00")
+ "previous_last_transaction_modified_at",
+ [None, datetime.datetime(2020, 1, 1, tzinfo=pytz.UTC)],
+)
[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_updates_checkout_last_transaction_modified_at(
+ mocked_process,
+ mocked_fully_paid,
+ previous_last_transaction_modified_at,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+ transaction_item_generator,
+):
+ # given
+ checkout = checkout_with_prices
+ checkout.last_transaction_modified_at = previous_last_transaction_modified_at
+ checkout.save()
+ 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()
+
+ 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"]
+
+ checkout.refresh_from_db()
+ transaction = checkout.payment_transactions.first()
+ assert checkout.last_transaction_modified_at == transaction.modified_at
+ assert (
+ checkout.last_transaction_modified_at != previous_last_transaction_modified_at
+ )
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
index 80174875c6..67a551fe79 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
@@ -3,6 +3,7 @@ from unittest.mock import patch
import graphene
import pytest
+from freezegun import freeze_time
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
@@ -2788,3 +2789,56 @@ def test_transaction_update_by_app_assign_app_owner(
assert transaction.app_identifier == app_api_client.app.identifier
assert transaction.app == app_api_client.app
assert transaction.user is None
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_transaction_update_for_checkout_updates_last_transaction_modified_at(
+ checkout_with_items,
+ permission_manage_payments,
+ app_api_client,
+ transaction_item_generator,
+ app,
+):
+ # given
+ current_authorized_value = Decimal("1")
+ current_charged_value = Decimal("2")
+ transaction = transaction_item_generator(
+ checkout_id=checkout_with_items.pk,
+ app=app,
+ authorized_value=current_authorized_value,
+ charged_value=current_charged_value,
+ )
+ with freeze_time("2000-05-31 12:00:01"):
+ transaction.save(update_fields=["modified_at"])
+ previous_modified_at = transaction.modified_at
+ checkout_with_items.last_transaction_modified_at = previous_modified_at
+ checkout_with_items.save()
+
+ authorized_value = Decimal("12")
+ charged_value = Decimal("13")
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "amountCharged": {
+ "amount": charged_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+ transaction.refresh_from_db()
+
+ assert checkout_with_items.last_transaction_modified_at != previous_modified_at
+ assert checkout_with_items.last_transaction_modified_at == transaction.modified_at
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index 7ddcb84475..b56d07528a 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -30,6 +30,7 @@ from .utils import (
create_transaction,
gateway_postprocess,
get_already_processed_transaction_or_create_new_transaction,
+ recalculate_refundable_for_checkout,
update_payment,
validate_gateway_response,
)
@@ -233,6 +234,9 @@ def _request_payment_action(
apps_ids=[transaction_action_data.transaction_app_owner.pk],
)
if not transaction_request_event_active and not webhooks:
+ recalculate_refundable_for_checkout(
+ transaction_action_data.transaction, transaction_action_data.event
+ )
create_failed_transaction_event(
transaction_action_data.event,
cause="No app or plugin is configured to handle payment action requests.",
diff --git a/saleor/payment/migrations/0052_transactionitem_last_refund_success.py b/saleor/payment/migrations/0052_transactionitem_last_refund_success.py
new file mode 100644
index 0000000000..f8195fb56d
--- /dev/null
+++ b/saleor/payment/migrations/0052_transactionitem_last_refund_success.py
@@ -0,0 +1,24 @@
+# Generated by Django 3.2.22 on 2023-11-20 14:21
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0051_alter_transactionitem_available_actions"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="transactionitem",
+ name="last_refund_success",
+ field=models.BooleanField(default=True),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE payment_transactionitem ALTER COLUMN last_refund_success SET
+ DEFAULT True;
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/payment/migrations/0054_merge_20231122_0828.py b/saleor/payment/migrations/0054_merge_20231122_0828.py
new file mode 100644
index 0000000000..4bc57f5593
--- /dev/null
+++ b/saleor/payment/migrations/0054_merge_20231122_0828.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.22 on 2023-11-22 08:28
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0052_transactionitem_last_refund_success"),
+ ("payment", "0053_auto_20230601_0818"),
+ ]
+
+ operations = []
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 4e8d13a6e3..4d5e8a11c1 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -145,6 +145,10 @@ class TransactionItem(ModelWithMetadata):
)
app_identifier = models.CharField(blank=True, null=True, max_length=256)
+ # If last release funds action failed the flag will be set to False
+ # Used to define if the checkout with transaction is refundable or not
+ last_refund_success = models.BooleanField(default=True)
+
class Meta:
ordering = ("pk",)
indexes = [
diff --git a/saleor/payment/tasks.py b/saleor/payment/tasks.py
new file mode 100644
index 0000000000..6ab2f539e1
--- /dev/null
+++ b/saleor/payment/tasks.py
@@ -0,0 +1,148 @@
+import logging
+from datetime import datetime
+
+import pytz
+from django.conf import settings
+from django.db.models import OuterRef, Q, Subquery
+
+from ..celeryconf import app
+from ..channel.models import Channel
+from ..checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
+from ..checkout.models import Checkout
+from ..payment.models import TransactionEvent, TransactionItem
+from ..plugins.manager import get_plugins_manager
+from . import PaymentError, TransactionAction, TransactionEventType
+from .gateway import request_cancelation_action, request_refund_action
+
+logger = logging.getLogger(__name__)
+
+
+def checkouts_with_funds_to_release():
+ """Fetch checkouts that are ready release the funds.
+
+ Fetch checkouts with the funds where the last modification was more than defined
+ TTL ago. Exclude the checkouts with payment statuses which define that the
+ checkout doesn't have any processed funds.
+ """
+ expired_checkouts_time = (
+ datetime.now(pytz.UTC) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ )
+
+ return Checkout.objects.filter(
+ Q(
+ automatically_refundable=True,
+ last_change__lt=expired_checkouts_time,
+ last_transaction_modified_at__lt=expired_checkouts_time,
+ )
+ & (
+ ~Q(authorize_status=CheckoutAuthorizeStatus.NONE)
+ | ~Q(charge_status=CheckoutChargeStatus.NONE)
+ )
+ )
+
+
+def transaction_release_funds_for_checkout_task():
+ CHECKOUT_BATCH_SIZE = int(settings.CHECKOUT_BATCH_FOR_RELEASING_FUNDS)
+ TRANSACTION_BATCH_SIZE = int(settings.TRANSACTION_BATCH_FOR_RELEASING_FUNDS)
+
+ # Fetch checkouts that are ready to release funds
+ checkouts = checkouts_with_funds_to_release().order_by("last_change")
+ checkouts_data = checkouts.values_list("pk", "channel_id")[:CHECKOUT_BATCH_SIZE]
+ checkout_pks = [pk for pk, _ in checkouts_data]
+ checkout_channel_ids = [channel_id for _, channel_id in checkouts_data]
+ channel_map = Channel.objects.filter(id__in=checkout_channel_ids).in_bulk()
+ if checkout_pks:
+ transaction_events = TransactionEvent.objects.filter(
+ transaction_id=OuterRef("pk"),
+ ).order_by("-created_at")
+
+ checkout_subquery = Checkout.objects.filter(pk=OuterRef("checkout_id"))
+ # Fetch transactions for checkouts that are ready to release funds.
+ # Select_related app as, this will be used to trigger the proper webhook
+ # Annotate the last event for each transaction to exclude the transactions that
+ # were already processed
+ transactions = (
+ TransactionItem.objects.select_related("app")
+ .annotate(last_event_type=Subquery(transaction_events.values("type")[:1]))
+ .annotate(channel_id=Subquery(checkout_subquery.values("channel_id")[:1]))
+ .filter(
+ Q(checkout_id__in=checkout_pks, order_id=None)
+ & ~Q(
+ last_event_type__in=[
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.CANCEL_REQUEST,
+ ]
+ )
+ )[:TRANSACTION_BATCH_SIZE]
+ )
+ transactions_with_cancel_request_events = []
+ transactions_with_charge_request_events = []
+
+ for transaction in transactions:
+ # If transaction is authorized we need to trigger the cancel event
+ if transaction.authorized_value:
+ event = TransactionEvent(
+ amount_value=transaction.authorized_value,
+ currency=transaction.currency,
+ type=TransactionEventType.CANCEL_REQUEST,
+ transaction_id=transaction.id,
+ )
+ transactions_with_cancel_request_events.append((transaction, event))
+
+ # If transaction is charged we need to trigger the refund event
+ if transaction.charged_value:
+ event = TransactionEvent(
+ amount_value=transaction.charged_value,
+ currency=transaction.currency,
+ type=TransactionEventType.REFUND_REQUEST,
+ transaction_id=transaction.id,
+ )
+ transactions_with_charge_request_events.append((transaction, event))
+
+ if (
+ transactions_with_charge_request_events
+ or transactions_with_cancel_request_events
+ ):
+ TransactionEvent.objects.bulk_create(
+ [event for _tr, event in transactions_with_cancel_request_events]
+ + [event for _tr, event in transactions_with_charge_request_events]
+ )
+ manager = get_plugins_manager()
+ for transaction, event in transactions_with_cancel_request_events:
+ channel_slug = channel_map[transaction.channel_id].slug
+ try:
+ request_cancelation_action(
+ request_event=event,
+ cancel_value=event.amount_value,
+ action=TransactionAction.CANCEL,
+ channel_slug=channel_slug,
+ user=None,
+ app=None,
+ transaction=transaction,
+ manager=manager,
+ )
+ except PaymentError as e:
+ logger.warning(
+ "Unable to cancel transaction %s. %s",
+ transaction.token,
+ str(e),
+ )
+ for transaction, event in transactions_with_charge_request_events:
+ channel_slug = channel_map[transaction.channel_id].slug
+ try:
+ request_refund_action(
+ request_event=event,
+ refund_value=event.amount_value,
+ channel_slug=channel_slug,
+ user=None,
+ app=None,
+ transaction=transaction,
+ manager=manager,
+ )
+ except PaymentError as e:
+ logger.warning(
+ "Unable to refund transaction %s. %s",
+ transaction.token,
+ str(e),
+ )
diff --git a/saleor/payment/tests/test_gateway.py b/saleor/payment/tests/test_gateway.py
index 0d66293c8c..71b187bd52 100644
--- a/saleor/payment/tests/test_gateway.py
+++ b/saleor/payment/tests/test_gateway.py
@@ -637,6 +637,43 @@ def test_request_refund_action_missing_active_event(
)
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+def test_request_refund_action_updates_refundable_for_checkout(
+ mocked_is_active, staff_user, checkout, transaction_item_generator
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save()
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=Decimal(100)
+ )
+ action_value = Decimal("5.00")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.REFUND_REQUEST,
+ )
+ mocked_is_active.side_effect = [False, False]
+
+ # when
+ with pytest.raises(PaymentError):
+ request_refund_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ refund_value=action_value,
+ channel_slug=checkout.channel.slug,
+ user=staff_user,
+ app=None,
+ request_event=requested_event,
+ )
+
+ # then
+ transaction.refresh_from_db()
+ checkout.refresh_from_db()
+ assert checkout.automatically_refundable is False
+ assert transaction.last_refund_success is False
+
+
@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
def test_request_refund_action_on_order(
@@ -937,6 +974,44 @@ def test_request_cancelation_action_missing_active_event(
)
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+def test_request_cancel_action_updates_refundable_for_checkout(
+ mocked_is_active, checkout, staff_user, transaction_item_generator
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save()
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk, authorized_value=Decimal(100)
+ )
+ requested_event = transaction.events.create(
+ currency=transaction.currency,
+ type=TransactionEventType.CANCEL_REQUEST,
+ )
+
+ mocked_is_active.return_value = False
+
+ # when
+ with pytest.raises(PaymentError):
+ request_cancelation_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ cancel_value=None,
+ channel_slug=checkout.channel.slug,
+ user=staff_user,
+ app=None,
+ request_event=requested_event,
+ action=TransactionAction.CANCEL,
+ )
+
+ # then
+ transaction.refresh_from_db()
+ checkout.refresh_from_db()
+ assert checkout.automatically_refundable is False
+ assert transaction.last_refund_success is False
+
+
@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@patch("saleor.plugins.manager.PluginsManager.transaction_cancelation_requested")
def test_request_cancelation_action_on_order(
diff --git a/saleor/payment/tests/test_tasks.py b/saleor/payment/tests/test_tasks.py
new file mode 100644
index 0000000000..044d33c735
--- /dev/null
+++ b/saleor/payment/tests/test_tasks.py
@@ -0,0 +1,383 @@
+from datetime import datetime, timedelta
+from decimal import Decimal
+from unittest import mock
+
+import pytz
+from freezegun import freeze_time
+
+from ...checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
+from ...checkout.actions import transaction_amounts_for_checkout_updated
+from .. import TransactionAction, TransactionEventType
+from ..tasks import transaction_release_funds_for_checkout_task
+
+
[email protected]("saleor.payment.tasks.request_cancelation_action")
[email protected]("saleor.payment.tasks.request_refund_action")
+@freeze_time("2021-03-18 12:00:00")
+def test_transaction_release_funds_for_checkout_task_checkout_with_new_last_change(
+ mocked_refund_action,
+ mocked_cancel_action,
+ checkout,
+ settings,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ time_before_ttl = ttl_time + timedelta(seconds=1)
+ time_after_ttl = ttl_time - 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)
+
+ with freeze_time(time_before_ttl):
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable", "last_change"])
+
+ # when
+ transaction_release_funds_for_checkout_task()
+
+ # then
+ assert not mocked_refund_action.called
+ assert not mocked_cancel_action.called
+
+
[email protected]("saleor.payment.tasks.request_cancelation_action")
[email protected]("saleor.payment.tasks.request_refund_action")
+@freeze_time("2021-03-18 12:00:00")
+def test_transaction_release_funds_for_checkout_task_checkout_not_refundable(
+ mocked_refund_action,
+ mocked_cancel_action,
+ checkout,
+ settings,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ time_after_ttl = ttl_time - 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)
+ checkout.automatically_refundable = False
+ checkout.save(update_fields=["automatically_refundable", "last_change"])
+
+ # when
+ transaction_release_funds_for_checkout_task()
+
+ # then
+ assert not mocked_refund_action.called
+ assert not mocked_cancel_action.called
+
+
[email protected]("saleor.payment.tasks.request_cancelation_action")
[email protected]("saleor.payment.tasks.request_refund_action")
+@freeze_time("2021-03-18 12:00:00")
+def test_transaction_release_funds_for_checkout_task_checkout_with_new_tr_modified(
+ mocked_refund_action,
+ mocked_cancel_action,
+ checkout,
+ settings,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ time_before_ttl = ttl_time + timedelta(seconds=1)
+ time_after_ttl = ttl_time - timedelta(seconds=1)
+ with freeze_time(time_before_ttl):
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=Decimal(100),
+ )
+ transaction_amounts_for_checkout_updated(transaction_item, plugins_manager)
+
+ with freeze_time(time_after_ttl):
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable", "last_change"])
+
+ # when
+ transaction_release_funds_for_checkout_task()
+
+ # then
+ assert not mocked_refund_action.called
+ assert not mocked_cancel_action.called
+
+
[email protected]("saleor.payment.tasks.request_cancelation_action")
[email protected]("saleor.payment.tasks.request_refund_action")
+@freeze_time("2021-03-18 12:00:00")
+def test_transaction_release_funds_for_checkout_task_checkout_with_none_status(
+ mocked_refund_action,
+ mocked_cancel_action,
+ checkout,
+ settings,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ time_after_ttl = ttl_time - timedelta(seconds=1)
+ with freeze_time(time_after_ttl):
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=0,
+ )
+ transaction_amounts_for_checkout_updated(transaction_item, plugins_manager)
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable", "last_change"])
+
+ # when
+ transaction_release_funds_for_checkout_task()
+
+ # then
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.NONE
+ assert checkout.charge_status == CheckoutChargeStatus.NONE
+ assert not mocked_refund_action.called
+ assert not mocked_cancel_action.called
+
+
[email protected]("saleor.payment.tasks.request_cancelation_action")
[email protected]("saleor.payment.tasks.request_refund_action")
+@freeze_time("2021-03-18 12:00:00")
+def test_transaction_release_funds_for_checkout_task_not_valid_checkout(
+ mocked_refund_action,
+ mocked_cancel_action,
+ settings,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ time_after_ttl = ttl_time - timedelta(seconds=1)
+ with freeze_time(time_after_ttl):
+ transaction_item_generator(
+ charged_value=Decimal(100),
+ )
+
+ # when
+ transaction_release_funds_for_checkout_task()
+
+ # then
+ assert not mocked_refund_action.called
+ assert not mocked_cancel_action.called
+
+
[email protected]("saleor.payment.tasks.request_cancelation_action")
[email protected]("saleor.payment.tasks.request_refund_action")
+@freeze_time("2021-03-18 12:00:00")
+def test_transaction_release_funds_for_checkout_task_transaction_for_order(
+ mocked_refund_action,
+ mocked_cancel_action,
+ order,
+ settings,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ time_after_ttl = ttl_time - timedelta(seconds=1)
+ with freeze_time(time_after_ttl):
+ transaction_item_generator(
+ order_id=order.pk,
+ charged_value=Decimal(100),
+ )
+
+ # when
+ transaction_release_funds_for_checkout_task()
+
+ # then
+ assert not mocked_refund_action.called
+ assert not mocked_cancel_action.called
+
+
[email protected]("saleor.payment.tasks.request_cancelation_action")
[email protected]("saleor.payment.tasks.request_refund_action")
+@freeze_time("2021-03-18 12:00:00")
+def test_transaction_release_funds_for_checkout_task_without_transaction(
+ mocked_refund_action,
+ mocked_cancel_action,
+ checkout,
+ settings,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ time_after_ttl = ttl_time - timedelta(seconds=1)
+ with freeze_time(time_after_ttl):
+ checkout.authorize_status = CheckoutAuthorizeStatus.FULL
+ checkout.charge_status = CheckoutChargeStatus.FULL
+ checkout.automatically_refundable = True
+ checkout.save(
+ update_fields=[
+ "automatically_refundable",
+ "last_change",
+ "authorize_status",
+ "charge_status",
+ ]
+ )
+
+ # when
+ transaction_release_funds_for_checkout_task()
+
+ # then
+ assert not mocked_refund_action.called
+ assert not mocked_cancel_action.called
+
+
[email protected]("saleor.payment.tasks.request_cancelation_action")
[email protected]("saleor.payment.tasks.request_refund_action")
+@freeze_time("2021-03-18 12:00:00")
+def test_transaction_release_funds_for_checkout_task_refund_already_requested(
+ mocked_refund_action,
+ mocked_cancel_action,
+ checkout,
+ settings,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ time_after_ttl = ttl_time - 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)
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable", "last_change"])
+ transaction_item.events.create(type=TransactionEventType.REFUND_REQUEST)
+
+ # when
+ transaction_release_funds_for_checkout_task()
+
+ # then
+ assert not mocked_refund_action.called
+ assert not mocked_cancel_action.called
+
+
[email protected]("saleor.payment.tasks.request_cancelation_action")
[email protected]("saleor.payment.tasks.request_refund_action")
+@freeze_time("2021-03-18 12:00:00")
+def test_transaction_release_funds_for_checkout_task_cancel_already_requested(
+ mocked_refund_action,
+ mocked_cancel_action,
+ checkout,
+ settings,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ time_after_ttl = ttl_time - timedelta(seconds=1)
+ with freeze_time(time_after_ttl):
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk,
+ authorized_value=Decimal(100),
+ )
+ transaction_amounts_for_checkout_updated(transaction_item, plugins_manager)
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable", "last_change"])
+ transaction_item.events.create(type=TransactionEventType.CANCEL_REQUEST)
+
+ # when
+ transaction_release_funds_for_checkout_task()
+
+ # then
+ assert not mocked_refund_action.called
+ assert not mocked_cancel_action.called
+
+
[email protected]("saleor.payment.tasks.request_cancelation_action")
[email protected]("saleor.payment.tasks.request_refund_action")
+@freeze_time("2021-03-18 12:00:00")
+def test_transaction_release_funds_for_checkout_task_transaction_with_authorization(
+ mocked_refund_action,
+ mocked_cancel_action,
+ checkout,
+ settings,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ time_after_ttl = ttl_time - timedelta(seconds=1)
+ with freeze_time(time_after_ttl):
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk,
+ authorized_value=Decimal(100),
+ )
+ transaction_amounts_for_checkout_updated(transaction_item, plugins_manager)
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable", "last_change"])
+
+ # when
+ transaction_release_funds_for_checkout_task()
+
+ # then
+ request_event = transaction_item.events.filter(
+ type=TransactionEventType.CANCEL_REQUEST
+ ).first()
+ assert request_event
+ assert not mocked_refund_action.called
+ mocked_cancel_action.assert_called_once_with(
+ channel_slug=checkout.channel.slug,
+ user=None,
+ app=None,
+ transaction=transaction_item,
+ manager=mock.ANY,
+ request_event=request_event,
+ cancel_value=transaction_item.authorized_value,
+ action=TransactionAction.CANCEL,
+ )
+
+
[email protected]("saleor.payment.tasks.request_cancelation_action")
[email protected]("saleor.payment.tasks.request_refund_action")
+@freeze_time("2021-03-18 12:00:00")
+def test_transaction_release_funds_for_checkout_task_transaction_with_charge(
+ mocked_refund_action,
+ mocked_cancel_action,
+ checkout,
+ settings,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ time_after_ttl = ttl_time - 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)
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable", "last_change"])
+
+ # when
+ transaction_release_funds_for_checkout_task()
+
+ # then
+ request_event = transaction_item.events.filter(
+ type=TransactionEventType.REFUND_REQUEST
+ ).first()
+ assert request_event
+ assert not mocked_cancel_action.called
+ mocked_refund_action.assert_called_once_with(
+ channel_slug=checkout.channel.slug,
+ user=None,
+ app=None,
+ transaction=transaction_item,
+ manager=mock.ANY,
+ request_event=request_event,
+ refund_value=transaction_item.charged_value,
+ )
diff --git a/saleor/payment/tests/test_transaction_item_calculations.py b/saleor/payment/tests/test_transaction_item_calculations.py
index f9ccf1beba..906d71b3d0 100644
--- a/saleor/payment/tests/test_transaction_item_calculations.py
+++ b/saleor/payment/tests/test_transaction_item_calculations.py
@@ -1,7 +1,10 @@
+import datetime
from datetime import timedelta
from decimal import Decimal
+import pytz
from django.utils import timezone
+from freezegun import freeze_time
from .. import TransactionEventType
from ..models import TransactionItem
@@ -1604,3 +1607,32 @@ def test_skips_event_that_should_not_be_taken_into_account(
_assert_amounts(
transaction, authorized_value=first_value, authorize_pending_value=second_value
)
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_recalculate_transaction_amounts_updates_transaction_modified_at(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ authorized_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ ],
+ amounts=[
+ authorized_value,
+ ],
+ )
+ # when
+ with freeze_time("2023-03-18 12:00:00"):
+ calculation_time = datetime.datetime.now(pytz.UTC)
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ assert transaction.modified_at == calculation_time
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index 2464e696f2..3e741fe43c 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -28,6 +28,7 @@ from ..utils import (
get_channel_slug_from_payment,
get_correct_event_types_based_on_request_type,
parse_transaction_action_data,
+ recalculate_refundable_for_checkout,
try_void_or_refund_inactive_payment,
)
@@ -1092,6 +1093,216 @@ def test_create_transaction_event_from_request_and_webhook_response_different_am
assert failed_event.type == TransactionEventType.AUTHORIZATION_FAILURE
+@freeze_time("2018-05-31 12:00:01")
+def test_create_event_from_request_and_webhook_missing_response_calculate_refundable(
+ transaction_item_generator,
+ checkout,
+ app,
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save()
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=Decimal(100)
+ )
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ response_data = None
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ checkout.refresh_from_db()
+ transaction.refresh_from_db()
+ assert transaction.last_refund_success is False
+ assert checkout.automatically_refundable is False
+
+
+def test_create_event_from_request_and_webhook_error_response_calculate_refundable(
+ transaction_item_generator,
+ checkout,
+ app,
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save()
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=Decimal(100)
+ )
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = 12.00
+ event_type = TransactionEventType.CHARGE_FAILURE
+ event_time = "2022-11-18T13:25:58.169685+00:00"
+ event_url = "http://localhost:3000/event/ref123"
+ event_cause = "No cause"
+
+ response_data = {
+ # missing pspReference
+ "amount": event_amount,
+ "result": event_type.upper(),
+ "time": event_time,
+ "externalUrl": event_url,
+ "message": event_cause,
+ "actions": ["CHARGE", "CHARGE", "CANCEL"],
+ }
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ checkout.refresh_from_db()
+ transaction.refresh_from_db()
+ assert transaction.last_refund_success is False
+ assert checkout.automatically_refundable is False
+
+
+def test_create_event_from_request_and_webhook_failure_event_calculate_refundable(
+ transaction_item_generator,
+ checkout,
+ app,
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save()
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=Decimal(100)
+ )
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = 11.00
+ event_type = TransactionEventType.REFUND_FAILURE
+ event_time = "2022-11-18T13:25:58.169685+00:00"
+ event_url = "http://localhost:3000/event/ref123"
+ event_cause = "No cause"
+
+ response_data = {
+ "pspReference": "123",
+ "amount": event_amount,
+ "result": event_type.upper(),
+ "time": event_time,
+ "externalUrl": event_url,
+ "message": event_cause,
+ "actions": ["CHARGE", "CHARGE", "CANCEL"],
+ }
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ checkout.refresh_from_db()
+ transaction.refresh_from_db()
+ assert transaction.last_refund_success is False
+ assert checkout.automatically_refundable is False
+
+
+def test_create_event_from_request_and_webhook_success_event_calculate_refundable(
+ transaction_item_generator,
+ checkout,
+ app,
+):
+ # given
+ checkout.automatically_refundable = False
+ checkout.save()
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=Decimal(100)
+ )
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = 12.00
+ event_type = TransactionEventType.REFUND_SUCCESS
+ event_time = "2022-11-18T13:25:58.169685+00:00"
+ event_url = "http://localhost:3000/event/ref123"
+ event_cause = "No cause"
+
+ response_data = {
+ "pspReference": "123",
+ "amount": event_amount,
+ "result": event_type.upper(),
+ "time": event_time,
+ "externalUrl": event_url,
+ "message": event_cause,
+ "actions": ["CHARGE", "CHARGE", "CANCEL"],
+ }
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ checkout.refresh_from_db()
+ transaction.refresh_from_db()
+ assert transaction.last_refund_success is True
+ assert checkout.automatically_refundable is True
+
+
+def test_create_event_from_request_and_webhook_pending_event_calculate_refundable(
+ transaction_item_generator,
+ checkout,
+ app,
+):
+ # given
+ checkout.automatically_refundable = False
+ checkout.save()
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=Decimal(100)
+ )
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ response_data = {
+ "pspReference": "123",
+ }
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ checkout.refresh_from_db()
+ transaction.refresh_from_db()
+ assert transaction.last_refund_success is True
+ assert checkout.automatically_refundable is True
+
+
@pytest.mark.parametrize(
("db_field_name", "value", "event_type"),
[
@@ -1632,3 +1843,413 @@ def test_create_transaction_event_for_transaction_session_failure_doesnt_set_act
# then
transaction.refresh_from_db()
assert transaction.available_actions == ["charge"]
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_create_transaction_event_from_request_and_webhook_updates_modified_at(
+ transaction_item_generator,
+ checkout,
+ app,
+):
+ # given
+ transaction = transaction_item_generator(checkout_id=checkout.pk)
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = 12.00
+ event_type = TransactionEventType.CHARGE_FAILURE
+ event_time = "2022-11-18T13:25:58.169685+00:00"
+ event_url = "http://localhost:3000/event/ref123"
+ event_cause = "No cause"
+
+ expected_psp_reference = "psp:122:222"
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ "time": event_time,
+ "externalUrl": event_url,
+ "message": event_cause,
+ "actions": ["CHARGE", "CHARGE", "CANCEL"],
+ }
+
+ # when
+ with freeze_time("2023-03-18 12:00:00"):
+ calculation_time = datetime.now(pytz.UTC)
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ transaction.refresh_from_db()
+ checkout.refresh_from_db()
+ assert transaction.modified_at == calculation_time
+ assert checkout.last_transaction_modified_at == calculation_time
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_create_transaction_event_updates_transaction_modified_at(
+ transaction_item_generator,
+ transaction_session_response,
+ webhook_app,
+ plugins_manager,
+ checkout,
+):
+ # given
+ expected_amount = Decimal("15")
+ response = transaction_session_response.copy()
+ response["amount"] = expected_amount
+
+ transaction = transaction_item_generator(checkout_id=checkout.pk)
+ request_event = TransactionEvent.objects.create(
+ transaction=transaction, include_in_calculations=False
+ )
+
+ # when
+ with freeze_time("2023-03-18 12:00:00"):
+ calculation_time = datetime.now(pytz.UTC)
+ create_transaction_event_for_transaction_session(
+ request_event,
+ webhook_app,
+ manager=plugins_manager,
+ transaction_webhook_response=response,
+ )
+
+ # then
+ transaction.refresh_from_db()
+ checkout.refresh_from_db()
+ assert transaction.modified_at == calculation_time
+ assert checkout.last_transaction_modified_at == calculation_time
+
+
+def test_recalculate_refundable_for_checkout_with_request_refund(
+ transaction_item_generator, checkout
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable"])
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk, last_refund_success=True, charged_value=Decimal(10)
+ )
+ request_event = transaction_item.events.create(
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=Decimal(10),
+ include_in_calculations=False,
+ )
+
+ # when
+ recalculate_refundable_for_checkout(transaction_item, request_event)
+
+ # then
+ checkout.refresh_from_db()
+ transaction_item.refresh_from_db()
+ assert transaction_item.last_refund_success is False
+ assert checkout.automatically_refundable is False
+
+
+def test_recalculate_refundable_for_checkout_with_request_cancel(
+ transaction_item_generator, checkout
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable"])
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk, last_refund_success=True, charged_value=Decimal(10)
+ )
+ request_event = transaction_item.events.create(
+ type=TransactionEventType.CANCEL_REQUEST,
+ amount_value=Decimal(10),
+ include_in_calculations=False,
+ )
+
+ # when
+ recalculate_refundable_for_checkout(transaction_item, request_event)
+
+ # then
+ checkout.refresh_from_db()
+ transaction_item.refresh_from_db()
+ assert transaction_item.last_refund_success is False
+ assert checkout.automatically_refundable is False
+
+
+ "event_type",
+ [
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.CHARGE_REQUEST,
+ ],
+)
+def test_recalculate_refundable_for_checkout_with_non_related_request_event(
+ event_type, transaction_item_generator, checkout
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable"])
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk, last_refund_success=True, charged_value=Decimal(10)
+ )
+ request_event = transaction_item.events.create(
+ type=event_type,
+ amount_value=Decimal(10),
+ include_in_calculations=False,
+ )
+
+ # when
+ recalculate_refundable_for_checkout(transaction_item, request_event)
+
+ # then
+ checkout.refresh_from_db()
+ transaction_item.refresh_from_db()
+ assert transaction_item.last_refund_success is True
+ assert checkout.automatically_refundable is True
+
+
+ "event_type",
+ [
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.CHARGE_FAILURE,
+ ],
+)
+def test_recalculate_refundable_for_checkout_with_non_related_events(
+ event_type, transaction_item_generator, checkout
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable"])
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk, last_refund_success=True, charged_value=Decimal(10)
+ )
+ request_event = transaction_item.events.create(
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=Decimal(10),
+ include_in_calculations=False,
+ psp_reference="123",
+ )
+ response_event = transaction_item.events.create(
+ type=event_type, amount_value=Decimal(10), psp_reference="123"
+ )
+
+ # when
+ recalculate_refundable_for_checkout(transaction_item, request_event, response_event)
+
+ # then
+ checkout.refresh_from_db()
+ transaction_item.refresh_from_db()
+ assert transaction_item.last_refund_success is True
+ assert checkout.automatically_refundable is True
+
+
+def test_recalculate_refundable_for_checkout_with_response_refund_success(
+ transaction_item_generator, checkout
+):
+ # given
+ checkout.automatically_refundable = False
+ checkout.save(update_fields=["automatically_refundable"])
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk, last_refund_success=False, charged_value=Decimal(10)
+ )
+ request_event = transaction_item.events.create(
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=Decimal(10),
+ include_in_calculations=False,
+ psp_reference="123",
+ )
+ response_event = transaction_item.events.create(
+ type=TransactionEventType.REFUND_SUCCESS,
+ amount_value=Decimal(10),
+ psp_reference="123",
+ )
+
+ # when
+ recalculate_refundable_for_checkout(transaction_item, request_event, response_event)
+
+ # then
+ checkout.refresh_from_db()
+ transaction_item.refresh_from_db()
+ assert transaction_item.last_refund_success is True
+ assert checkout.automatically_refundable is True
+
+
+def test_recalculate_refundable_for_checkout_with_response_refund_failure(
+ transaction_item_generator, checkout
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable"])
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk, last_refund_success=True, charged_value=Decimal(10)
+ )
+ request_event = transaction_item.events.create(
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=Decimal(10),
+ include_in_calculations=False,
+ psp_reference="123",
+ )
+ response_event = transaction_item.events.create(
+ type=TransactionEventType.REFUND_FAILURE,
+ amount_value=Decimal(10),
+ psp_reference="123",
+ )
+
+ # when
+ recalculate_refundable_for_checkout(transaction_item, request_event, response_event)
+
+ # then
+ checkout.refresh_from_db()
+ transaction_item.refresh_from_db()
+ assert transaction_item.last_refund_success is False
+ assert checkout.automatically_refundable is False
+
+
+def test_recalculate_refundable_for_checkout_with_response_refund_pending(
+ transaction_item_generator, checkout
+):
+ # given
+ checkout.automatically_refundable = False
+ checkout.save(update_fields=["automatically_refundable"])
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk, last_refund_success=False, charged_value=Decimal(10)
+ )
+ request_event = transaction_item.events.create(
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=Decimal(10),
+ include_in_calculations=True,
+ psp_reference="123",
+ )
+
+ # when
+ recalculate_refundable_for_checkout(transaction_item, request_event)
+
+ # then
+ checkout.refresh_from_db()
+ transaction_item.refresh_from_db()
+ assert transaction_item.last_refund_success is True
+ assert checkout.automatically_refundable is True
+
+
+def test_recalculate_refundable_for_checkout_with_response_cancel_failure(
+ transaction_item_generator, checkout
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save(update_fields=["automatically_refundable"])
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk, last_refund_success=True, charged_value=Decimal(10)
+ )
+ request_event = transaction_item.events.create(
+ type=TransactionEventType.CANCEL_REQUEST,
+ amount_value=Decimal(10),
+ include_in_calculations=False,
+ psp_reference="123",
+ )
+ response_event = transaction_item.events.create(
+ type=TransactionEventType.CANCEL_FAILURE,
+ amount_value=Decimal(10),
+ psp_reference="123",
+ )
+
+ # when
+ recalculate_refundable_for_checkout(transaction_item, request_event, response_event)
+
+ # then
+ checkout.refresh_from_db()
+ transaction_item.refresh_from_db()
+ assert transaction_item.last_refund_success is False
+ assert checkout.automatically_refundable is False
+
+
+def test_recalculate_refundable_for_checkout_with_response_cancel_success(
+ transaction_item_generator, checkout
+):
+ # given
+ checkout.automatically_refundable = False
+ checkout.save(update_fields=["automatically_refundable"])
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk, last_refund_success=False, charged_value=Decimal(10)
+ )
+ request_event = transaction_item.events.create(
+ type=TransactionEventType.CANCEL_REQUEST,
+ amount_value=Decimal(10),
+ include_in_calculations=False,
+ psp_reference="123",
+ )
+ response_event = transaction_item.events.create(
+ type=TransactionEventType.CANCEL_SUCCESS,
+ amount_value=Decimal(10),
+ psp_reference="123",
+ )
+
+ # when
+ recalculate_refundable_for_checkout(transaction_item, request_event, response_event)
+
+ # then
+ checkout.refresh_from_db()
+ transaction_item.refresh_from_db()
+ assert transaction_item.last_refund_success is True
+ assert checkout.automatically_refundable is True
+
+
+def test_recalculate_refundable_for_checkout_with_response_cancel_pending(
+ transaction_item_generator, checkout
+):
+ # given
+ checkout.automatically_refundable = False
+ checkout.save(update_fields=["automatically_refundable"])
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk, last_refund_success=False, charged_value=Decimal(10)
+ )
+ request_event = transaction_item.events.create(
+ type=TransactionEventType.CANCEL_REQUEST,
+ amount_value=Decimal(10),
+ include_in_calculations=True,
+ psp_reference="123",
+ )
+
+ # when
+ recalculate_refundable_for_checkout(transaction_item, request_event)
+
+ # then
+ checkout.refresh_from_db()
+ transaction_item.refresh_from_db()
+ assert transaction_item.last_refund_success is True
+ assert checkout.automatically_refundable is True
+
+
+def test_recalculate_refundable_for_checkout_update_missing_checkout(
+ transaction_item_generator,
+):
+ # given
+ transaction_item = transaction_item_generator(
+ last_refund_success=True, charged_value=Decimal(10)
+ )
+ request_event = transaction_item.events.create(
+ type=TransactionEventType.CANCEL_REQUEST,
+ amount_value=Decimal(10),
+ include_in_calculations=False,
+ psp_reference="123",
+ )
+
+ # when
+ recalculate_refundable_for_checkout(transaction_item, request_event)
+
+ # then
+ transaction_item.refresh_from_db()
+ assert transaction_item.last_refund_success is False
diff --git a/saleor/payment/transaction_item_calculations.py b/saleor/payment/transaction_item_calculations.py
index 8b9d7e1d3b..d074fb8ecb 100644
--- a/saleor/payment/transaction_item_calculations.py
+++ b/saleor/payment/transaction_item_calculations.py
@@ -395,5 +395,6 @@ def recalculate_transaction_amounts(transaction: TransactionItem, save: bool = T
"charge_pending_value",
"refund_pending_value",
"cancel_pending_value",
+ "modified_at",
]
)
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 8920e5c6b8..6ce40814bf 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -20,6 +20,7 @@ from ..channel import TransactionFlowStrategy
from ..checkout.actions import transaction_amounts_for_checkout_updated
from ..checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ..checkout.models import Checkout
+from ..checkout.payment_utils import update_refundable_for_checkout
from ..core.prices import quantize_price
from ..core.tracing import traced_atomic_transaction
from ..graphql.core.utils import str_to_enum
@@ -63,6 +64,68 @@ GENERIC_TRANSACTION_ERROR = "Transaction was unsuccessful"
ALLOWED_GATEWAY_KINDS = {choices[0] for choices in TransactionKind.CHOICES}
+def _recalculate_last_refund_success_for_transaction(
+ transaction_item: TransactionItem,
+ request_event: TransactionEvent,
+ response_event: Optional[TransactionEvent] = None,
+) -> bool:
+ """Recalculate last_refund_success for transaction.
+
+ Based on the request and response events, we can determine if the last refund was
+ successful or not.
+ If response event is none, the request event can store the details updated based
+ on the response from the gateway (in case of async flow).
+ If the request event doesn't have these details, we can assume that the last
+ refund failed.
+ As a response we return the boolean flag which determines if the transaction's last
+ refund success was changed.
+ """
+ last_refund_success_changed = False
+ last_refund_success = transaction_item.last_refund_success
+ if response_event:
+ if response_event.type in [
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.CANCEL_SUCCESS,
+ ]:
+ last_refund_success_changed = last_refund_success is not True
+ transaction_item.last_refund_success = True
+
+ if response_event.type in [
+ TransactionEventType.REFUND_FAILURE,
+ TransactionEventType.CANCEL_FAILURE,
+ ]:
+ last_refund_success_changed = last_refund_success is not False
+ transaction_item.last_refund_success = False
+ elif request_event.type in [
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.CANCEL_REQUEST,
+ ]:
+ if request_event.include_in_calculations:
+ last_refund_success_changed = last_refund_success is not True
+ transaction_item.last_refund_success = True
+ else:
+ last_refund_success_changed = last_refund_success is not False
+ transaction_item.last_refund_success = False
+ return last_refund_success_changed
+
+
+def recalculate_refundable_for_checkout(
+ transaction_item: TransactionItem,
+ request_event: TransactionEvent,
+ response_event: Optional[TransactionEvent] = None,
+):
+ last_refund_success_changed = _recalculate_last_refund_success_for_transaction(
+ transaction_item,
+ request_event,
+ response_event,
+ )
+ if last_refund_success_changed:
+ transaction_item.save(update_fields=["last_refund_success"])
+
+ if transaction_item.checkout_id:
+ update_refundable_for_checkout(transaction_item.checkout_id)
+
+
def create_payment_lines_information(
payment: Payment,
manager: PluginsManager,
@@ -1194,6 +1257,7 @@ def create_transaction_event_for_transaction_session(
"cancel_pending_value",
"psp_reference",
"available_actions",
+ "modified_at",
]
)
if transaction_item.order_id:
@@ -1227,7 +1291,9 @@ def create_transaction_event_from_request_and_webhook_response(
transaction_webhook_response=transaction_webhook_response,
event_type=request_event.type,
)
+ transaction_item = request_event.transaction
if not transaction_request_response:
+ recalculate_refundable_for_checkout(transaction_item, request_event)
return create_failed_transaction_event(request_event, cause=error_msg or "")
psp_reference = transaction_request_response.psp_reference
@@ -1243,6 +1309,7 @@ def create_transaction_event_from_request_and_webhook_response(
currency=request_event.currency,
)
if error_msg:
+ recalculate_refundable_for_checkout(transaction_item, request_event)
return create_failed_transaction_event(request_event, cause=error_msg)
transaction_item = request_event.transaction
@@ -1265,6 +1332,7 @@ def create_transaction_event_from_request_and_webhook_response(
"charge_pending_value",
"refund_pending_value",
"cancel_pending_value",
+ "modified_at",
]
)
@@ -1288,6 +1356,7 @@ def create_transaction_event_from_request_and_webhook_response(
)
elif transaction_item.checkout_id:
manager = get_plugins_manager()
+ recalculate_refundable_for_checkout(transaction_item, request_event, event)
transaction_amounts_for_checkout_updated(transaction_item, manager)
return event
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 6ed347eabd..cd2678c8af 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -49,6 +49,10 @@ from ...payment.interface import (
TransactionSessionResult,
)
from ...payment.models import Payment, TransactionItem
+from ...payment.utils import (
+ create_failed_transaction_event,
+ recalculate_refundable_for_checkout,
+)
from ...settings import WEBHOOK_SYNC_TIMEOUT
from ...thumbnail.models import Thumbnail
from ...webhook.const import CACHE_EXCLUDED_SHIPPING_KEY, WEBHOOK_CACHE_DEFAULT_TIMEOUT
@@ -2468,6 +2472,13 @@ class WebhookPlugin(BasePlugin):
return previous_value
if not transaction_data.transaction_app_owner:
+ create_failed_transaction_event(
+ transaction_data.event,
+ cause="Transaction request skipped. Missing relation to PaymentApp.",
+ )
+ recalculate_refundable_for_checkout(
+ transaction_data.transaction, transaction_data.event
+ )
logger.warning(
f"Transaction request skipped for "
f"{transaction_data.transaction.psp_reference}. "
diff --git a/saleor/plugins/webhook/tests/test_tasks.py b/saleor/plugins/webhook/tests/test_tasks.py
index dba911065d..ff78d73364 100644
--- a/saleor/plugins/webhook/tests/test_tasks.py
+++ b/saleor/plugins/webhook/tests/test_tasks.py
@@ -169,6 +169,252 @@ def test_trigger_transaction_request_with_webhook_subscription(
mocked_task.assert_called_once_with(generated_delivery.id, event.id)
+@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.handle_transaction_request_task.delay")
+def test_trigger_transaction_request_missing_app_owner_updates_refundable_checkout(
+ mocked_task,
+ transaction_item_created_by_app,
+ staff_user,
+ permission_manage_payments,
+ app,
+ checkout,
+):
+ # given
+ subscription = """
+ subscription{
+ event{
+ ...on TransactionRefundRequested{
+ transaction{
+ id
+ }
+ action{
+ amount
+ actionType
+ }
+ }
+ }
+ }
+ """
+ checkout.automatically_refundable = True
+ checkout.save()
+
+ transaction_item_created_by_app.order = None
+ transaction_item_created_by_app.checkout = checkout
+ transaction_item_created_by_app.save()
+ event = transaction_item_created_by_app.events.create(
+ type=TransactionEventType.REFUND_REQUEST
+ )
+
+ app.permissions.set([permission_manage_payments])
+
+ webhook = app.webhooks.create(
+ name="webhook",
+ is_active=True,
+ target_url="http://localhost:3000/",
+ subscription_query=subscription,
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED)
+
+ transaction_data = TransactionActionData(
+ transaction=transaction_item_created_by_app,
+ action_type="refund",
+ action_value=Decimal("10.00"),
+ event=event,
+ transaction_app_owner=None,
+ )
+
+ # when
+ trigger_transaction_request(
+ transaction_data, WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED, staff_user
+ )
+
+ # then
+ checkout.refresh_from_db()
+ transaction_item_created_by_app.refresh_from_db()
+ assert checkout.automatically_refundable is False
+ assert transaction_item_created_by_app.last_refund_success is False
+ assert not mocked_task.called
+
+
+@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.handle_transaction_request_task.delay")
+def test_trigger_transaction_request_missing_webhook_updates_refundable_checkout(
+ mocked_task,
+ transaction_item_created_by_app,
+ staff_user,
+ permission_manage_payments,
+ app,
+ checkout,
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save()
+
+ transaction_item_created_by_app.order = None
+ transaction_item_created_by_app.checkout = checkout
+ transaction_item_created_by_app.save()
+ event = transaction_item_created_by_app.events.create(
+ type=TransactionEventType.REFUND_REQUEST
+ )
+
+ app.permissions.set([permission_manage_payments])
+
+ transaction_data = TransactionActionData(
+ transaction=transaction_item_created_by_app,
+ action_type="refund",
+ action_value=Decimal("10.00"),
+ event=event,
+ transaction_app_owner=app,
+ )
+
+ # when
+ trigger_transaction_request(
+ transaction_data, WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED, staff_user
+ )
+
+ # then
+ checkout.refresh_from_db()
+ transaction_item_created_by_app.refresh_from_db()
+ assert checkout.automatically_refundable is False
+ assert transaction_item_created_by_app.last_refund_success is False
+ assert not mocked_task.called
+
+
+@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.handle_transaction_request_task.delay")
+def test_trigger_transaction_request_incorrect_subscription_updates_refundable_checkout(
+ mocked_task,
+ transaction_item_created_by_app,
+ staff_user,
+ permission_manage_payments,
+ app,
+ checkout,
+):
+ # given
+ subscription = """
+ subscription{
+ event{
+ ...on TransactionRefundRequested{
+ transaction{
+ id
+ incorrectField
+ }
+ action{
+ amount
+ actionType
+ }
+ }
+ }
+ }
+ """
+ checkout.automatically_refundable = True
+ checkout.save()
+
+ transaction_item_created_by_app.order = None
+ transaction_item_created_by_app.checkout = checkout
+ transaction_item_created_by_app.save()
+ event = transaction_item_created_by_app.events.create(
+ type=TransactionEventType.REFUND_REQUEST
+ )
+
+ app.permissions.set([permission_manage_payments])
+
+ webhook = app.webhooks.create(
+ name="webhook",
+ is_active=True,
+ target_url="http://localhost:3000/",
+ subscription_query=subscription,
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED)
+
+ transaction_data = TransactionActionData(
+ transaction=transaction_item_created_by_app,
+ action_type="refund",
+ action_value=Decimal("10.00"),
+ event=event,
+ transaction_app_owner=app,
+ )
+
+ # when
+ trigger_transaction_request(
+ transaction_data, WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED, staff_user
+ )
+
+ # then
+ checkout.refresh_from_db()
+ transaction_item_created_by_app.refresh_from_db()
+ assert checkout.automatically_refundable is False
+ assert transaction_item_created_by_app.last_refund_success is False
+ assert not mocked_task.called
+
+
+@freeze_time("2022-06-11 12:50")
[email protected](HTTPSession, "request")
+def test_handle_transaction_request_task_missing_delivery_updates_refundable_checkout(
+ mocked_post_request,
+ transaction_item_generator,
+ permission_manage_payments,
+ staff_user,
+ mocked_webhook_response,
+ app,
+ checkout,
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save()
+
+ transaction = transaction_item_generator(checkout_id=checkout.pk)
+ expected_psp_reference = "psp:ref:123"
+ mocked_webhook_response.text = json.dumps({"pspReference": expected_psp_reference})
+ mocked_webhook_response.content = json.dumps(
+ {"pspReference": expected_psp_reference}
+ )
+ mocked_post_request.return_value = mocked_webhook_response
+
+ target_url = "http://localhost:3000/"
+
+ event = transaction.events.create(type=TransactionEventType.REFUND_REQUEST)
+ app.permissions.set([permission_manage_payments])
+
+ webhook = app.webhooks.create(
+ name="webhook",
+ is_active=True,
+ target_url=target_url,
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED)
+
+ transaction_data = TransactionActionData(
+ transaction=transaction,
+ action_type="refund",
+ action_value=Decimal("10.00"),
+ event=event,
+ transaction_app_owner=app,
+ )
+
+ payload = generate_transaction_action_request_payload(transaction_data, staff_user)
+ event_payload = EventPayload.objects.create(payload=payload)
+ delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED,
+ payload=event_payload,
+ webhook=webhook,
+ )
+ delivery_id = delivery.id
+
+ delivery.delete()
+
+ # when
+ handle_transaction_request_task(delivery_id, transaction_data.event.id)
+
+ # then
+ checkout.refresh_from_db()
+ transaction.refresh_from_db()
+
+ assert checkout.automatically_refundable is False
+ assert transaction.last_refund_success is False
+ assert not mocked_post_request.called
+
+
@freeze_time("2022-06-11 12:50")
@mock.patch.object(HTTPSession, "request")
def test_handle_transaction_request_task_with_only_psp_reference(
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index 839920cba0..1b2c4a53b9 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -1966,6 +1966,112 @@ def test_transaction_refund_requested(
)
+@freeze_time("1914-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_transaction_request")
+def test_transaction_refund_requested_missing_app_owner_updated_refundable_for_checkout(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ settings,
+ checkout,
+ channel_USD,
+ app,
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save()
+ any_webhook.app = app
+ any_webhook.save()
+
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+ transaction = TransactionItem.objects.create(
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=[
+ "refund",
+ ],
+ currency="USD",
+ checkout_id=checkout.pk,
+ authorized_value=Decimal("10"),
+ app_identifier=app.identifier,
+ app=app,
+ )
+ event = transaction.events.create(type=TransactionEventType.REFUND_REQUEST)
+ action_value = Decimal("5.00")
+ transaction_action_data = TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.REFUND,
+ action_value=action_value,
+ event=event,
+ transaction_app_owner=None,
+ )
+
+ # when
+ manager.transaction_refund_requested(
+ transaction_action_data, channel_slug=channel_USD.slug
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.automatically_refundable is False
+
+
+@freeze_time("1914-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_transaction_request")
+def test_transaction_cancel_requested_missing_app_owner_updated_refundable_for_checkout(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ settings,
+ checkout,
+ channel_USD,
+ app,
+):
+ # given
+ checkout.automatically_refundable = True
+ checkout.save()
+ any_webhook.app = app
+ any_webhook.save()
+
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+ transaction = TransactionItem.objects.create(
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=[
+ "refund",
+ ],
+ currency="USD",
+ checkout_id=checkout.pk,
+ authorized_value=Decimal("10"),
+ app_identifier=app.identifier,
+ app=app,
+ )
+ event = transaction.events.create(type=TransactionEventType.CANCEL_REQUEST)
+ action_value = Decimal("5.00")
+ transaction_action_data = TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CANCEL,
+ action_value=action_value,
+ event=event,
+ transaction_app_owner=None,
+ )
+
+ # when
+ manager.transaction_refund_requested(
+ transaction_action_data, channel_slug=channel_USD.slug
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.automatically_refundable is False
+
+
@freeze_time("1914-06-28 10:50")
@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
@mock.patch("saleor.plugins.webhook.plugin.trigger_transaction_request")
diff --git a/saleor/settings.py b/saleor/settings.py
index ad40d07efe..80cd7739d4 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -623,6 +623,10 @@ CELERY_BEAT_SCHEDULE = {
"task": "saleor.app.tasks.remove_apps_task",
"schedule": crontab(hour=3, minute=0),
},
+ "release-funds-for-abandoned-checkouts": {
+ "task": "saleor.payment.tasks.transaction_release_funds_for_checkout_task",
+ "schedule": timedelta(minutes=10),
+ },
}
# The maximum wait time between each is_due() call on schedulers
@@ -825,6 +829,17 @@ CHECKOUT_PRICES_TTL = timedelta(
seconds=parse(os.environ.get("CHECKOUT_PRICES_TTL", "1 hour"))
)
+CHECKOUT_TTL_BEFORE_RELEASING_FUNDS = timedelta(
+ seconds=parse(os.environ.get("CHECKOUT_TTL_BEFORE_RELEASING_FUNDS", "6 hours"))
+)
+CHECKOUT_BATCH_FOR_RELEASING_FUNDS = os.environ.get(
+ "CHECKOUT_BATCH_FOR_RELEASING_FUNDS", 30
+)
+TRANSACTION_BATCH_FOR_RELEASING_FUNDS = os.environ.get(
+ "TRANSACTION_BATCH_FOR_RELEASING_FUNDS", 60
+)
+
+
# The maximum SearchVector expression count allowed per index SQL statement
# If the count is exceeded, the expression list will be truncated
INDEX_MAXIMUM_EXPR_COUNT = 4000
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 519aa969b4..52df99bfd0 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -6570,6 +6570,7 @@ def transaction_item_generator():
refunded_value=Decimal(0),
canceled_value=Decimal(0),
use_old_id=False,
+ last_refund_success=True,
):
if available_actions is None:
available_actions = []
@@ -6586,6 +6587,7 @@ def transaction_item_generator():
app=app,
user=user,
use_old_id=use_old_id,
+ last_refund_success=last_refund_success,
)
create_manual_adjustment_events(
transaction=transaction,
diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.py
index bd07a89413..cace7fa767 100644
--- a/saleor/webhook/transport/synchronous/transport.py
+++ b/saleor/webhook/transport/synchronous/transport.py
@@ -20,7 +20,10 @@ from ....graphql.webhook.subscription_payload import (
from ....graphql.webhook.subscription_types import WEBHOOK_TYPES_MAP
from ....payment import PaymentError
from ....payment.models import TransactionEvent
-from ....payment.utils import create_transaction_event_from_request_and_webhook_response
+from ....payment.utils import (
+ create_transaction_event_from_request_and_webhook_response,
+ recalculate_refundable_for_checkout,
+)
from ... import observability
from ...const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
from ...event_types import WebhookEventSyncType
@@ -55,17 +58,18 @@ task_logger = get_task_logger(__name__)
retry_kwargs={"max_retries": 5},
)
def handle_transaction_request_task(self, delivery_id, request_event_id):
- delivery = get_delivery_for_webhook(delivery_id)
- if not delivery:
+ request_event = TransactionEvent.objects.filter(id=request_event_id).first()
+ if not request_event:
logger.error(
- f"Cannot find the delivery with id: {delivery_id} "
+ f"Cannot find the request event with id: {request_event_id} "
f"for transaction-request webhook."
)
return None
- request_event = TransactionEvent.objects.filter(id=request_event_id).first()
- if not request_event:
+ delivery = get_delivery_for_webhook(delivery_id)
+ if not delivery:
+ recalculate_refundable_for_checkout(request_event.transaction, request_event)
logger.error(
- f"Cannot find the request event with id: {request_event_id} "
+ f"Cannot find the delivery with id: {delivery_id} "
f"for transaction-request webhook."
)
return None
diff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.py
index d67a57a568..3ff49fad0f 100644
--- a/saleor/webhook/transport/utils.py
+++ b/saleor/webhook/transport/utils.py
@@ -32,6 +32,7 @@ from ...core.models import (
from ...core.taxes import TaxData, TaxLineData
from ...core.utils import build_absolute_uri
from ...core.utils.events import call_event
+from ...payment import PaymentError
from ...payment.interface import (
GatewayResponse,
PaymentData,
@@ -39,7 +40,10 @@ from ...payment.interface import (
PaymentMethodInfo,
TransactionActionData,
)
-from ...payment.utils import create_failed_transaction_event
+from ...payment.utils import (
+ create_failed_transaction_event,
+ recalculate_refundable_for_checkout,
+)
from ...webhook.utils import get_webhooks_for_event
from .. import observability
from ..const import APP_ID_PREFIX
@@ -421,13 +425,6 @@ def trigger_transaction_request(
handle_transaction_request_task,
)
- if not transaction_data.event:
- logger.warning(
- "The transaction request for transaction: %s doesn't have a "
- "proper REQUEST event.",
- transaction_data.transaction.id,
- )
- return None
if not transaction_data.transaction_app_owner:
create_failed_transaction_event(
transaction_data.event,
@@ -436,6 +433,9 @@ def trigger_transaction_request(
"attached to any app."
),
)
+ recalculate_refundable_for_checkout(
+ transaction_data.transaction, transaction_data.event
+ )
return None
webhook = get_webhooks_for_event(
event_type, apps_ids=[transaction_data.transaction_app_owner.pk]
@@ -445,19 +445,29 @@ def trigger_transaction_request(
transaction_data.event,
cause="Cannot find a webhook that can process the action.",
)
+ recalculate_refundable_for_checkout(
+ transaction_data.transaction, transaction_data.event
+ )
return None
if webhook.subscription_query:
- delivery = create_delivery_for_subscription_sync_event(
- event_type=event_type,
- subscribable_object=transaction_data,
- webhook=webhook,
- )
+ delivery = None
+ try:
+ delivery = create_delivery_for_subscription_sync_event(
+ event_type=event_type,
+ subscribable_object=transaction_data,
+ webhook=webhook,
+ )
+ except PaymentError as e:
+ logger.warning("Failed to create delivery for subscription webhook: %s", e)
if not delivery:
create_failed_transaction_event(
transaction_data.event,
cause="Cannot generate a payload for the action.",
)
+ recalculate_refundable_for_checkout(
+ transaction_data.transaction, transaction_data.event
+ )
return None
else:
payload = generate_transaction_action_request_payload(