Skip to content

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

Fix order.chargeStatus calculated incorrectly (#14538)

Maciej Korycinskia8a3ccf92d83
diff --git a/saleor/graphql/order/mutations/order_grant_refund_create.py b/saleor/graphql/order/mutations/order_grant_refund_create.py
index 6572144ee4..e23dd2b2fc 100644
--- a/saleor/graphql/order/mutations/order_grant_refund_create.py
+++ b/saleor/graphql/order/mutations/order_grant_refund_create.py
@@ -6,6 +6,7 @@ from django.core.exceptions import ValidationError
from django.db import transaction
from ....order import models
+from ....order.utils import update_order_charge_data
from ....permission.enums import OrderPermissions
from ...core import ResolveInfo
from ...core.descriptions import ADDED_IN_313, ADDED_IN_315, PREVIEW_FEATURE
@@ -248,5 +249,6 @@ class OrderGrantRefundCreate(BaseMutation):
for line in cleaned_input_lines:
line.granted_refund = granted_refund
models.OrderGrantedRefundLine.objects.bulk_create(cleaned_input_lines)
+ update_order_charge_data(order)
return cls(order=order, granted_refund=granted_refund)
diff --git a/saleor/graphql/order/mutations/order_grant_refund_update.py b/saleor/graphql/order/mutations/order_grant_refund_update.py
index e86b40243b..0881a4a514 100644
--- a/saleor/graphql/order/mutations/order_grant_refund_update.py
+++ b/saleor/graphql/order/mutations/order_grant_refund_update.py
@@ -6,6 +6,7 @@ from django.db import transaction
from graphql import GraphQLError
from ....order import models
+from ....order.utils import update_order_charge_data
from ....permission.enums import OrderPermissions
from ...core import ResolveInfo
from ...core.descriptions import ADDED_IN_313, ADDED_IN_315, PREVIEW_FEATURE
@@ -333,4 +334,5 @@ class OrderGrantRefundUpdate(BaseMutation):
cleaned_input = cls.clean_input(granted_refund, input)
cls.process_update_for_granted_refund(order, granted_refund, cleaned_input)
+ update_order_charge_data(order)
return cls(order=order, granted_refund=granted_refund)
diff --git a/saleor/graphql/order/tests/mutations/test_order_grant_refund_create.py b/saleor/graphql/order/tests/mutations/test_order_grant_refund_create.py
index cb29a56d40..49f90b9a6f 100644
--- a/saleor/graphql/order/tests/mutations/test_order_grant_refund_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_grant_refund_create.py
@@ -2,11 +2,12 @@ from decimal import Decimal
import graphene
-from saleor.core.prices import quantize_price
-
+from .....core.prices import quantize_price
+from .....order.utils import update_order_charge_data
from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
from ...enums import (
+ OrderChargeStatusEnum,
OrderGrantRefundCreateErrorCode,
OrderGrantRefundCreateLineErrorCode,
)
@@ -42,6 +43,7 @@ mutation OrderGrantRefundCreate(
}
order{
id
+ chargeStatus
grantedRefunds{
id
amount{
@@ -97,7 +99,6 @@ def test_grant_refund_by_user(staff_api_client, permission_manage_orders, order)
response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
# then
-
content = get_graphql_content(response)
data = content["data"]["orderGrantRefundCreate"]
errors = data["errors"]
@@ -684,3 +685,39 @@ def test_grant_refund_with_lines_and_existing_other_grant_and_refund_exceeding_q
line["code"]
== OrderGrantRefundCreateLineErrorCode.QUANTITY_GREATER_THAN_AVAILABLE.name
)
+
+
+def test_grant_refund_updates_order_charge_status(
+ staff_api_client, permission_manage_orders, order_with_lines
+):
+ # given
+ order = order_with_lines
+ order_id = to_global_id_or_none(order)
+ order.payment_transactions.create(
+ charged_value=order.total.gross.amount,
+ authorized_value=Decimal(12),
+ currency=order_with_lines.currency,
+ )
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ amount = Decimal("10.00")
+ reason = "Granted refund reason."
+ variables = {
+ "id": order_id,
+ "input": {"amount": amount, "reason": reason},
+ }
+ update_order_charge_data(order)
+ assert order.charge_status == OrderChargeStatusEnum.FULL.value
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ errors = data["errors"]
+ assert not errors
+
+ assert order_id == data["order"]["id"]
+ assert len(data["order"]["grantedRefunds"]) == 1
+
+ assert data["order"]["chargeStatus"] == OrderChargeStatusEnum.OVERCHARGED.name
diff --git a/saleor/graphql/order/tests/mutations/test_order_grant_refund_update.py b/saleor/graphql/order/tests/mutations/test_order_grant_refund_update.py
index 27e4aa2f64..4108576110 100644
--- a/saleor/graphql/order/tests/mutations/test_order_grant_refund_update.py
+++ b/saleor/graphql/order/tests/mutations/test_order_grant_refund_update.py
@@ -1,7 +1,7 @@
from decimal import Decimal
-from saleor.core.prices import quantize_price
-
+from .....core.prices import quantize_price
+from .....order.utils import update_order_charge_data
from ....core.utils import to_global_id_or_none
from ....tests.utils import (
assert_no_permission,
@@ -9,6 +9,7 @@ from ....tests.utils import (
get_graphql_content_from_response,
)
from ...enums import (
+ OrderChargeStatusEnum,
OrderGrantRefundUpdateErrorCode,
OrderGrantRefundUpdateLineErrorCode,
)
@@ -1156,3 +1157,53 @@ def test_grant_refund_update_with_shipping_cost_already_included(
== OrderGrantRefundUpdateErrorCode.SHIPPING_COSTS_ALREADY_GRANTED.name
)
assert len(granted_refund.lines.all()) == 0
+
+
+def test_grant_refund_updates_order_charge_status(
+ staff_api_client, app, permission_manage_orders, order_with_lines
+):
+ # given
+ order = order_with_lines
+ new_granted_refund_amount = Decimal("5.00")
+ order.payment_transactions.create(
+ charged_value=order.total.gross.amount - new_granted_refund_amount,
+ authorized_value=Decimal(12),
+ currency=order_with_lines.currency,
+ )
+ current_reason = "Granted refund reason."
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ app=app,
+ )
+
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": new_granted_refund_amount,
+ },
+ }
+ update_order_charge_data(order)
+
+ # overcharged as total(98.40) - current grantedRefund(10.00) is less than
+ # total charged(98.40 - 5.00)
+ assert order.charge_status == OrderChargeStatusEnum.OVERCHARGED.value
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # then
+ order.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ assert not data["errors"]
+
+ assert data["order"]["id"] == to_global_id_or_none(order)
+ assert len(data["order"]["grantedRefunds"]) == 1
+
+ assert order.charge_status == OrderChargeStatusEnum.FULL.value
diff --git a/saleor/order/migrations/0165_fix_order_charge_status_with_transactions.py b/saleor/order/migrations/0165_fix_order_charge_status_with_transactions.py
new file mode 100644
index 0000000000..839b8ac38c
--- /dev/null
+++ b/saleor/order/migrations/0165_fix_order_charge_status_with_transactions.py
@@ -0,0 +1,99 @@
+from decimal import Decimal
+
+from babel.numbers import get_currency_precision
+from django.db import migrations
+from django.db.models.expressions import Exists, OuterRef
+
+
+def quantize_price(price, currency: str):
+ precision = get_currency_precision(currency)
+ number_places = Decimal(10) ** -precision
+ return price.quantize(number_places)
+
+
+def update_order_charge_status(order, granted_refund_amount):
+ """Update the current charge status for the order.
+
+ We treat the order as overcharged when the charged amount is bigger that
+ order.total - order granted refund
+ We treat the order as fully charged when the charged amount is equal to
+ order.total - order granted refund.
+ We treat the order as partially charged when the charged amount covers only part of
+ the order.total - order granted refund
+ We treat the order as not charged when the charged amount is 0.
+ """
+ total_charged = order.total_charged_amount or Decimal("0")
+ total_charged = quantize_price(total_charged, order.currency)
+
+ current_total_gross = order.total_gross_amount - granted_refund_amount
+ current_total_gross = max(current_total_gross, Decimal("0"))
+ current_total_gross = quantize_price(current_total_gross, order.currency)
+
+ if total_charged == current_total_gross:
+ order.charge_status = "full"
+ elif total_charged <= Decimal(0):
+ order.charge_status = "none"
+ elif total_charged < current_total_gross:
+ order.charge_status = "partial"
+ else:
+ order.charge_status = "overcharged"
+
+
+def update_orders_charge_statuses_task(Order, OrderGrantedRefund, number=0):
+ """Update the charge status for orders with granted refunds.
+
+ Task takes around 0.3 seconds for 1000 orders and around 5 MB of memory.
+ """
+ batch_size = 1000
+ orders = (
+ Order.objects.order_by("number")
+ .filter(
+ Exists(
+ OrderGrantedRefund.objects.filter(
+ order_id=OuterRef("pk"),
+ )
+ ),
+ number__gt=number,
+ )
+ .prefetch_related("granted_refunds")[:batch_size]
+ )
+
+ orders_to_update = []
+ last_number = number
+ for o in orders:
+ granted_refund_amount = sum(
+ [refund.amount_value for refund in o.granted_refunds.all()], Decimal(0)
+ )
+ update_order_charge_status(o, granted_refund_amount)
+ orders_to_update.append(o)
+
+ if orders_to_update:
+ last_number = orders_to_update[-1].number
+ Order.objects.bulk_update(orders_to_update, ["charge_status"])
+
+ return last_number, orders_to_update
+
+
+def update_orders_charge_statuses(apps, schema_editor):
+ Order = apps.get_model("order", "Order")
+ OrderGrantedRefund = apps.get_model("order", "OrderGrantedRefund")
+
+ number = 0
+ while True:
+ last_number, orders_to_update = update_orders_charge_statuses_task(
+ Order, OrderGrantedRefund, number=number
+ )
+ number = last_number
+ if not orders_to_update:
+ break
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0164_auto_20230329_1200"),
+ ]
+ operations = [
+ migrations.RunPython(
+ update_orders_charge_statuses, reverse_code=migrations.RunPython.noop
+ ),
+ ]
diff --git a/saleor/order/migrations/0170_merge_20231030_0857.py b/saleor/order/migrations/0170_merge_20231030_0857.py
new file mode 100644
index 0000000000..9d6f0a3be0
--- /dev/null
+++ b/saleor/order/migrations/0170_merge_20231030_0857.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.22 on 2023-10-30 08:57
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0165_fix_order_charge_status_with_transactions"),
+ ("order", "0169_alter_order_options"),
+ ]
+
+ operations = []
diff --git a/saleor/order/migrations/0174_merge_20231030_1033.py b/saleor/order/migrations/0174_merge_20231030_1033.py
new file mode 100644
index 0000000000..334301ff61
--- /dev/null
+++ b/saleor/order/migrations/0174_merge_20231030_1033.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.22 on 2023-10-30 10:33
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0170_merge_20231030_0857"),
+ ("order", "0173_auto_20230816_1245"),
+ ]
+
+ operations = []
diff --git a/saleor/order/migrations/0175_merge_20231030_1040.py b/saleor/order/migrations/0175_merge_20231030_1040.py
new file mode 100644
index 0000000000..bb639d8f44
--- /dev/null
+++ b/saleor/order/migrations/0175_merge_20231030_1040.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.22 on 2023-10-30 10:40
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0174_merge_20231030_1033"),
+ ("order", "0174_order_idx_order_created_at"),
+ ]
+
+ operations = []
diff --git a/saleor/order/migrations/0178_merge_20231030_1055.py b/saleor/order/migrations/0178_merge_20231030_1055.py
new file mode 100644
index 0000000000..a1e52f828c
--- /dev/null
+++ b/saleor/order/migrations/0178_merge_20231030_1055.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.22 on 2023-10-30 10:55
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0175_merge_20231030_1040"),
+ ("order", "0177_set_order_voucher_code"),
+ ]
+
+ operations = []
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index 473eebe109..d55b536a15 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -29,7 +29,7 @@ from ...tests.fixtures import recalculate_order
from ...warehouse import WarehouseClickAndCollectOption
from ...warehouse.models import Stock, Warehouse
from ...warehouse.tests.utils import get_quantity_allocated_for_stock
-from .. import FulfillmentStatus, OrderEvents, OrderStatus
+from .. import FulfillmentStatus, OrderChargeStatus, OrderEvents, OrderStatus
from ..calculations import fetch_order_prices_if_expired
from ..events import (
OrderEventsEmails,
@@ -1548,3 +1548,56 @@ def test_add_variant_to_order_adds_translations_in_order_language(
== get_translation(variant.product, language_code).name
)
assert line.translated_variant_name == get_translation(variant, language_code).name
+
+
+ ("granted_refund_amount", "charged_amount", "expected_charge_status"),
+ [
+ # granted refund contains part of the order's total, charge amount is 0
+ (Decimal("10.40"), Decimal("0"), OrderChargeStatus.NONE),
+ # granted refund covers the whole order's total, charge amount is 0
+ # status is FULL, as the order total - granted refund amount is 0.
+ # It means that a charge amount equal to 0 fully covers the order total (0)
+ (Decimal("98.40"), Decimal("0"), OrderChargeStatus.FULL),
+ (Decimal("0"), Decimal("0"), OrderChargeStatus.NONE),
+ (Decimal("0"), Decimal("11.00"), OrderChargeStatus.PARTIAL),
+ (Decimal("4"), Decimal("11.00"), OrderChargeStatus.PARTIAL),
+ # granted refund covers 88.40 of total, which is 98.40. Charge amount is 10.
+ # status is FULL, as the order total - granted refund amount is 10.
+ (Decimal("88.40"), Decimal("10.00"), OrderChargeStatus.FULL),
+ (Decimal("0"), Decimal("98.40"), OrderChargeStatus.FULL),
+ # granted refund covers 88.40 of total, which is 98.40. Charge amount is 98.40.
+ # status is OVERCHARGED as the charge amount is greater than the order
+ # total - granted refund amount
+ (Decimal("88.40"), Decimal("98.40"), OrderChargeStatus.OVERCHARGED),
+ ],
+)
+def test_order_update_charge_status_with_transaction_item_and_granted_refund(
+ granted_refund_amount,
+ charged_amount,
+ expected_charge_status,
+ order_with_lines,
+ staff_user,
+):
+ # given
+ assert order_with_lines.total.gross.amount == Decimal("98.40")
+ order_with_lines.payment_transactions.create(
+ charged_value=charged_amount,
+ authorized_value=Decimal(12),
+ currency=order_with_lines.currency,
+ )
+
+ order_with_lines.granted_refunds.create(
+ amount_value=granted_refund_amount,
+ currency="USD",
+ reason="Test reason",
+ user=staff_user,
+ )
+
+ # when
+ update_order_charge_data(order_with_lines)
+
+ # then
+ order_with_lines.refresh_from_db()
+
+ assert order_with_lines.charge_status == expected_charge_status
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index e03d46ad02..76efcd7a16 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -913,9 +913,7 @@ def update_order_charge_status(order: Order, granted_refund_amount: Decimal):
current_total_gross = order.total_gross_amount - granted_refund_amount
current_total_gross = max(current_total_gross, Decimal("0"))
- current_total_gross = quantize_price(
- current_total_gross - granted_refund_amount, order.currency
- )
+ current_total_gross = quantize_price(current_total_gross, order.currency)
if total_charged == current_total_gross:
order.charge_status = OrderChargeStatus.FULL
@@ -933,8 +931,8 @@ def _update_order_total_charged(
order_transactions: Iterable["TransactionItem"],
):
order.total_charged_amount = sum(
- order_payments.values_list("captured_amount", flat=True)
- ) or Decimal(0)
+ [p.captured_amount for p in order_payments], Decimal(0)
+ )
order.total_charged_amount += sum([tr.charged_value for tr in order_transactions])
@@ -952,7 +950,7 @@ def update_order_charge_data(
if order_granted_refunds is None:
order_granted_refunds = order.granted_refunds.all()
granted_refund_amount = sum(
- [refund.amount.amount for refund in order_granted_refunds]
+ [refund.amount.amount for refund in order_granted_refunds], Decimal(0)
)
_update_order_total_charged(
order, order_payments=order_payments, order_transactions=order_transactions