Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix authorize and charge statuses for checkout (#14573)
Maciej Korycinski5b2bde516fe7
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.pyindex ca7131d2c5..492b934e1f 100644--- a/saleor/checkout/calculations.py+++ b/saleor/checkout/calculations.py@@ -507,6 +507,7 @@ def fetch_checkout_data(update_checkout_payment_statuses(checkout=checkout_info.checkout,checkout_total_gross=current_total_gross,+ checkout_has_lines=bool(lines),checkout_transactions=checkout_transactions,)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.pynew file mode 100644index 0000000000..450fc9e658--- /dev/null+++ b/saleor/checkout/migrations/0060_fix_charge_and_authorize_status_for_empty_checkouts.py@@ -0,0 +1,153 @@+from decimal import Decimal++from django.db import migrations+from django.db.models.expressions import Exists, OuterRef+from prices import Money++# It takes less that a second to process the batch.+# The memory usage peak on celery worker was around 40MB.+BATCH_SIZE = 2000+++def zero_money(currency):+ """Return a money object set to zero.++ This is a function used as a model's default.+ """+ return Money(0, currency)+++def _update_charge_status(+ checkout,+ checkout_total_gross,+ total_charged,+ checkout_has_lines,+):+ zero_money_amount = zero_money(checkout.currency)+ total_charged = max(zero_money_amount, total_charged)+ checkout_with_only_zero_price_lines = (+ checkout_has_lines and checkout_total_gross <= zero_money_amount+ )++ if total_charged <= zero_money_amount and checkout_with_only_zero_price_lines:+ checkout.charge_status = "full"+ elif total_charged <= zero_money_amount:+ checkout.charge_status = "none"+ elif total_charged < checkout_total_gross:+ checkout.charge_status = "partial"+ elif total_charged == checkout_total_gross:+ checkout.charge_status = "full"+ elif total_charged > checkout_total_gross:+ checkout.charge_status = "overcharged"+ else:+ checkout.charge_status = "none"+++def _update_authorize_status(+ checkout,+ checkout_total_gross,+ total_authorized,+ total_charged,+ checkout_has_lines,+):+ total_covered = total_authorized + total_charged+ zero_money_amount = zero_money(checkout.currency)++ checkout_with_only_zero_price_lines = (+ checkout_has_lines and checkout_total_gross <= zero_money_amount+ )++ if total_covered <= zero_money_amount and checkout_with_only_zero_price_lines:+ checkout.authorize_status = "full"+ elif total_covered == zero_money_amount:+ checkout.authorize_status = "none"+ elif total_covered >= checkout_total_gross:+ checkout.authorize_status = "full"+ elif total_covered < checkout_total_gross and total_covered > zero_money_amount:+ checkout.authorize_status = "partial"+ else:+ checkout.authorize_status = "none"+++def _get_payment_amount_for_checkout(checkout_transactions, currency):+ total_charged_amount = zero_money(currency)+ total_authorized_amount = zero_money(currency)+ for transaction in checkout_transactions:+ total_authorized_amount += transaction.amount_authorized+ total_authorized_amount += transaction.amount_authorize_pending++ total_charged_amount += transaction.amount_charged+ total_charged_amount += transaction.amount_charge_pending+ return total_authorized_amount, total_charged_amount+++def update_checkout_payment_statuses(+ checkout,+ checkout_total_gross,+ checkout_has_lines,+ checkout_transactions,+):+ total_authorized_amount, total_charged_amount = _get_payment_amount_for_checkout(+ checkout_transactions, checkout.currency+ )+ _update_authorize_status(+ checkout,+ checkout_total_gross,+ total_authorized_amount,+ total_charged_amount,+ checkout_has_lines,+ )+ _update_charge_status(+ checkout, checkout_total_gross, total_charged_amount, checkout_has_lines+ )+++def fix_statuses_for_batch_of_empty_checkouts(+ Checkout, empty_checkouts_fully_charged_and_authorized_ids+):+ checkouts = Checkout.objects.filter(+ pk__in=empty_checkouts_fully_charged_and_authorized_ids+ ).prefetch_related("payment_transactions")+ checkouts_to_update = []+ for checkout in checkouts:+ update_checkout_payment_statuses(+ checkout,+ checkout.total_gross_amount,+ False,+ checkout.payment_transactions.all(),+ )+ checkouts_to_update.append(checkout)+ Checkout.objects.bulk_update(+ checkouts_to_update, ["authorize_status", "charge_status"]+ )+++def fix_charge_status_for_empty_checkouts(apps, _schema_editor):+ Checkout = apps.get_model("checkout", "Checkout")+ CheckoutLine = apps.get_model("checkout", "CheckoutLine")++ while True:+ empty_checkouts_fully_charged_and_authorized_ids = Checkout.objects.filter(+ ~Exists(CheckoutLine.objects.filter(checkout_id=OuterRef("pk"))),+ charge_status="full",+ authorize_status="full",+ total_gross_amount__lte=Decimal(0),+ ).values_list("pk", flat=True)[:BATCH_SIZE]++ if not empty_checkouts_fully_charged_and_authorized_ids:+ break+ fix_statuses_for_batch_of_empty_checkouts(+ Checkout, empty_checkouts_fully_charged_and_authorized_ids+ )+++class Migration(migrations.Migration):+ dependencies = [+ ("checkout", "0059_merge_0058"),+ ]+ operations = [+ migrations.RunPython(+ fix_charge_status_for_empty_checkouts,+ reverse_code=migrations.RunPython.noop,+ ),+ ]diff --git a/saleor/checkout/migrations/tasks/__init__.py b/saleor/checkout/migrations/tasks/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/checkout/payment_utils.py b/saleor/checkout/payment_utils.pyindex 53a6b27361..a95ee460b2 100644--- a/saleor/checkout/payment_utils.py+++ b/saleor/checkout/payment_utils.py@@ -13,12 +13,20 @@ if TYPE_CHECKING:def _update_charge_status(- checkout: Checkout, checkout_total_gross: Money, total_charged: Money+ checkout: Checkout,+ checkout_total_gross: Money,+ total_charged: Money,+ checkout_has_lines: bool,):zero_money_amount = zero_money(checkout.currency)total_charged = max(zero_money_amount, total_charged)+ checkout_with_only_zero_price_lines = (+ checkout_has_lines and checkout_total_gross <= zero_money_amount+ )- if total_charged <= zero_money_amount and checkout_total_gross != zero_money_amount:+ if total_charged <= zero_money_amount and checkout_with_only_zero_price_lines:+ checkout.charge_status = CheckoutChargeStatus.FULL+ elif total_charged <= zero_money_amount:checkout.charge_status = CheckoutChargeStatus.NONEelif total_charged < checkout_total_gross:checkout.charge_status = CheckoutChargeStatus.PARTIAL@@ -35,10 +43,18 @@ def _update_authorize_status(checkout_total_gross: Money,total_authorized: Money,total_charged: Money,+ checkout_has_lines: bool,):total_covered = total_authorized + total_chargedzero_money_amount = zero_money(checkout.currency)- if total_covered == zero_money_amount and checkout_total_gross != zero_money_amount:++ checkout_with_only_zero_price_lines = (+ checkout_has_lines and checkout_total_gross <= zero_money_amount+ )++ if total_covered <= zero_money_amount and checkout_with_only_zero_price_lines:+ checkout.authorize_status = CheckoutAuthorizeStatus.FULL+ elif total_covered == zero_money_amount:checkout.authorize_status = CheckoutAuthorizeStatus.NONEelif total_covered >= checkout_total_gross:checkout.authorize_status = CheckoutAuthorizeStatus.FULL@@ -65,19 +81,34 @@ def _get_payment_amount_for_checkout(def update_checkout_payment_statuses(checkout: Checkout,checkout_total_gross: Money,+ checkout_has_lines: bool,checkout_transactions: Optional[Iterable["TransactionItem"]] = None,save: bool = True,):+ current_authorize_status = checkout.authorize_status+ current_charge_status = checkout.charge_status+if checkout_transactions is None:checkout_transactions = checkout.payment_transactions.all()total_authorized_amount, total_charged_amount = _get_payment_amount_for_checkout(checkout_transactions, checkout.currency)_update_authorize_status(- checkout, checkout_total_gross, total_authorized_amount, total_charged_amount+ checkout,+ checkout_total_gross,+ total_authorized_amount,+ total_charged_amount,+ checkout_has_lines,+ )+ _update_charge_status(+ checkout, checkout_total_gross, total_charged_amount, checkout_has_lines)- _update_charge_status(checkout, checkout_total_gross, total_charged_amount)if save:- checkout.save(- update_fields=["authorize_status", "charge_status", "last_change"]- )+ fields_to_update = []+ if current_authorize_status != checkout.authorize_status:+ fields_to_update.append("authorize_status")+ if current_charge_status != checkout.charge_status:+ fields_to_update.append("charge_status")+ if fields_to_update:+ fields_to_update.append("last_change")+ checkout.save(update_fields=fields_to_update)diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.pyindex 58e5cdcf4a..7143a907ea 100644--- a/saleor/checkout/tests/test_checkout_complete.py+++ b/saleor/checkout/tests/test_checkout_complete.py@@ -1192,7 +1192,9 @@ def test_complete_checkout_0_total_with_transaction_for_mark_as_paid(checkout.billing_address = customer_user.default_billing_addresscheckout.save()- update_checkout_payment_statuses(checkout, zero_money(checkout.currency))+ update_checkout_payment_statuses(+ checkout, zero_money(checkout.currency), checkout_has_lines=True+ )manager = get_plugins_manager()lines, _ = fetch_checkout_lines(checkout)@@ -1945,7 +1947,8 @@ def test_checkout_complete_pick_transaction_flow_when_checkout_total_zero(checkout.total = zero_taxed_money(checkout.currency)update_checkout_payment_statuses(checkout=checkout,- checkout_total_gross=checkout.total,+ checkout_total_gross=checkout.total.gross,+ checkout_has_lines=bool(lines),)mocked_flow.return_value = order, False, {}diff --git a/saleor/checkout/tests/test_payment_utils.py b/saleor/checkout/tests/test_payment_utils.pynew file mode 100644index 0000000000..86df1312b5--- /dev/null+++ b/saleor/checkout/tests/test_payment_utils.py@@ -0,0 +1,54 @@+from decimal import Decimal++import pytest++from .. import CheckoutChargeStatus+from ..payment_utils import update_checkout_payment_statuses+++ ("checkout_total", "charged_value", "has_lines", "expected_charge_status"),+ [+ (Decimal(-1), Decimal(-1), False, CheckoutChargeStatus.NONE),+ (Decimal(0), Decimal(-1), False, CheckoutChargeStatus.NONE),+ (Decimal(0), Decimal(0), True, CheckoutChargeStatus.FULL),+ (Decimal(0), Decimal(0), False, CheckoutChargeStatus.NONE),+ (Decimal(1), Decimal(0), False, CheckoutChargeStatus.NONE),+ (Decimal(1), Decimal(0.5), False, CheckoutChargeStatus.PARTIAL),+ (Decimal(1), Decimal(1), False, CheckoutChargeStatus.FULL),+ (Decimal(0), Decimal(1), False, CheckoutChargeStatus.OVERCHARGED),+ (Decimal(1), Decimal(2), False, CheckoutChargeStatus.OVERCHARGED),+ (Decimal(1), Decimal(0), True, CheckoutChargeStatus.NONE),+ (Decimal(1), Decimal(0.5), True, CheckoutChargeStatus.PARTIAL),+ (Decimal(1), Decimal(1), True, CheckoutChargeStatus.FULL),+ (Decimal(0), Decimal(1), True, CheckoutChargeStatus.OVERCHARGED),+ (Decimal(1), Decimal(2), True, CheckoutChargeStatus.OVERCHARGED),+ ],+)+def test_checkout_charge_status(+ checkout_total,+ charged_value,+ has_lines,+ expected_charge_status,+ checkout_with_prices,+ transaction_item_generator,+):+ # given+ checkout_with_prices.total_gross_amount = checkout_total+ checkout_with_prices.total_net_amount = checkout_total++ tr = transaction_item_generator(+ checkout_id=checkout_with_prices.pk, charged_value=charged_value+ )++ # when+ update_checkout_payment_statuses(+ checkout_with_prices,+ checkout_total_gross=checkout_with_prices.total.gross,+ checkout_has_lines=has_lines,+ checkout_transactions=[tr],+ )++ # then+ checkout_with_prices.refresh_from_db()+ assert checkout_with_prices.charge_status == expected_charge_statusdiff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex b62a37088e..b21b9d5d82 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -412,7 +412,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(62):+ with django_assert_num_queries(61):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 1@@ -430,7 +430,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(62):+ with django_assert_num_queries(61):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 10@@ -681,7 +681,7 @@ def test_update_checkout_lines_with_reservations(reservation_length=5,)- with django_assert_num_queries(76):+ with django_assert_num_queries(75):variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)variables = {"id": to_global_id_or_none(checkout),@@ -695,7 +695,7 @@ def test_update_checkout_lines_with_reservations(assert not data["errors"]# Updating multiple lines in checkout has same query count as updating one- with django_assert_num_queries(76):+ with django_assert_num_queries(75):variables = {"id": to_global_id_or_none(checkout),"lines": [],@@ -940,7 +940,7 @@ def test_add_checkout_lines_with_reservations(new_lines.append({"quantity": 2, "variantId": variant_id})# Adding multiple lines to checkout has same query count as adding one- with django_assert_num_queries(75):+ with django_assert_num_queries(74):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": [new_lines[0]],@@ -953,7 +953,7 @@ def test_add_checkout_lines_with_reservations(checkout.lines.exclude(id=line.id).delete()- with django_assert_num_queries(75):+ with django_assert_num_queries(74):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": new_lines,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.pyindex f1be2ee59f..fbb6d9028a 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py@@ -127,6 +127,7 @@ def prepare_checkout_for_test(update_checkout_payment_statuses(checkout=checkout_info.checkout,checkout_total_gross=total.gross,+ checkout_has_lines=bool(lines),)return checkout@@ -161,6 +162,7 @@ def test_checkout_without_any_transaction(update_checkout_payment_statuses(checkout=checkout_info.checkout,checkout_total_gross=total.gross,+ checkout_has_lines=bool(lines),)redirect_url = "https://www.example.com"@@ -209,6 +211,7 @@ def test_checkout_without_any_transaction_allow_to_create_order(update_checkout_payment_statuses(checkout=checkout_info.checkout,checkout_total_gross=total.gross,+ checkout_has_lines=bool(lines),)redirect_url = "https://www.example.com"@@ -263,6 +266,7 @@ def test_checkout_with_total_0(update_checkout_payment_statuses(checkout=checkout_info.checkout,checkout_total_gross=total.gross,+ checkout_has_lines=bool(lines),)redirect_url = "https://www.example.com"@@ -328,6 +332,7 @@ def test_checkout_with_authorized(update_checkout_payment_statuses(checkout=checkout_info.checkout,checkout_total_gross=total.gross,+ checkout_has_lines=bool(lines),)redirect_url = "https://www.example.com"@@ -424,6 +429,7 @@ def test_checkout_with_charged(update_checkout_payment_statuses(checkout=checkout_info.checkout,checkout_total_gross=total.gross,+ checkout_has_lines=bool(lines),)redirect_url = "https://www.example.com"@@ -513,6 +519,7 @@ def test_checkout_paid_with_multiple_transactions(update_checkout_payment_statuses(checkout=checkout_info.checkout,checkout_total_gross=total.gross,+ checkout_has_lines=bool(lines),)redirect_url = "https://www.example.com"@@ -571,6 +578,7 @@ def test_checkout_partially_paid(update_checkout_payment_statuses(checkout=checkout_info.checkout,checkout_total_gross=total.gross,+ checkout_has_lines=bool(lines),)redirect_url = "https://www.example.com"@@ -623,6 +631,7 @@ def test_checkout_partially_paid_allow_unpaid_order(update_checkout_payment_statuses(checkout=checkout_info.checkout,checkout_total_gross=total.gross,+ checkout_has_lines=bool(lines),)redirect_url = "https://www.example.com"@@ -689,6 +698,7 @@ def test_checkout_with_pending_charged(update_checkout_payment_statuses(checkout=checkout_info.checkout,checkout_total_gross=total.gross,+ checkout_has_lines=bool(lines),)redirect_url = "https://www.example.com"@@ -765,6 +775,7 @@ def test_checkout_with_pending_authorized(update_checkout_payment_statuses(checkout=checkout_info.checkout,checkout_total_gross=total.gross,+ checkout_has_lines=bool(lines),)redirect_url = "https://www.example.com"diff --git a/saleor/graphql/checkout/tests/test_checkout_filters.py b/saleor/graphql/checkout/tests/test_checkout_filters.pyindex 2a071d17b3..ed9a2d114d 100644--- a/saleor/graphql/checkout/tests/test_checkout_filters.py+++ b/saleor/graphql/checkout/tests/test_checkout_filters.py@@ -486,13 +486,15 @@ def test_checkouts_query_with_filter_authorize_status(currency=checkout_with_prices.currency, authorized_value=Decimal("10"))- update_checkout_payment_statuses(first_checkout, first_checkout.total.gross)+ update_checkout_payment_statuses(+ first_checkout, first_checkout.total.gross, checkout_has_lines=True+ )checkout_with_prices.payment_transactions.create(currency=checkout_with_prices.currency, **transaction_data)update_checkout_payment_statuses(- checkout_with_prices, checkout_with_prices.total.gross+ checkout_with_prices, checkout_with_prices.total.gross, checkout_has_lines=True)variables = {"filter": {"authorizeStatus": statuses}}@@ -586,13 +588,15 @@ def test_checkouts_query_with_filter_charge_status(currency=checkout_with_prices.currency, charged_value=Decimal("10"))- update_checkout_payment_statuses(first_checkout, first_checkout.total.gross)+ update_checkout_payment_statuses(+ first_checkout, first_checkout.total.gross, checkout_has_lines=True+ )checkout_with_prices.payment_transactions.create(currency=checkout_with_prices.currency, **transaction_data)update_checkout_payment_statuses(- checkout_with_prices, checkout_with_prices.total.gross+ checkout_with_prices, checkout_with_prices.total.gross, checkout_has_lines=True)variables = {"filter": {"chargeStatus": statuses}}diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex 334db48125..78049a88af 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -1168,6 +1168,7 @@ class Checkout(ModelObjectType[models.Checkout]):lines=lines,address=address,checkout_transactions=transactions,+ force_status_update=True,)return checkout_info.checkout.authorize_status@@ -1187,6 +1188,7 @@ class Checkout(ModelObjectType[models.Checkout]):lines=lines,address=address,checkout_transactions=transactions,+ force_status_update=True,)return checkout_info.checkout.charge_status