Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Store order base prices in dedicated columns so a dropped tax calculation cannot leave untaxed totals (#19801) (#19806)
Marcin Wcisłoc69c56cae409
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1d2ac41653..37db715d43 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -78,5 +78,6 @@ All notable, unreleased changes to this project will be documented in this file.- Fixed migration `account.0103_create_default_customer_type` to respect `POPULATE_DEFAULTS`; the default customer type is no longer created when defaults are disabled, and the post-migration assignment task skips when none exists.- Fixed `appCreate` and `appUpdate` failing with an unhandled error when `permissions` was `null` or omitted. `appCreate` now creates an app with no permissions, and `appUpdate` leaves the app's existing permissions untouched. Passing an empty list to `appUpdate` still clears them.- Fixed the `set_user_search_document_values` data migration task failing with a statement timeout on large user tables.+- Fixed orders being completed with untaxed totals when a concurrent modification drops the tax calculation. The pre-tax prices used to qualify order promotions are now stored in dedicated `base_subtotal_amount` and `base_total_amount` columns instead of overwriting `subtotal` and `total`, and `draftOrderComplete` returns a `TAX_ERROR` instead of finalizing an order whose recalculated prices could not be stored because another process modified it in the meantime. Retrying the mutation succeeds.### Deprecationsdiff --git a/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_order.py b/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_order.pyindex 34f5fdc381..ac2b041dd6 100644--- a/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_order.py+++ b/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_order.py@@ -9,9 +9,9 @@ def test_fetch_promotion_rules_for_order(order, order_line_JPY, order_promotion_# givenrule = order_promotion_rule- order.subtotal_net_amount = 100- order.total_net_amount = 100- order.save(update_fields=["subtotal_net_amount", "total_net_amount"])+ order.base_subtotal_amount = 100+ order.base_total_amount = 100+ order.save(update_fields=["base_subtotal_amount", "base_total_amount"])# whenrules_per_promotion_id = fetch_promotion_rules_for_checkout_or_order(order)@@ -27,9 +27,9 @@ def test_fetch_promotion_rules_for_order_no_matching_rule(order_promotion_rule,):# given- order.subtotal_net_amount = 10- order.total_net_amount = 10- order.save(update_fields=["subtotal_net_amount", "total_net_amount"])+ order.base_subtotal_amount = 10+ order.base_total_amount = 10+ order.save(update_fields=["base_subtotal_amount", "base_total_amount"])# whenrules_per_promotion_id = fetch_promotion_rules_for_checkout_or_order(order)@@ -84,9 +84,9 @@ def test_fetch_promotion_rules_for_checkout_inner_or_operator(}rule.save(update_fields=["order_predicate"])- order.subtotal_net_amount = 100- order.total_net_amount = 100- order.save(update_fields=["subtotal_net_amount", "total_net_amount"])+ order.base_subtotal_amount = 100+ order.base_total_amount = 100+ order.save(update_fields=["base_subtotal_amount", "base_total_amount"])# whenrules_per_promotion_id = fetch_promotion_rules_for_checkout_or_order(order)diff --git a/saleor/discount/utils/order.py b/saleor/discount/utils/order.pyindex 1372091ec9..3b8b8e0db2 100644--- a/saleor/discount/utils/order.py+++ b/saleor/discount/utils/order.py@@ -6,7 +6,6 @@ from uuid import UUIDfrom django.conf import settingsfrom django.db import transactionfrom django.db.models import prefetch_related_objects-from prices import TaxedMoneyfrom ...channel.models import Channelfrom ...core.db.connection import allow_writer@@ -221,19 +220,26 @@ def _clear_prefetched_order_discounts(order):def _set_order_base_prices(order: Order, lines_info: list["EditableOrderLineInfo"]):- """Set base order prices that includes only catalogue discounts."""+ """Set base order prices that includes only catalogue discounts.++ The values are stored in their own `base_subtotal`/`base_total` fields, the way+ `Checkout` keeps them. Order promotions are qualified by a predicate evaluated in+ the database, so these pre-tax prices have to be persisted - but they must not be+ written to `subtotal`/`total`, which carry the taxes and are saved only once the+ tax calculation has finished.+ """lines = [line_info.line for line_info in lines_info]subtotal = base_order_subtotal(order, lines)shipping_price = order.undiscounted_base_shipping_pricetotal = subtotal + shipping_priceupdate_fields = []- if order.subtotal != TaxedMoney(net=subtotal, gross=subtotal):- order.subtotal = TaxedMoney(net=subtotal, gross=subtotal)- update_fields.extend(["subtotal_net_amount", "subtotal_gross_amount"])- if order.total != TaxedMoney(net=total, gross=total):- order.total = TaxedMoney(net=total, gross=total)- update_fields.extend(["total_net_amount", "total_gross_amount"])+ if order.base_subtotal != subtotal:+ order.base_subtotal = subtotal+ update_fields.append("base_subtotal_amount")+ if order.base_total != total:+ order.base_total = total+ update_fields.append("base_total_amount")if update_fields:with allow_writer():diff --git a/saleor/graphql/order/filters.py b/saleor/graphql/order/filters.pyindex d6e267fc8d..071bf5a52c 100644--- a/saleor/graphql/order/filters.py+++ b/saleor/graphql/order/filters.py@@ -1201,15 +1201,15 @@ class DraftOrderWhereInput(WhereInputObjectType):class OrderDiscountedObjectWhere(DiscountedObjectWhere):class Meta:model = Order- fields = ["subtotal_net_amount", "total_net_amount"]+ fields = ["base_subtotal_amount", "base_total_amount"]def filter_base_subtotal_price(self, queryset, name, value):currency = get_currency_from_filter_data(self.data)- return _filter_price(queryset, name, "subtotal_net_amount", value, currency)+ return _filter_price(queryset, name, "base_subtotal_amount", value, currency)def filter_base_total_price(self, queryset, name, value):currency = get_currency_from_filter_data(self.data)- return _filter_price(queryset, name, "total_net_amount", value, currency)+ return _filter_price(queryset, name, "base_total_amount", value, currency)def _filter_price(qs, _, field_name, value, currency):diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.pyindex e6da7869c1..9702db62c1 100644--- a/saleor/graphql/order/mutations/draft_order_complete.py+++ b/saleor/graphql/order/mutations/draft_order_complete.py@@ -140,6 +140,16 @@ class DraftOrderComplete(BaseMutation):"Configured Tax App returned invalid response.",code=OrderErrorCode.TAX_ERROR.value,)+ if order.should_refresh_prices:+ # The recalculation above did not store its result - the order was modified+ # by another process while the taxes were being calculated. Completing now+ # would finalize an order with the prices from before that modification,+ # and a completed order is no longer recalculated, so it could not be+ # corrected afterwards. Leaving it as a draft keeps it recalculable.+ raise ValidationError(+ "Order prices could not be recalculated. Please try again.",+ code=OrderErrorCode.TAX_ERROR.value,+ )cls.validate_order(order)country = get_order_country(order)diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.pyindex 017d8bcbb1..2baf0b0bbb 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py@@ -26,7 +26,7 @@ from .....order.actions import order_createdfrom .....order.calculations import fetch_order_prices_if_expiredfrom .....order.error_codes import OrderErrorCodefrom .....order.interface import OrderTaxedPricesData-from .....order.models import OrderEvent, OrderLine+from .....order.models import Order, OrderEvent, OrderLinefrom .....payment.model_helpers import get_subtotalfrom .....plugins import PLUGIN_IDENTIFIER_PREFIXfrom .....plugins.tests.sample_plugins import PluginSample@@ -2089,3 +2089,45 @@ def test_draft_order_complete_with_single_use_voucher(code_instance.refresh_from_db()assert not code_instance.is_active+++def test_draft_order_complete_is_rejected_when_recalculation_collides(+ staff_api_client,+ permission_group_manage_orders,+ draft_order,+):+ # given+ # Another process touches the order while its prices are being recalculated, so+ # the recalculated prices are not stored and the order keeps the ones from before+ # the change that made it need a recalculation.+ order = draft_order+ order.should_refresh_prices = True+ order.save(update_fields=["should_refresh_prices"])++ def touch_order_from_another_process(*args, **kwargs):+ Order.objects.filter(pk=order.pk).update(updated_at=timezone.now())++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ order_id = graphene.Node.to_global_id("Order", order.id)++ # when+ with race_condition.RunBefore(+ "saleor.order.calculations.calculate_taxes", touch_order_from_another_process+ ):+ response = staff_api_client.post_graphql(+ DRAFT_ORDER_COMPLETE_MUTATION, {"id": order_id}+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["draftOrderComplete"]["errors"]+ assert len(errors) == 1+ assert errors[0]["code"] == OrderErrorCode.TAX_ERROR.name+ assert errors[0]["message"] == (+ "Order prices could not be recalculated. Please try again."+ )+ # The order was not completed, so it stays recalculable instead of being frozen+ # with prices that carry no tax.+ order.refresh_from_db()+ assert order.status == OrderStatus.DRAFT+ assert order.should_refresh_prices is Truediff --git a/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py b/saleor/graphql/order/tests/queries/test_draft_order_with_filter.pyindex d02cf7bf98..8463f1ed08 100644--- a/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py+++ b/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py@@ -280,8 +280,8 @@ def test_draft_orders_query_with_filter_base_total_price_range(draft_order, gte,# givenorder = draft_ordercurrency = order.currency- order.total_net_amount = Decimal(20)- order.save(update_fields=["total_net_amount"])+ order.base_total_amount = Decimal(20)+ order.save(update_fields=["base_total_amount"])qs = Order.objects.all()predicate_data = {@@ -315,8 +315,8 @@ def test_draft_orders_query_with_filter_base_subtotal_price_range(# givenorder = draft_ordercurrency = order.currency- order.subtotal_net_amount = Decimal(20)- order.save(update_fields=["subtotal_net_amount"])+ order.base_subtotal_amount = Decimal(20)+ order.save(update_fields=["base_subtotal_amount"])qs = Order.objects.all()predicate_data = {@@ -352,8 +352,8 @@ def test_draft_orders_query_with_filter_base_total_price_one_of(# givenorder = draft_ordercurrency = order.currency- order.total_net_amount = Decimal(20)- order.save(update_fields=["total_net_amount"])+ order.base_total_amount = Decimal(20)+ order.save(update_fields=["base_total_amount"])qs = Order.objects.all()predicate_data = {@@ -385,8 +385,8 @@ def test_draft_orders_query_with_filter_base_subtotal_price_one_of(# givenorder = draft_ordercurrency = order.currency- order.subtotal_net_amount = Decimal(20)- order.save(update_fields=["subtotal_net_amount"])+ order.base_subtotal_amount = Decimal(20)+ order.save(update_fields=["base_subtotal_amount"])qs = Order.objects.all()predicate_data = {@@ -412,8 +412,8 @@ def test_draft_orders_query_with_filter_base_subtotal_price_one_of(def test_draft_orders_query_with_filter_base_total_price_missing_currency(draft_order):# givenorder = draft_order- order.total_net_amount = Decimal(20)- order.save(update_fields=["total_net_amount"])+ order.base_total_amount = Decimal(20)+ order.save(update_fields=["base_total_amount"])qs = Order.objects.all()predicate_data = {@@ -443,8 +443,8 @@ def test_draft_orders_query_with_filter_base_subtotal_price_missing_currency():# givenorder = draft_order- order.subtotal_net_amount = Decimal(20)- order.save(update_fields=["subtotal_net_amount"])+ order.base_subtotal_amount = Decimal(20)+ order.save(update_fields=["base_subtotal_amount"])qs = Order.objects.all()predicate_data = {@@ -473,8 +473,8 @@ def test_draft_orders_query_with_filter_price_with_and_or(draft_order):# givenorder = draft_ordercurrency = order.currency- order.total_net_amount = Decimal(20)- order.save(update_fields=["total_net_amount"])+ order.base_total_amount = Decimal(20)+ order.save(update_fields=["base_total_amount"])qs = Order.objects.all()predicate_data = {diff --git a/saleor/order/calculations.py b/saleor/order/calculations.pyindex 445af396f1..5665eca47f 100644--- a/saleor/order/calculations.py+++ b/saleor/order/calculations.py@@ -131,7 +131,8 @@ def process_order_prices(order_qs_select_for_update().only("updated_at").get(id=order.id))except Order.DoesNotExist:- # Order was removed. Return data without saving.+ # Order was removed. Return data without saving. There is no stored+ # order left to be inconsistent, so the in-memory flag stays cleared.return order, lines# Check whether the order has been modified during the recalculation process by another process.@@ -183,6 +184,12 @@ def process_order_prices("tax_rate",],)+ else:+ # The prices calculated here were not stored, so the order keeps+ # the ones from before the change that triggered this+ # recalculation. Mirror that into the instance the caller holds,+ # so it can tell that the stored prices are not the ones it got.+ order.should_refresh_prices = Truereturn order, lineswith allow_writer_for_default_connection(database_connection_name):diff --git a/saleor/order/migrations/0228_add_order_base_prices.py b/saleor/order/migrations/0228_add_order_base_prices.pynew file mode 100644index 0000000000..d87aa2e2a3--- /dev/null+++ b/saleor/order/migrations/0228_add_order_base_prices.py@@ -0,0 +1,34 @@+# Generated by Django 5.2.17 on 2026-09-17 09:35++from decimal import Decimal++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0227_orderline_price_override_reason"),+ ]++ operations = [+ migrations.AddField(+ model_name="order",+ name="base_subtotal_amount",+ field=models.DecimalField(+ db_default=Decimal(0),+ decimal_places=3,+ default=Decimal(0),+ max_digits=20,+ ),+ ),+ migrations.AddField(+ model_name="order",+ name="base_total_amount",+ field=models.DecimalField(+ db_default=Decimal(0),+ decimal_places=3,+ default=Decimal(0),+ max_digits=20,+ ),+ ),+ ]diff --git a/saleor/order/models.py b/saleor/order/models.pyindex a6296532db..f28c84b4de 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -342,6 +342,31 @@ class Order(ModelWithMetadata, ModelWithExternalReference):net_amount_field="subtotal_net_amount",gross_amount_field="subtotal_gross_amount",)+ # base prices contain only catalogue discounts (do not contain voucher discount).+ # They are kept apart from `subtotal`/`total` so that the pre-tax values needed to+ # qualify order promotions never overwrite the prices that carry the taxes.+ #+ # These are internal to the price recalculation: `_set_order_base_prices` writes+ # them right before the order promotion predicates read them, in the same pass,+ # and nothing else reads them. That is why existing orders were not backfilled -+ # orders that never recalculate keep the default 0. Exposing these fields anywhere+ # else (API, webhook payloads, filters) requires backfilling them first.+ base_subtotal_amount = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=Decimal(0),+ db_default=Decimal(0),+ )+ base_subtotal = MoneyField(+ amount_field="base_subtotal_amount", currency_field="currency"+ )+ base_total_amount = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=Decimal(0),+ db_default=Decimal(0),+ )+ base_total = MoneyField(amount_field="base_total_amount", currency_field="currency")voucher = models.ForeignKey(Voucher, blank=True, null=True, related_name="+", on_delete=models.SET_NULLdiff --git a/saleor/order/tests/test_fetch_order_prices_concurrent_update.py b/saleor/order/tests/test_fetch_order_prices_concurrent_update.pynew file mode 100644index 0000000000..ceeb99a872--- /dev/null+++ b/saleor/order/tests/test_fetch_order_prices_concurrent_update.py@@ -0,0 +1,331 @@+"""Regression tests for orders left with prices that carry no tax.++`fetch_order_prices_if_expired` used to write the order prices twice:++1. `process_order_promotion` -> `handle_order_promotion` -> `_set_order_base_prices`+ saved the *pre-tax* `subtotal` and `total` straight to the database, before taxes+ were calculated at all - order promotions are qualified by a predicate evaluated in+ SQL, so the pre-tax prices have to be persisted.+2. `process_order_prices` -> `process_calculation_result` saves the taxed prices for+ the order and all of its lines, unless its `updated_at` guard decides the order was+ modified concurrently, in which case the save is skipped.++A skipped second write left the order with the untaxed values from the first one, next+to a `shipping_price` and lines that kept the taxes from an earlier, successful pass.++The pre-tax prices now live in their own `base_subtotal`/`base_total` columns, the way+`Checkout` keeps them, so `subtotal`/`total` are written only by the taxed save. When+that save is skipped the order simply keeps the prices it had before, consistent with+its lines. The skip is mirrored into the `should_refresh_prices` flag of the instance+the caller holds, so `draftOrderComplete` refuses to finalize an order whose stored+prices are not the ones it just calculated.++This holds the same way for flat rates and for a tax app - it does not depend on how+the taxes are calculated.+"""++import dataclasses+from decimal import Decimal+from unittest.mock import patch++import pytest+from django.utils import timezone+from prices import Money, TaxedMoney+from promise import Promise++from ...core.prices import quantize_price+from ...core.taxes import (+ TaxData,+ TaxLineData,+ zero_taxed_money,+)+from ...plugins.manager import get_plugins_manager+from ...tests import race_condition+from .. import calculations+from ..models import Order++# Base (pre-tax) prices of the `draft_order` fixture.+SUBTOTAL_NET = Decimal("70.00")+SHIPPING_NET = Decimal("10.00")+TOTAL_NET = SUBTOTAL_NET + SHIPPING_NET+++def _sum_line_totals(order: Order) -> TaxedMoney:+ return sum(+ (line.total_price for line in order.lines.all()),+ zero_taxed_money(order.currency),+ )+++def _line_totals(order: Order) -> dict:+ return {line.pk: line.total_price for line in order.lines.all()}+++def _recalculate(order, manager=None):+ return calculations.fetch_order_prices_if_expired(+ order,+ manager or get_plugins_manager(allow_replica=False),+ None,+ force_update=True,+ ).get()+++def _recalculate_while_order_is_touched(order, manager, force_update=True):+ def touch_order_from_another_process(*args, **kwargs):+ Order.objects.filter(pk=order.pk).update(updated_at=timezone.now())++ # The base prices have already been written by the time `calculate_taxes` runs,+ # so this mimics another process touching the order between that write and the+ # taxed save.+ with race_condition.RunBefore(+ "saleor.order.calculations.calculate_taxes", touch_order_from_another_process+ ):+ return calculations.fetch_order_prices_if_expired(+ order, manager, None, force_update=force_update+ ).get()+++def _assert_prices_unchanged(persisted: Order, before: Order):+ assert persisted.subtotal == before.subtotal+ assert persisted.total == before.total+ assert persisted.shipping_price == before.shipping_price+ assert _line_totals(persisted) == _line_totals(before)+ assert persisted.subtotal == _sum_line_totals(persisted)+ assert persisted.total == persisted.subtotal + persisted.shipping_price+++def order_with_taxed_prices(draft_order, plugins_manager, tax_configuration_flat_rates):+ """Draft order whose persisted prices are taxed and internally consistent."""+ _recalculate(draft_order, plugins_manager)+ draft_order.refresh_from_db()+ assert draft_order.total.tax.amount > Decimal(0)+ assert draft_order.total == draft_order.subtotal + draft_order.shipping_price+ return draft_order+++# --------------------------------------------------------------------------------+# The pre-tax prices never touch `subtotal`/`total`.+# --------------------------------------------------------------------------------+++def test_base_prices_are_stored_apart_from_the_taxed_prices(+ draft_order, plugins_manager, tax_configuration_flat_rates+):+ # given+ order = draft_order+ currency = order.currency+ before = Order.objects.get(pk=order.pk)+ assert before.base_subtotal == Money(0, currency)+ assert before.base_total == Money(0, currency)+ persisted_during_tax_calculation = []++ def record_persisted_order(*args, **kwargs):+ persisted_during_tax_calculation.append(Order.objects.get(pk=order.pk))++ # when+ with race_condition.RunBefore(+ "saleor.order.calculations.calculate_taxes", record_persisted_order+ ):+ _recalculate(Order.objects.get(pk=order.pk), plugins_manager)++ # then+ # By the time the taxes are calculated the pre-tax prices are already stored, in+ # their own columns - `subtotal` and `total` are still what they were before.+ assert len(persisted_during_tax_calculation) == 1+ during = persisted_during_tax_calculation[0]+ assert during.base_subtotal == Money(SUBTOTAL_NET, currency)+ assert during.base_total == Money(TOTAL_NET, currency)+ assert during.subtotal == before.subtotal+ assert during.total == before.total+++def test_crash_during_recalculation_leaves_the_stored_prices_untouched(+ order_with_taxed_prices, plugins_manager+):+ # given+ order = order_with_taxed_prices+ before = Order.objects.get(pk=order.pk)++ def blow_up(*args, **kwargs):+ raise RuntimeError("pod killed mid-recalculation")++ # when+ with patch("saleor.order.calculations.calculate_prices", side_effect=blow_up):+ with pytest.raises(RuntimeError):+ _recalculate(Order.objects.get(pk=order.pk), plugins_manager)++ # then+ _assert_prices_unchanged(Order.objects.get(pk=order.pk), before)+++# --------------------------------------------------------------------------------+# The recalculated prices are dropped, the previous ones stay.+# --------------------------------------------------------------------------------+++def test_concurrent_update_keeps_the_previously_stored_prices(+ order_with_taxed_prices, plugins_manager+):+ # given+ order = order_with_taxed_prices+ before = Order.objects.get(pk=order.pk)++ # when+ _recalculate_while_order_is_touched(Order.objects.get(pk=order.pk), plugins_manager)++ # then+ # The taxed save was skipped and nothing else wrote the prices, so the order keeps+ # the taxed, consistent prices it had.+ persisted = Order.objects.get(pk=order.pk)+ _assert_prices_unchanged(persisted, before)+ assert persisted.total.tax.amount > Decimal(0)+++def test_concurrent_update_returns_prices_that_were_not_persisted(+ order_with_taxed_prices, plugins_manager+):+ # given+ order = order_with_taxed_prices+ order_in_request = Order.objects.get(pk=order.pk)+ assert order_in_request.should_refresh_prices is False++ # when+ returned_order, _ = _recalculate_while_order_is_touched(+ order_in_request, plugins_manager+ )++ # then+ # The caller gets correctly taxed prices and no tax error, so the returned prices+ # alone cannot tell `draftOrderComplete` that they were never stored. The flag on+ # the instance is what it has to look at.+ assert returned_order.tax_error is None+ assert returned_order.total.tax.amount > Decimal(0)+ assert returned_order.should_refresh_prices is True+ # The caller did not flag the order before recalculating, so nothing in the+ # database says a recalculation was dropped - the instance is the only signal.+ assert Order.objects.get(pk=order.pk).should_refresh_prices is False+++def test_concurrent_update_keeps_the_flag_the_caller_set(+ order_with_taxed_prices, plugins_manager+):+ # given+ # Mutations flag the order before recalculating, which is what makes it need a+ # recalculation in the first place.+ order = order_with_taxed_prices+ Order.objects.filter(pk=order.pk).update(should_refresh_prices=True)++ # when+ _recalculate_while_order_is_touched(+ Order.objects.get(pk=order.pk), plugins_manager, force_update=False+ )++ # then+ # Only the taxed save clears the flag, so a skipped save leaves it set and the+ # prices are recalculated on the next read.+ assert Order.objects.get(pk=order.pk).should_refresh_prices is True+++def test_concurrent_update_prices_are_recalculated_on_the_next_pass(+ order_with_taxed_prices, plugins_manager+):+ # given+ order = order_with_taxed_prices+ Order.objects.filter(pk=order.pk).update(should_refresh_prices=True)+ _recalculate_while_order_is_touched(+ Order.objects.get(pk=order.pk), plugins_manager, force_update=False+ )+ assert Order.objects.get(pk=order.pk).should_refresh_prices is True++ # when+ # `draftOrderComplete` recalculates without forcing an update, so this is what it+ # does for an order whose previous recalculation was dropped.+ calculations.fetch_order_prices_if_expired(+ Order.objects.get(pk=order.pk), plugins_manager, None+ ).get()++ # then+ persisted = Order.objects.get(pk=order.pk)+ assert persisted.should_refresh_prices is False+ assert persisted.total.tax.amount > Decimal(0)+ assert persisted.subtotal == _sum_line_totals(persisted)+ assert persisted.total == persisted.subtotal + persisted.shipping_price+++def test_successful_recalculation_clears_the_flag(+ order_with_taxed_prices, plugins_manager+):+ # given+ order = order_with_taxed_prices+ Order.objects.filter(pk=order.pk).update(should_refresh_prices=True)+ order_in_request = Order.objects.get(pk=order.pk)++ # when+ calculations.fetch_order_prices_if_expired(+ order_in_request, plugins_manager, None+ ).get()++ # then+ persisted = Order.objects.get(pk=order.pk)+ assert persisted.should_refresh_prices is False+ assert order_in_request.should_refresh_prices is False+ assert persisted.total.tax.amount > Decimal(0)+ assert persisted.subtotal == _sum_line_totals(persisted)+ assert persisted.total == persisted.subtotal + persisted.shipping_price+++# --------------------------------------------------------------------------------+# The same, with a tax app instead of a tax plugin.+#+# `_apply_tax_data` is all-or-nothing - it bails out on missing tax data and derives+# `subtotal`/`total` from the same payload it used for the lines - so the app path+# cannot produce a half-taxed order on its own. Where the two paths behave the same is+# the skipped taxed save, so that is what is covered here.+# --------------------------------------------------------------------------------++APP_TAX_RATE = Decimal(10)+++def _tax_data_for(order: Order) -> TaxData:+ currency = order.currency+ rate = Decimal(1) + APP_TAX_RATE / Decimal(100)+ shipping_net = order.base_shipping_price_amount+ return TaxData(+ shipping_price_net_amount=shipping_net,+ shipping_price_gross_amount=quantize_price(shipping_net * rate, currency),+ shipping_tax_rate=APP_TAX_RATE,+ lines=[+ TaxLineData(+ total_net_amount=line.base_unit_price_amount * line.quantity,+ total_gross_amount=quantize_price(+ line.base_unit_price_amount * line.quantity * rate, currency+ ),+ tax_rate=APP_TAX_RATE,+ )+ for line in order.lines.all()+ ],+ )+++@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")+def test_app_concurrent_update_keeps_the_previously_stored_prices(+ mocked_trigger_webhook_sync_promise,+ draft_order,+ tax_configuration_tax_app,+ plugins_manager,+):+ # given+ order = draft_order+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(+ dataclasses.asdict(_tax_data_for(order))+ )+ _recalculate(order, plugins_manager)+ before = Order.objects.get(pk=order.pk)+ assert before.total.tax.amount > Decimal(0)++ # when+ _recalculate_while_order_is_touched(Order.objects.get(pk=order.pk), plugins_manager)++ # then+ _assert_prices_unchanged(Order.objects.get(pk=order.pk), before)