Skip to content

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

Refresh order charge and authorize statuses when prices are recalculated (#19766)

Lukasz Ostrowski80205e99997f
diff --git a/saleor/graphql/order/tests/integration/test_draft_order.py b/saleor/graphql/order/tests/integration/test_draft_order.py
index cea9a9003a..2bd5a11298 100644
--- a/saleor/graphql/order/tests/integration/test_draft_order.py
+++ b/saleor/graphql/order/tests/integration/test_draft_order.py
@@ -1,10 +1,16 @@
+from decimal import Decimal
+from unittest import mock
+
import graphene
import pytest
from .....order import OrderStatus
+from .....payment import TransactionEventType
+from .....payment.interface import TransactionSessionResult
from ....account.tests.mutations.permission_group.test_permission_group_update import (
PERMISSION_GROUP_UPDATE_MUTATION,
)
+from ....order.enums import OrderChargeStatusEnum
from ....tests.utils import assert_no_permission, get_graphql_content
from ..mutations.test_draft_order_complete import DRAFT_ORDER_COMPLETE_MUTATION
from ..mutations.test_draft_order_create import DRAFT_ORDER_CREATE_MUTATION
@@ -156,3 +162,231 @@ def test_user_cannot_manage_draft_order_after_losing_access_to_channel(
# then
assert_no_permission(response)
+
+
+DRAFT_ORDER_CREATE = """
+mutation draftOrderCreate($input: DraftOrderCreateInput!) {
+ draftOrderCreate(input: $input) {
+ errors { field code message }
+ order { id }
+ }
+}
+"""
+
+ORDER_LINES_CREATE = """
+mutation orderLinesCreate($id: ID!, $input: [OrderLineCreateInput!]!) {
+ orderLinesCreate(id: $id, input: $input) {
+ errors { field code message }
+ orderLines { id }
+ }
+}
+"""
+
+ORDER_LINE_DELETE = """
+mutation orderLineDelete($id: ID!) {
+ orderLineDelete(id: $id) {
+ errors { field code message }
+ }
+}
+"""
+
+DRAFT_ORDER_UPDATE_ADDRESSES = """
+mutation draftOrderUpdate($id: ID!, $input: DraftOrderInput!) {
+ draftOrderUpdate(id: $id, input: $input) {
+ errors { field code message }
+ }
+}
+"""
+
+ORDER_UPDATE_SHIPPING = """
+mutation orderUpdateShipping($order: ID!, $input: OrderUpdateShippingInput!) {
+ orderUpdateShipping(order: $order, input: $input) {
+ errors { field code message }
+ }
+}
+"""
+
+TRANSACTION_INITIALIZE = """
+mutation transactionInitialize(
+ $id: ID!, $amount: PositiveDecimal!, $paymentGateway: PaymentGatewayToInitialize!
+) {
+ transactionInitialize(id: $id, amount: $amount, paymentGateway: $paymentGateway) {
+ errors { field code message }
+ transaction { id chargedAmount { amount } }
+ }
+}
+"""
+
+ORDER_TOTAL_QUERY = """
+query order($id: ID!) {
+ order(id: $id) {
+ total { gross { amount } }
+ }
+}
+"""
+
+ORDER_CHARGE_STATUS_QUERY = """
+query order($id: ID!) {
+ order(id: $id) {
+ chargeStatus
+ }
+}
+"""
+
+DRAFT_ORDER_COMPLETE = """
+mutation draftOrderComplete($id: ID!) {
+ draftOrderComplete(id: $id) {
+ errors { field code message }
+ order { id chargeStatus total { gross { amount } } }
+ }
+}
+"""
+
+
+def _create_order_line(api_client, order_id, variant_id, quantity):
+ response = api_client.post_graphql(
+ ORDER_LINES_CREATE,
+ {
+ "id": order_id,
+ "input": [{"variantId": variant_id, "quantity": quantity}],
+ },
+ )
+ data = get_graphql_content(response)["data"]["orderLinesCreate"]
+ assert data["errors"] == []
+ return data["orderLines"][0]["id"]
+
+
+def _set_shipping_method(api_client, order_id, shipping_method):
+ response = api_client.post_graphql(
+ ORDER_UPDATE_SHIPPING,
+ {
+ "order": order_id,
+ "input": {
+ "shippingMethod": graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ },
+ },
+ )
+ assert get_graphql_content(response)["data"]["orderUpdateShipping"]["errors"] == []
+
+
+def _fetch_total(api_client, order_id):
+ """Read the order total, which also persists the recalculated prices."""
+ response = api_client.post_graphql(ORDER_TOTAL_QUERY, {"id": order_id})
+ order_data = get_graphql_content(response)["data"]["order"]
+ return Decimal(str(order_data["total"]["gross"]["amount"]))
+
+
+def _fetch_charge_status(api_client, order_id):
+ response = api_client.post_graphql(ORDER_CHARGE_STATUS_QUERY, {"id": order_id})
+ return get_graphql_content(response)["data"]["order"]["chargeStatus"]
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_draft_order_charge_status_when_total_changes_after_the_order_is_charged(
+ mocked_initialize,
+ staff_api_client,
+ user_api_client,
+ permission_group_manage_orders,
+ channel_USD,
+ product,
+ shipping_method,
+ graphql_address_data,
+ webhook_app,
+ transaction_session_response,
+):
+ """Charge status calculated against a stale draft total is refreshed on complete.
+
+ A draft order is charged for the total the customer was shown, while the order
+ total stored in the database is lower, as the lines have been changed in the
+ meantime. The charge status calculated at that point is `OVERCHARGED`, and the
+ completion recalculation, which brings the total back to the charged amount, has
+ to refresh it.
+ """
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ variant_id = graphene.Node.to_global_id(
+ "ProductVariant", product.variants.first().pk
+ )
+ app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = app_identifier
+ webhook_app.save(update_fields=["identifier"])
+
+ # when
+ # create an empty draft order
+ response = staff_api_client.post_graphql(
+ DRAFT_ORDER_CREATE,
+ {
+ "input": {
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ "userEmail": "[email protected]",
+ }
+ },
+ )
+ data = get_graphql_content(response)["data"]["draftOrderCreate"]
+ assert data["errors"] == []
+ order_id = data["order"]["id"]
+
+ # add the lines, the addresses and the shipping method
+ line_id = _create_order_line(staff_api_client, order_id, variant_id, quantity=2)
+ response = staff_api_client.post_graphql(
+ DRAFT_ORDER_UPDATE_ADDRESSES,
+ {
+ "id": order_id,
+ "input": {
+ "shippingAddress": graphql_address_data,
+ "billingAddress": graphql_address_data,
+ },
+ },
+ )
+ assert get_graphql_content(response)["data"]["draftOrderUpdate"]["errors"] == []
+ _set_shipping_method(staff_api_client, order_id, shipping_method)
+
+ # the total the customer is charged for
+ amount_to_charge = _fetch_total(staff_api_client, order_id)
+
+ # drop the line, so that the stored total no longer covers the charged amount
+ response = staff_api_client.post_graphql(ORDER_LINE_DELETE, {"id": line_id})
+ assert get_graphql_content(response)["data"]["orderLineDelete"]["errors"] == []
+ assert _fetch_total(staff_api_client, order_id) < amount_to_charge
+
+ # charge the order for the amount the customer was shown
+ gateway_response = transaction_session_response.copy()
+ gateway_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ gateway_response["amount"] = str(amount_to_charge)
+ mocked_initialize.return_value = TransactionSessionResult(
+ app_identifier=app_identifier, response=gateway_response
+ )
+ response = user_api_client.post_graphql(
+ TRANSACTION_INITIALIZE,
+ {
+ "id": order_id,
+ "amount": amount_to_charge,
+ "paymentGateway": {"id": app_identifier, "data": None},
+ },
+ )
+ transaction_data = get_graphql_content(response)["data"]["transactionInitialize"]
+ assert transaction_data["errors"] == []
+ assert (
+ Decimal(str(transaction_data["transaction"]["chargedAmount"]["amount"]))
+ == amount_to_charge
+ )
+
+ assert (
+ _fetch_charge_status(staff_api_client, order_id)
+ == OrderChargeStatusEnum.OVERCHARGED.name
+ )
+
+ # bring the line and the shipping method back, so that the order total matches
+ # the charged amount again
+ _create_order_line(staff_api_client, order_id, variant_id, quantity=2)
+ _set_shipping_method(staff_api_client, order_id, shipping_method)
+
+ # then
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE, {"id": order_id})
+ data = get_graphql_content(response)["data"]["draftOrderComplete"]
+ assert data["errors"] == []
+ assert Decimal(str(data["order"]["total"]["gross"]["amount"])) == amount_to_charge
+ assert data["order"]["chargeStatus"] == OrderChargeStatusEnum.FULL.name
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index 6be59fdd05..445af396f1 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -58,6 +58,7 @@ from .utils import (
calculate_draft_order_line_price_expiration_date,
log_address_if_validation_skipped_for_order,
order_info_for_logs,
+ updates_amounts_for_order,
)
if TYPE_CHECKING:
@@ -138,22 +139,36 @@ def process_order_prices(
# to avoid overwriting changes made by the other requests. Skipping the save function does not affect
# the query response because it returns the adjusted order and line info objects.
if locked_order.updated_at == order.updated_at:
- order.save(
- update_fields=[
- "subtotal_net_amount",
- "subtotal_gross_amount",
- "total_net_amount",
- "total_gross_amount",
- "undiscounted_total_net_amount",
- "undiscounted_total_gross_amount",
- "shipping_price_net_amount",
- "shipping_price_gross_amount",
- "base_shipping_price_amount",
- "shipping_tax_rate",
- "should_refresh_prices",
- "tax_error",
- ]
- )
+ update_fields = [
+ "subtotal_net_amount",
+ "subtotal_gross_amount",
+ "total_net_amount",
+ "total_gross_amount",
+ "undiscounted_total_net_amount",
+ "undiscounted_total_gross_amount",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "base_shipping_price_amount",
+ "shipping_tax_rate",
+ "should_refresh_prices",
+ "tax_error",
+ ]
+ if order.total_charged_amount or order.total_authorized_amount:
+ # Charge and authorize statuses are derived from the order
+ # total, so an order that has funds attached needs them
+ # refreshed together with it. The `updated_at` check above
+ # guarantees that the charged and authorized amounts have not
+ # been modified by another process in the meantime.
+ updates_amounts_for_order(order, save=False)
+ update_fields.extend(
+ [
+ "total_charged_amount",
+ "charge_status",
+ "total_authorized_amount",
+ "authorize_status",
+ ]
+ )
+ order.save(update_fields=update_fields)
order.lines.bulk_update(
lines,
[
diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.py
index dbd2ac5268..91d088ec0f 100644
--- a/saleor/order/tests/test_calculations.py
+++ b/saleor/order/tests/test_calculations.py
@@ -19,7 +19,8 @@ from ...core.taxes import (
)
from ...discount import DiscountValueType
from ...graphql.core.utils import to_global_id_or_none
-from ...order.utils import get_order_country
+from ...order.utils import get_order_country, updates_amounts_for_order
+from ...payment.models import TransactionItem
from ...plugins import PLUGIN_IDENTIFIER_PREFIX
from ...plugins.avatax.plugin import DeprecatedAvataxPlugin
from ...plugins.avatax.tests.conftest import plugin_configuration # noqa: F401
@@ -29,7 +30,7 @@ from ...tax import TaxCalculationStrategy
from ...tax.calculations.order import update_order_prices_with_flat_rates
from ...tax.utils import get_tax_calculation_strategy_for_order
from ...tests import race_condition
-from .. import OrderStatus, calculations
+from .. import OrderChargeStatus, OrderStatus, calculations
from ..calculations import logger
from ..interface import OrderTaxedPricesData
from ..models import Order
@@ -1995,3 +1996,78 @@ def test_fetch_order_prices_if_expired_order_updated_during_price_recalculation(
assert order.should_refresh_prices is True
assert order.updated_at > updated_at_before_recalculation
assert order.customer_note == expected_note
+
+
+ (
+ "_case",
+ "stale_total_offset",
+ "charged_offset",
+ "initial_charge_status",
+ "expected_charge_status",
+ ),
+ [
+ (
+ "charged_more_than_the_stale_total_and_the_order_grows_to_match",
+ Decimal(-10),
+ Decimal(0),
+ OrderChargeStatus.OVERCHARGED,
+ OrderChargeStatus.FULL,
+ ),
+ (
+ "charged_the_stale_total_and_the_order_grows",
+ Decimal(-10),
+ Decimal(-10),
+ OrderChargeStatus.FULL,
+ OrderChargeStatus.PARTIAL,
+ ),
+ (
+ "charged_the_stale_total_and_the_order_shrinks",
+ Decimal(10),
+ Decimal(10),
+ OrderChargeStatus.FULL,
+ OrderChargeStatus.OVERCHARGED,
+ ),
+ ],
+)
+def test_fetch_order_prices_if_expired_refreshes_charge_status(
+ _case,
+ stale_total_offset,
+ charged_offset,
+ initial_charge_status,
+ expected_charge_status,
+ order_with_lines,
+ fetch_kwargs,
+):
+ """Charge status calculated against a stale total is refreshed with the prices."""
+ # given
+ order = order_with_lines
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
+ # `order_with_lines` here is only marked as unconfirmed in memory, so the refresh
+ # has to be narrowed down not to bring the non-editable status back
+ order.refresh_from_db(fields=("total_gross_amount",))
+ recalculated_total = order.total_gross_amount
+
+ TransactionItem.objects.create(
+ order=order,
+ currency=order.currency,
+ charged_value=recalculated_total + charged_offset,
+ )
+
+ # the stored total no longer matches the prices, the charge status is calculated
+ # against the stale value
+ order.total_gross_amount = recalculated_total + stale_total_offset
+ order.save(update_fields=["total_gross_amount"])
+ updates_amounts_for_order(order)
+ assert order.charge_status == initial_charge_status
+
+ order.should_refresh_prices = True
+ order.save(update_fields=["should_refresh_prices", "updated_at"])
+
+ # when
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
+
+ # then
+ order.refresh_from_db(fields=("total_gross_amount", "charge_status"))
+ assert order.total_gross_amount == recalculated_total
+ assert order.charge_status == expected_charge_status