Skip to content

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

Fix logic for subtracting gift cards value from checkout total. Subtract (#17926)

Marcin Wcisło9e1838c9eb0b
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 0cd3b01a2c..ebbcea119d 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -146,9 +146,26 @@ def calculate_checkout_total_with_gift_cards(
pregenerated_subscription_payloads=pregenerated_subscription_payloads,
force_update=force_update,
allow_sync_webhooks=allow_sync_webhooks,
- ) - checkout_info.checkout.get_total_gift_cards_balance(database_connection_name)
+ )
+
+ if total == zero_taxed_money(total.currency):
+ return total
+
+ # Calculate how many percent of total net value the total gross value is.
+ gross_percentage = total.gross / total.net
+
+ # Subtract gift cards value from total gross value.
+ total.gross -= checkout_info.checkout.get_total_gift_cards_balance(
+ database_connection_name
+ )
+
+ # Gross value cannot be below zero.
+ total.gross = max(total.gross, zero_money(total.currency))
+
+ # Adjusted total net value is proportional to potentially reduced total gross value.
+ total.net = quantize_price(total.gross / gross_percentage, total.currency)
- return max(total, zero_taxed_money(total.currency))
+ return total
def checkout_total(
diff --git a/saleor/order/migrations/0197_fix_negative_total_net_for_orders_using_gift_cards.py b/saleor/order/migrations/0197_fix_negative_total_net_for_orders_using_gift_cards.py
new file mode 100644
index 0000000000..23c407cafd
--- /dev/null
+++ b/saleor/order/migrations/0197_fix_negative_total_net_for_orders_using_gift_cards.py
@@ -0,0 +1,51 @@
+# Generated by Django 4.2.15 on 2025-07-02 11:39
+
+import uuid
+from decimal import Decimal
+
+from django.db import migrations, transaction
+
+
+def fix_negative_total_net_for_orders_using_gift_cards(apps, _schema_editor):
+ Order = apps.get_model("order", "Order")
+ # No memory usage tests were conducted here.
+ # It's assumed that loading 500 identifiers to memory is not straining the memory
+ # usage.
+
+ BATCH_SIZE = 500
+ start_pk = uuid.UUID("00000000-0000-0000-0000-000000000000")
+ while True:
+ with transaction.atomic():
+ # Following select query has been tested on database with 4.2m actual orders, it took ~5s.
+ order_pks = list(
+ Order.objects.filter(
+ pk__gt=start_pk,
+ total_net_amount__lt=Decimal("0.00"),
+ )
+ .exclude(gift_cards=None)
+ .order_by("pk")
+ .select_for_update()
+ .values_list("pk", flat=True)[:BATCH_SIZE]
+ )
+
+ if not order_pks:
+ break
+
+ Order.objects.filter(
+ pk__in=order_pks,
+ ).update(total_net_amount=Decimal("0.00"))
+
+ start_pk = order_pks[-1]
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0196_alter_fulfillment_shipping_refund_amount_and_more"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ fix_negative_total_net_for_orders_using_gift_cards,
+ reverse_code=migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/order/migrations/0205_merge_20250703_1438.py b/saleor/order/migrations/0205_merge_20250703_1438.py
new file mode 100644
index 0000000000..a17c31a066
--- /dev/null
+++ b/saleor/order/migrations/0205_merge_20250703_1438.py
@@ -0,0 +1,12 @@
+# Generated by Django 4.2.20 on 2025-07-03 14:38
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0197_fix_negative_total_net_for_orders_using_gift_cards"),
+ ("order", "0204_set_order_lines_count"),
+ ]
+
+ operations = []
diff --git a/saleor/order/migrations/0216_merge_20250704_1033.py b/saleor/order/migrations/0216_merge_20250704_1033.py
new file mode 100644
index 0000000000..f2ab8a15b5
--- /dev/null
+++ b/saleor/order/migrations/0216_merge_20250704_1033.py
@@ -0,0 +1,12 @@
+# Generated by Django 5.2.1 on 2025-07-04 10:33
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0205_merge_20250703_1438"),
+ ("order", "0215_merge_20250623_0624"),
+ ]
+
+ operations = []
diff --git a/saleor/order/tests/fixtures/order.py b/saleor/order/tests/fixtures/order.py
index 88b8dd3d7a..8976eea549 100644
--- a/saleor/order/tests/fixtures/order.py
+++ b/saleor/order/tests/fixtures/order.py
@@ -231,6 +231,12 @@ def order(order_generator):
return order_generator()
+def order_with_gift_card(order, gift_card):
+ order.gift_cards.add(gift_card)
+ return order
+
+
@pytest.fixture
def order_unconfirmed(order):
order.status = OrderStatus.UNCONFIRMED
diff --git a/saleor/tax/tests/test_checkout_calculations.py b/saleor/tax/tests/test_checkout_calculations.py
index 6bffaa4a5f..2c756db7bd 100644
--- a/saleor/tax/tests/test_checkout_calculations.py
+++ b/saleor/tax/tests/test_checkout_calculations.py
@@ -1,8 +1,10 @@
from decimal import Decimal
+from unittest import mock
import pytest
from prices import Money, TaxedMoney
+from ...checkout import calculations
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...checkout.utils import add_variant_to_checkout
from ...core.prices import quantize_price
@@ -32,6 +34,64 @@ def _enable_flat_rates(
tc.save()
+ (
+ "checkout_total_net",
+ "checkout_total_gross",
+ "gift_card_balance",
+ "expected_total_net",
+ "expected_total_gross",
+ ),
+ [
+ ("0.00", "0.00", "0.00", "0.00", "0.00"),
+ ("0.00", "0.00", "10.00", "0.00", "0.00"),
+ ("10.00", "10.00", "5.00", "5.00", "5.00"), # tax rate = 0%
+ ("10.00", "10.00", "10.00", "0.00", "0.00"), # tax rate = 0%
+ ("10.00", "12.00", "10.00", "1.67", "2.00"), # tax rate = 20%
+ ("10.00", "12.00", "12.00", "0.00", "0.00"), # tax rate = 20%
+ ("30.00", "36.00", "12.00", "20", "24.00"), # tax rate = 20%
+ ],
+)
[email protected]("saleor.checkout.calculations.checkout_total")
+def test_calculate_checkout_total_with_gift_cards(
+ checkout_total_mock,
+ checkout_total_net,
+ checkout_total_gross,
+ gift_card_balance,
+ expected_total_net,
+ expected_total_gross,
+ gift_card,
+ checkout_with_gift_card,
+ address,
+):
+ assert not gift_card.last_used_on
+ gift_card.current_balance_amount = Decimal(gift_card_balance)
+ gift_card.save(update_fields=["current_balance_amount"])
+
+ checkout = checkout_with_gift_card
+ checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
+ checkout.metadata_storage.store_value_in_private_metadata(
+ items={"accepted": "false"}
+ )
+ checkout.save()
+ checkout.metadata_storage.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ checkout_total_mock.return_value = TaxedMoney(
+ net=Money(checkout_total_net, "USD"), gross=Money(checkout_total_gross, "USD")
+ )
+
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+
+ assert total.net == Money(expected_total_net, "USD")
+ assert total.gross == Money(expected_total_gross, "USD")
+
+
@pytest.mark.parametrize(
(
"expected_net",