Skip to content

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

Refactor get_last_active_payment on checkout

IKarbowiakd0e45b35dc2c
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 2e96e47adc..59639b20b4 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -139,8 +139,7 @@ class Checkout(ModelWithMetadata):
return next(matching_lines, None)
def get_last_active_payment(self) -> Optional["Payment"]:
- payments = [payment for payment in self.payments.all() if payment.is_active]
- return max(payments, default=None, key=attrgetter("pk"))
+ return self.payments.filter(is_active=True).last()
def set_country(
self, country_code: str, commit: bool = False, replace: bool = True
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index 1020a3c1fd..e2c73e2b82 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -18,6 +18,7 @@ from ...discount import DiscountValueType, VoucherType
from ...discount.models import NotApplicable, Voucher
from ...order import OrderEvents, OrderEventsEmails
from ...order.models import OrderEvent
+from ...payment.models import Payment
from ...plugins.manager import get_plugins_manager
from ...shipping.models import ShippingZone
from ...tests.utils import flush_post_commit_hooks
@@ -1404,3 +1405,18 @@ def test_store_user_address_create_new_address_if_not_associated(address):
assert user.addresses.count() == expected_user_addresses_count
assert user.default_billing_address_id != address.pk
+
+
+def test_get_last_active_payments(checkout_with_payments):
+ # given
+ payment = Payment.objects.create(
+ gateway="mirumee.payments.dummy",
+ is_active=True,
+ checkout=checkout_with_payments,
+ )
+
+ # when
+ last_payment = checkout_with_payments.get_last_active_payment()
+
+ # then
+ assert last_payment.pk == payment.pk
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 47840febbe..09dd76d66d 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -329,6 +329,21 @@ def checkout_with_voucher_percentage_and_shipping(
return checkout
+def checkout_with_payments(checkout):
+ Payment.objects.bulk_create(
+ [
+ Payment(
+ gateway="mirumee.payments.dummy", is_active=True, checkout=checkout
+ ),
+ Payment(
+ gateway="mirumee.payments.dummy", is_active=False, checkout=checkout
+ ),
+ ]
+ )
+ return checkout
+
+
@pytest.fixture
def address(db): # pylint: disable=W0613
return Address.objects.create(