Skip to content

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

Fix race condition in TransactionCreate mutation when updating checkout/order prices (#17913)

Filip Owczarek2864acf1fa4e
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_create.py b/saleor/graphql/payment/mutations/transaction/transaction_create.py
index d5f8890ca6..bbe77b4806 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_create.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_create.py
@@ -1,26 +1,36 @@
import uuid
from decimal import Decimal
-from typing import cast
+from typing import TYPE_CHECKING, cast
+from uuid import UUID
import graphene
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.db.models import Model
+from .....account.models import User
+from .....app.models import App
from .....checkout import models as checkout_models
-from .....checkout.actions import transaction_amounts_for_checkout_updated
+from .....checkout.actions import (
+ transaction_amounts_for_checkout_updated_without_price_recalculation,
+)
from .....core.prices import quantize_price
+from .....core.tracing import traced_atomic_transaction
from .....order import OrderStatus
from .....order import models as order_models
from .....order.actions import order_transaction_updated
from .....order.events import transaction_event as order_transaction_event
from .....order.fetch import fetch_order_info
from .....order.search import update_order_search_vector
-from .....order.utils import update_order_status, updates_amounts_for_order
+from .....order.utils import refresh_order_status, updates_amounts_for_order
from .....payment import TransactionEventType
from .....payment import models as payment_models
from .....payment.error_codes import TransactionCreateErrorCode
from .....payment.interface import PaymentMethodDetails
+from .....payment.lock_objects import (
+ get_checkout_and_transaction_item_locked_for_update,
+ get_order_and_transaction_item_locked_for_update,
+)
from .....payment.transaction_item_calculations import recalculate_transaction_amounts
from .....payment.utils import (
create_manual_adjustment_events,
@@ -47,6 +57,9 @@ from .shared import (
validate_payment_method_details_input,
)
+if TYPE_CHECKING:
+ from .....plugins.manager import PluginsManager
+
class TransactionCreateInput(BaseInputObjectType):
name = graphene.String(description="Payment name of the transaction.")
@@ -331,38 +344,87 @@ class TransactionCreate(BaseMutation):
)
@classmethod
- def update_order(
+ def process_order_with_transaction(
cls,
- order: order_models.Order,
- money_data: dict,
- update_search_vector: bool = True,
- ) -> None:
- update_fields = []
- if money_data:
- updates_amounts_for_order(order, save=False)
- update_fields.extend(
- [
- "total_authorized_amount",
- "total_charged_amount",
- "authorize_status",
- "charge_status",
- ]
- )
- if (
- order.channel.automatically_confirm_all_new_orders
- and order.status == OrderStatus.UNCONFIRMED
- ):
- update_order_status(order)
-
- if update_search_vector:
- update_order_search_vector(order, save=False)
- update_fields.append(
- "search_vector",
+ transaction: payment_models.TransactionItem,
+ manager: "PluginsManager",
+ user: User | None,
+ app: App | None,
+ money_data: dict[str, Decimal],
+ ):
+ order = None
+ # This is executed after we ensure that the transaction is not a checkout
+ # transaction, so we can safely cast the order_id to UUID.
+ order_id = cast(UUID, transaction.order_id)
+ with traced_atomic_transaction():
+ order, transaction = get_order_and_transaction_item_locked_for_update(
+ order_id, transaction.pk
)
+ update_fields = []
+ if money_data:
+ updates_amounts_for_order(order, save=False)
+ update_fields.extend(
+ [
+ "total_charged_amount",
+ "charge_status",
+ "total_authorized_amount",
+ "authorize_status",
+ ]
+ )
+ if (
+ order.channel.automatically_confirm_all_new_orders
+ and order.status == OrderStatus.UNCONFIRMED
+ ):
+ status_updated = refresh_order_status(order)
+ if status_updated:
+ update_fields.append("status")
+ if update_fields:
+ update_fields.append("updated_at")
+ order.save(update_fields=update_fields)
+
+ update_order_search_vector(order)
+
+ order_info = fetch_order_info(order)
+ order_transaction_updated(
+ order_info=order_info,
+ transaction_item=transaction,
+ manager=manager,
+ user=user,
+ app=app,
+ previous_authorized_value=Decimal(0),
+ previous_charged_value=Decimal(0),
+ previous_refunded_value=Decimal(0),
+ )
- if update_fields:
- update_fields.append("updated_at")
- order.save(update_fields=update_fields)
+ @classmethod
+ def process_order_or_checkout_with_transaction(
+ cls,
+ transaction: payment_models.TransactionItem,
+ manager: "PluginsManager",
+ user: User | None,
+ app: App | None,
+ money_data: dict[str, Decimal],
+ ):
+ checkout_deleted = False
+ if transaction.checkout_id and money_data:
+ with traced_atomic_transaction():
+ locked_checkout, transaction = (
+ get_checkout_and_transaction_item_locked_for_update(
+ transaction.checkout_id, transaction.pk
+ )
+ )
+ if transaction.checkout_id and locked_checkout:
+ transaction_amounts_for_checkout_updated_without_price_recalculation(
+ transaction, locked_checkout, manager, user, app
+ )
+ else:
+ checkout_deleted = True
+ # If the checkout was deleted, we still want to update the order associated with the transaction.
+
+ if (transaction.order_id or checkout_deleted) and money_data:
+ cls.process_order_with_transaction(
+ transaction, manager, user, app, money_data
+ )
@classmethod
def perform_mutation( # type: ignore[override]
@@ -417,25 +479,13 @@ class TransactionCreate(BaseMutation):
transaction=new_transaction, money_data=money_data, user=user, app=app
)
recalculate_transaction_amounts(new_transaction)
- if transaction_data.get("order_id") and money_data:
- order = cast(order_models.Order, new_transaction.order)
- cls.update_order(order, money_data, update_search_vector=True)
-
- order_info = fetch_order_info(order)
- order_transaction_updated(
- order_info=order_info,
- transaction_item=new_transaction,
- manager=manager,
- user=user,
- app=app,
- previous_authorized_value=Decimal(0),
- previous_charged_value=Decimal(0),
- previous_refunded_value=Decimal(0),
- )
- if transaction_data.get("checkout_id") and money_data:
- transaction_amounts_for_checkout_updated(
- new_transaction, manager, user, app
- )
+ cls.process_order_or_checkout_with_transaction(
+ new_transaction,
+ manager,
+ user,
+ app,
+ money_data,
+ )
if transaction_event:
cls.create_transaction_event(transaction_event, new_transaction, user, app)
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
index e6c00ccaa0..c9da55d653 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
@@ -1,10 +1,12 @@
from decimal import Decimal
from typing import TYPE_CHECKING, Optional, cast
+from uuid import UUID as UUID_TYPE
import graphene
from django.core.exceptions import ValidationError
from django.utils import timezone
+from .....account.models import User
from .....app.models import App
from .....checkout.actions import (
transaction_amounts_for_checkout_updated_without_price_recalculation,
@@ -65,7 +67,6 @@ from .shared import (
from .utils import get_transaction_item
if TYPE_CHECKING:
- from .....accounts.models import User
from .....plugins.manager import PluginsManager
@@ -307,17 +308,20 @@ class TransactionEventReport(DeprecatedModelMutation):
cls,
transaction: payment_models.TransactionItem,
manager: "PluginsManager",
- user: Optional["User"],
+ user: User | None,
app: App | None,
previous_authorized_value: Decimal,
previous_charged_value: Decimal,
previous_refunded_value: Decimal,
related_granted_refund: order_models.OrderGrantedRefund | None,
):
- order = cast(order_models.Order, transaction.order)
+ order = None
+ # This is executed after we ensure that the transaction is not a checkout
+ # transaction, so we can safely cast the order_id to UUID.
+ order_id = cast(UUID_TYPE, transaction.order_id)
with traced_atomic_transaction():
order, transaction = get_order_and_transaction_item_locked_for_update(
- order.pk, transaction.pk
+ order_id, transaction.pk
)
updates_amounts_for_order(order)
update_order_search_vector(order)
@@ -340,7 +344,7 @@ class TransactionEventReport(DeprecatedModelMutation):
cls,
transaction: payment_models.TransactionItem,
manager: "PluginsManager",
- user: Optional["User"],
+ user: User | None,
app: App | None,
previous_authorized_value: Decimal,
previous_charged_value: Decimal,
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_update.py b/saleor/graphql/payment/mutations/transaction/transaction_update.py
index c7205974b6..5d4d8a014c 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_update.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_update.py
@@ -6,10 +6,16 @@ from django.core.exceptions import ValidationError
from .....app.models import App
from .....checkout.actions import transaction_amounts_for_checkout_updated
from .....core.exceptions import PermissionDenied
+from .....order import OrderStatus
from .....order import models as order_models
from .....order.actions import order_transaction_updated
from .....order.events import transaction_event as order_transaction_event
from .....order.fetch import fetch_order_info
+from .....order.search import update_order_search_vector
+from .....order.utils import (
+ update_order_status,
+ updates_amounts_for_order,
+)
from .....payment import models as payment_models
from .....payment.error_codes import (
TransactionCreateErrorCode,
@@ -194,6 +200,42 @@ class TransactionUpdate(TransactionCreate):
transaction_data["app"] = app
transaction_data["app_identifier"] = app.identifier
+ # TODO (ENG-295): Remove this method when this will be refactored to use
+ # the new functions `process_order_or_checkout_with_transaction`.
+ @classmethod
+ def update_order(
+ cls,
+ order: order_models.Order,
+ money_data: dict,
+ update_search_vector: bool = True,
+ ) -> None:
+ update_fields = []
+ if money_data:
+ updates_amounts_for_order(order, save=False)
+ update_fields.extend(
+ [
+ "total_authorized_amount",
+ "total_charged_amount",
+ "authorize_status",
+ "charge_status",
+ ]
+ )
+ if (
+ order.channel.automatically_confirm_all_new_orders
+ and order.status == OrderStatus.UNCONFIRMED
+ ):
+ update_order_status(order)
+
+ if update_search_vector:
+ update_order_search_vector(order, save=False)
+ update_fields.append(
+ "search_vector",
+ )
+
+ if update_fields:
+ update_fields.append("updated_at")
+ order.save(update_fields=update_fields)
+
@classmethod
def perform_mutation(
cls,
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
index 006135db18..d40939d135 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -7,6 +7,7 @@ from freezegun import freeze_time
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
+from .....checkout.complete_checkout import create_order_from_checkout
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
from .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderEvents, OrderStatus
@@ -14,7 +15,12 @@ from .....order.models import Order
from .....order.utils import update_order_authorize_data, update_order_charge_data
from .....payment import PaymentMethodType, TransactionEventType
from .....payment.error_codes import TransactionCreateErrorCode
+from .....payment.lock_objects import (
+ get_checkout_and_transaction_item_locked_for_update,
+ get_order_and_transaction_item_locked_for_update,
+)
from .....payment.models import TransactionItem
+from .....tests import race_condition
from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
from ...enums import TransactionActionEnum, TransactionEventTypeEnum
@@ -418,7 +424,7 @@ def test_transaction_create_for_draft_order(
def test_transaction_create_for_checkout_by_app(
- checkout_with_items, permission_manage_payments, app_api_client
+ checkout_with_prices, permission_manage_payments, app_api_client, plugins_manager
):
# given
name = "Credit Card"
@@ -433,7 +439,7 @@ def test_transaction_create_for_checkout_by_app(
external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
variables = {
- "id": graphene.Node.to_global_id("Checkout", checkout_with_items.pk),
+ "id": graphene.Node.to_global_id("Checkout", checkout_with_prices.pk),
"transaction": {
"name": name,
"pspReference": psp_reference,
@@ -454,13 +460,13 @@ def test_transaction_create_for_checkout_by_app(
)
# then
- checkout_with_items.refresh_from_db()
- assert checkout_with_items.charge_status == CheckoutChargeStatus.NONE
- assert checkout_with_items.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+ checkout_with_prices.refresh_from_db()
+ assert checkout_with_prices.charge_status == CheckoutChargeStatus.NONE
+ assert checkout_with_prices.authorize_status == CheckoutAuthorizeStatus.PARTIAL
available_actions = list(set(available_actions))
- transaction = checkout_with_items.payment_transactions.first()
+ transaction = checkout_with_prices.payment_transactions.first()
content = get_graphql_content(response)
data = content["data"]["transactionCreate"]["transaction"]
assert data["actions"] == available_actions
@@ -483,7 +489,7 @@ def test_transaction_create_for_checkout_by_app(
def test_transaction_create_for_checkout_by_app_metadata_null_value(
- checkout_with_items, permission_manage_payments, app_api_client
+ checkout_with_prices, permission_manage_payments, app_api_client
):
# given
name = "Credit Card"
@@ -496,7 +502,7 @@ def test_transaction_create_for_checkout_by_app_metadata_null_value(
external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
variables = {
- "id": graphene.Node.to_global_id("Checkout", checkout_with_items.pk),
+ "id": graphene.Node.to_global_id("Checkout", checkout_with_prices.pk),
"transaction": {
"name": name,
"pspReference": psp_reference,
@@ -517,13 +523,13 @@ def test_transaction_create_for_checkout_by_app_metadata_null_value(
)
# then
- checkout_with_items.refresh_from_db()
- assert checkout_with_items.charge_status == CheckoutChargeStatus.NONE
- assert checkout_with_items.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+ checkout_with_prices.refresh_from_db()
+ assert checkout_with_prices.charge_status == CheckoutChargeStatus.NONE
+ assert checkout_with_prices.authorize_status == CheckoutAuthorizeStatus.PARTIAL
available_actions = list(set(available_actions))
- transaction = checkout_with_items.payment_transactions.first()
+ transaction = checkout_with_prices.payment_transactions.first()
content = get_graphql_content(response)
data = content["data"]["transactionCreate"]["transaction"]
assert data["actions"] == available_actions
@@ -1131,7 +1137,7 @@ def test_transaction_create_for_order_updates_order_total_charged_by_staff(
def test_transaction_create_for_checkout_by_staff(
- checkout_with_items, permission_manage_payments, staff_api_client
+ checkout_with_prices, permission_manage_payments, staff_api_client
):
# given
name = "Credit Card"
@@ -1145,7 +1151,7 @@ def test_transaction_create_for_checkout_by_staff(
private_metadata = {"key": "test-2", "value": "321"}
variables = {
- "id": graphene.Node.to_global_id("Checkout", checkout_with_items.pk),
+ "id": graphene.Node.to_global_id("Checkout", checkout_with_prices.pk),
"transaction": {
"name": name,
"pspReference": psp_reference,
@@ -1167,10 +1173,10 @@ def test_transaction_create_for_checkout_by_staff(
# then
available_actions = list(set(available_actions))
- checkout_with_items.refresh_from_db()
- assert checkout_with_items.charge_status == CheckoutChargeStatus.NONE
- assert checkout_with_items.authorize_status == CheckoutAuthorizeStatus.PARTIAL
- transaction = checkout_with_items.payment_transactions.first()
+ checkout_with_prices.refresh_from_db()
+ assert checkout_with_prices.charge_status == CheckoutChargeStatus.NONE
+ assert checkout_with_prices.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+ transaction = checkout_with_prices.payment_transactions.first()
content = get_graphql_content(response)
data = content["data"]["transactionCreate"]["transaction"]
assert data["actions"] == available_actions
@@ -2785,3 +2791,169 @@ def test_transaction_create_with_invalid_other_payment_method_details(
error = transaction_data["errors"][0]
assert error["code"] == "INVALID"
assert error["field"] == "paymentMethodDetails"
+
+
+# Test wrapped by `transaction=True` to ensure that `selector_for_update` is called in a database transaction.
[email protected]_db(transaction=True)
+@patch(
+ "saleor.graphql.payment.mutations.transaction.transaction_create.get_order_and_transaction_item_locked_for_update",
+ wraps=get_order_and_transaction_item_locked_for_update,
+)
+def test_lock_order_during_updating_order_amounts(
+ mocked_get_order_and_transaction_item_locked_for_update,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ charged_value = order.total.gross.amount
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order.pk),
+ "transaction": {
+ "name": "Credit Card",
+ "pspReference": "PSP reference - 123",
+ "availableActions": [],
+ "amountCharged": {
+ "amount": charged_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ order.refresh_from_db()
+ transaction_pk = order.payment_transactions.get().pk
+ assert order.total_charged.amount == charged_value
+ assert order.charge_status == OrderChargeStatus.FULL
+ assert order.authorize_status == OrderAuthorizeStatus.FULL
+ mocked_get_order_and_transaction_item_locked_for_update.assert_called_once_with(
+ order.pk, transaction_pk
+ )
+
+
+# Test wrapped by `transaction=True` to ensure that `selector_for_update` is called in a database transaction.
[email protected]_db(transaction=True)
+@patch(
+ "saleor.graphql.payment.mutations.transaction.transaction_create.get_checkout_and_transaction_item_locked_for_update",
+ wraps=get_checkout_and_transaction_item_locked_for_update,
+)
+def test_lock_checkout_during_updating_checkout_amounts(
+ mocked_get_checkout_and_transaction_item_locked_for_update,
+ app_api_client,
+ permission_manage_payments,
+ checkout_with_items,
+ plugins_manager,
+):
+ # given
+ name = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.name,
+ ]
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+
+ checkout = checkout_with_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)
+
+ assert checkout.channel.automatically_complete_fully_paid_checkouts is False
+
+ variables = {
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "transaction": {
+ "name": name,
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ "amountCharged": {
+ "amount": checkout_info.checkout.total.gross.amount,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
+ }
+
+ # when
+ app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ checkout.refresh_from_db()
+ transaction_pk = checkout.payment_transactions.get().pk
+ assert checkout.charge_status == CheckoutChargeStatus.FULL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ mocked_get_checkout_and_transaction_item_locked_for_update.assert_called_once_with(
+ checkout.pk, transaction_pk
+ )
+
+
+def test_transaction_create_create_checkout_completed_race_condition(
+ app_api_client,
+ permission_manage_payments,
+ checkout_with_prices,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ name = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.name,
+ TransactionActionEnum.CHARGE.name,
+ ]
+ authorized_value = Decimal(checkout_info.checkout.total.gross.amount)
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
+
+ variables = {
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "transaction": {
+ "name": name,
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ "externalUrl": external_url,
+ },
+ }
+
+ # when
+ def complete_checkout(*args, **kwargs):
+ create_order_from_checkout(
+ checkout_info, plugins_manager, user=None, app=app_api_client.app
+ )
+
+ with race_condition.RunBefore(
+ "saleor.graphql.payment.mutations.transaction.transaction_create.recalculate_transaction_amounts",
+ complete_checkout,
+ ):
+ app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ order = Order.objects.get(checkout_token=checkout.pk)
+
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.charge_status == OrderChargeStatus.NONE
+ assert order.authorize_status == OrderAuthorizeStatus.FULL
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 a65c66a3e8..cecc0a4fd6 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -13,7 +13,13 @@ from .....checkout.calculations import fetch_checkout_data
from .....checkout.complete_checkout import create_order_from_checkout
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
-from .....order import OrderEvents, OrderGrantedRefundStatus, OrderStatus
+from .....order import (
+ OrderAuthorizeStatus,
+ OrderChargeStatus,
+ OrderEvents,
+ OrderGrantedRefundStatus,
+ OrderStatus,
+)
from .....order.models import Order
from .....payment import OPTIONAL_AMOUNT_EVENTS, PaymentMethodType, TransactionEventType
from .....payment.lock_objects import (
@@ -25,7 +31,6 @@ from .....payment.transaction_item_calculations import recalculate_transaction_a
from .....tests import race_condition
from ....core.enums import TransactionEventReportErrorCode
from ....core.utils import to_global_id_or_none
-from ....order.enums import OrderAuthorizeStatusEnum, OrderChargeStatusEnum
from ....tests.utils import assert_no_permission, get_graphql_content
from ...enums import TransactionActionEnum, TransactionEventTypeEnum
@@ -1060,7 +1065,7 @@ def test_transaction_event_updates_order_total_charged(
order.refresh_from_db()
assert order.total_charged.amount == current_charged_value + amount
- assert order.charge_status == OrderChargeStatusEnum.PARTIAL.value
+ assert order.charge_status == OrderChargeStatus.PARTIAL
def test_transaction_event_updates_order_total_authorized(
@@ -1116,7 +1121,7 @@ def test_transaction_event_updates_order_total_authorized(
order.refresh_from_db()
assert order.total_authorized.amount == order.total.gross.amount + amount
- assert order.authorize_status == OrderAuthorizeStatusEnum.FULL.value
+ assert order.authorize_status == OrderAuthorizeStatus.FULL
def test_transaction_event_updates_search_vector(
@@ -2176,7 +2181,7 @@ def test_transaction_event_report_for_order_triggers_webhooks_when_fully_paid(
order.refresh_from_db()
assert order.status == excpected_order_status
- assert order.charge_status == OrderChargeStatusEnum.FULL.value
+ assert order.charge_status == OrderChargeStatus.FULL
mock_order_fully_paid.assert_called_once_with(order, webhooks=set())
mock_order_updated.assert_called_once_with(order, webhooks=set())
mock_order_paid.assert_called_once_with(order, webhooks=set())
@@ -2242,7 +2247,7 @@ def test_transaction_event_report_for_draft_order_triggers_webhooks_when_fully_p
order.refresh_from_db()
assert order.status == OrderStatus.DRAFT
- assert order.charge_status == OrderChargeStatusEnum.FULL.value
+ assert order.charge_status == OrderChargeStatus.FULL
mock_order_fully_paid.assert_called_once_with(order, webhooks=set())
mock_order_updated.assert_called_once_with(order, webhooks=set())
mock_order_paid.assert_called_once_with(order, webhooks=set())
@@ -2298,7 +2303,7 @@ def test_transaction_event_report_for_order_triggers_webhooks_when_partially_pai
get_graphql_content(response)
order.refresh_from_db()
- assert order.charge_status == OrderChargeStatusEnum.PARTIAL.value
+ assert order.charge_status == OrderChargeStatus.PARTIAL
assert not mock_order_fully_paid.called
mock_order_updated.assert_called_once_with(order, webhooks=set())
@@ -2353,7 +2358,7 @@ def test_transaction_event_report_for_order_triggers_webhooks_when_partially_aut
get_graphql_content(response)
order.refresh_from_db()
- assert order.authorize_status == OrderAuthorizeStatusEnum.PARTIAL.value
+ assert order.authorize_status == OrderAuthorizeStatus.PARTIAL
assert not mock_order_fully_paid.called
mock_order_updated.assert_called_once_with(order, webhooks=set())
@@ -2408,7 +2413,7 @@ def test_transaction_event_report_for_order_triggers_webhooks_when_fully_authori
get_graphql_content(response)
order.refresh_from_db()
- assert order.authorize_status == OrderAuthorizeStatusEnum.FULL.value
+ assert order.authorize_status == OrderAuthorizeStatus.FULL
assert not mock_order_fully_paid.called
mock_order_updated.assert_called_once_with(order, webhooks=set())
@@ -3392,7 +3397,8 @@ def test_lock_order_during_updating_order_amounts(
order.refresh_from_db()
assert order.total_charged.amount == amount
- assert order.charge_status == OrderChargeStatusEnum.FULL.value
+ assert order.charge_status == OrderChargeStatus.FULL
+ assert order.authorize_status == OrderAuthorizeStatus.FULL
mocked_get_order_and_transaction_item_locked_for_update.assert_called_once_with(
order.pk, transaction.pk
)
@@ -3530,7 +3536,7 @@ def test_transaction_event_report_checkout_completed_race_condition(
order = Order.objects.get(checkout_token=checkout.pk)
assert order.status == OrderStatus.UNFULFILLED
- assert order.charge_status == OrderChargeStatusEnum.FULL.value
+ assert order.charge_status == OrderChargeStatus.FULL
assert order.total_charged.amount == checkout.total.gross.amount
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index c4d930daa8..f917321949 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -183,36 +183,55 @@ def _calculate_quantity_including_returns(order):
)
+def refresh_order_status(order: Order):
+ """Refresh order status based on the most recent data.
+
+ This function recalculates the order status using the most up-to-date information
+ about fulfillments, returns, and replacements. It should always be called within
+ a transaction and with the order locked to ensure data consistency and prevent race conditions.
+
+ Returns
+ bool: True if the order status was changed, False otherwise.
+
+ """
+ old_status = order.status
+ # Calculate the quantities for the most recent data
+ (
+ total_quantity,
+ quantity_fulfilled,
+ quantity_returned,
+ quantity_awaiting_approval,
+ ) = _calculate_quantity_including_returns(order)
+
+ all_products_replaced = total_quantity == 0
+ if all_products_replaced:
+ return False
+
+ order.status = determine_order_status(
+ total_quantity,
+ quantity_fulfilled,
+ quantity_returned,
+ quantity_awaiting_approval,
+ )
+ return old_status != order.status
+
+
def update_order_status(order: Order):
"""Update order status depending on fulfillments."""
with transaction.atomic():
# Add a transaction block to ensure that the order status won't be overridden by
# another process.
locked_order = Order.objects.select_for_update().get(pk=order.pk)
- # Calculate the quantities for the most recent data
- (
- total_quantity,
- quantity_fulfilled,
- quantity_returned,
- quantity_awaiting_approval,
- ) = _calculate_quantity_including_returns(locked_order)
-
- all_products_replaced = total_quantity == 0
- if all_products_replaced:
- return
- status = determine_order_status(
- total_quantity,
- quantity_fulfilled,
- quantity_returned,
- quantity_awaiting_approval,
- )
+ status_updated = refresh_order_status(locked_order)
# we would like to update the status for the order provided as the argument
# to ensure that the reference order has up to date status
- if status != order.status:
- order.status = status
- order.save(update_fields=["status", "updated_at"])
+ if status_updated:
+ # We need to update the order status in original order object to ensure that
+ # the status is updated in the mutation response.
+ order.status = locked_order.status
+ locked_order.save(update_fields=["status", "updated_at"])
def determine_order_status(