Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Extend order with subtotal (#14887)
Michał Macioszczykf4eeba7fab16
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex c45afab9a0..8c8a3bf37b 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -48,6 +48,7 @@ from ..order.utils import (update_order_display_gross_prices,)from ..payment import PaymentError, TransactionKind, gateway+from ..payment.model_helpers import get_subtotalfrom ..payment.models import Payment, Transactionfrom ..payment.utils import fetch_customer_id, store_customer_idfrom ..product.models import ProductTranslation, ProductVariantTranslation@@ -478,11 +479,17 @@ def _prepare_order_data(+ shipping_total)+ subtotal = get_subtotal(+ [order_line_info.line for order_line_info in order_data["lines"]],+ taxed_total.currency,+ )+order_data.update({"language_code": checkout.language_code,"tracking_client_id": checkout.tracking_code or "","total": taxed_total,+ "subtotal": subtotal,"undiscounted_total": undiscounted_total,"shipping_tax_rate": shipping_tax_rate,}@@ -1212,13 +1219,17 @@ def _create_order_from_checkout(+ shipping_total)order.undiscounted_total = undiscounted_total+ currency = checkout_info.checkout.currency+ subtotal_list = [line.line.total_price for line in order_lines_info]+ order.subtotal = sum(subtotal_list, zero_taxed_money(currency))order.save(update_fields=["undiscounted_total_net_amount","undiscounted_total_gross_amount",+ "subtotal_net_amount",+ "subtotal_gross_amount",])-# allocations_handle_allocations_of_order_lines(checkout_info=checkout_info,@@ -1229,10 +1240,9 @@ def _create_order_from_checkout()# giftcards- currency = checkout_info.checkout.currency- subtotal_list = [line.line.total_price for line in order_lines_info]- subtotal = sum(subtotal_list, zero_taxed_money(currency))- total_without_giftcard = subtotal + shipping_total - checkout_info.checkout.discount+ total_without_giftcard = (+ order.subtotal + shipping_total - checkout_info.checkout.discount+ )add_gift_cards_to_order(checkout_info, order, total_without_giftcard.gross, user, app)diff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex 1edf6d303d..dd35afd12d 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -280,7 +280,7 @@ def validate_voucher_in_order(order: "Order"):if not order.voucher:return- subtotal = order.get_subtotal()+ subtotal = order.subtotalquantity = order.get_total_quantity()customer_email = order.get_customer_email()tax_configuration = order.channel.tax_configurationdiff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.pyindex 842bf0ecf4..adfb7000f9 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py@@ -8,6 +8,7 @@ from .....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom .....checkout.models import Checkoutfrom .....order import OrderStatusfrom .....order.models import Order+from .....payment.model_helpers import get_subtotalfrom .....plugins.manager import get_plugins_managerfrom ....core.utils import to_global_id_or_nonefrom ....tests.utils import get_graphql_content@@ -45,6 +46,15 @@ MUTATION_CHECKOUT_COMPLETE = """amount}}+ subtotal {+ currency+ net {+ amount+ }+ gross {+ amount+ }+ }undiscountedTotal {currencynet {@@ -124,6 +134,11 @@ def test_checkout_complete_order_already_exists(assert order_data["origin"] == order_with_lines.origin.upper()assert not order_data["original"]+ order = Order.objects.get()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["net"]["amount"] == subtotal.net.amount+def test_checkout_complete_with_inactive_channel_order_already_exists(user_api_client,@@ -213,6 +228,9 @@ def test_checkout_complete_0_total_value_no_payment(assert str(order.id) == order_tokenassert order_id == graphene.Node.to_global_id("Order", order.id)assert order.total.gross == total.gross+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["net"]["amount"] == subtotal.net.amountassert order.metadata == checkout.metadata_storage.metadataassert order.private_metadata == checkout.metadata_storage.private_metadata@@ -277,6 +295,9 @@ def test_checkout_complete_0_total_value_from_voucher(assert str(order.id) == order_tokenassert order_id == graphene.Node.to_global_id("Order", order.id)assert order.total.gross == total.gross+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["net"]["amount"] == subtotal.net.amountassert order.metadata == checkout.metadata_storage.metadataassert order.private_metadata == checkout.metadata_storage.private_metadata@@ -337,6 +358,9 @@ def test_checkout_complete_0_total_value_from_giftcard(assert str(order.id) == order_tokenassert order_id == graphene.Node.to_global_id("Order", order.id)assert order.total.gross == total.gross+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["net"]["amount"] == subtotal.net.amountassert order.metadata == checkout.metadata_storage.metadataassert order.private_metadata == checkout.metadata_storage.private_metadatadiff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.pyindex f961ffc2f5..6dd32d8095 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py@@ -27,6 +27,7 @@ from .....order.models import Fulfillment, Orderfrom .....payment import ChargeStatus, PaymentError, TransactionKindfrom .....payment.gateways.dummy_credit_card import TOKEN_VALIDATION_MAPPINGfrom .....payment.interface import GatewayResponse+from .....payment.model_helpers import get_subtotalfrom .....plugins.manager import PluginsManager, get_plugins_managerfrom .....product.models import VariantChannelListingPromotionRulefrom .....tests.utils import flush_post_commit_hooks@@ -68,6 +69,15 @@ MUTATION_CHECKOUT_COMPLETE = """amount}}+ subtotal {+ currency+ net {+ amount+ }+ gross {+ amount+ }+ }undiscountedTotal {currencynet {@@ -215,6 +225,9 @@ def test_checkout_complete(assert str(order.id) == order_tokenassert order.redirect_url == redirect_urlassert order.total.gross == total.gross+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert order.metadata == checkout.metadata_storage.metadataassert order.private_metadata == checkout.metadata_storage.private_metadataassert order.total_charged_amount == payment.total@@ -880,6 +893,9 @@ def test_checkout_with_voucher_complete(assert order.metadata == checkout.metadata_storage.metadataassert order.private_metadata == checkout.metadata_storage.private_metadata+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert order.total == totalassert order.undiscounted_total == total + discount_amount@@ -1132,6 +1148,9 @@ def test_checkout_with_voucher_complete_product_on_promotion(assert order.private_metadata == checkout.metadata_storage.private_metadataorder_line = order.lines.first()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert order.total == totalassert order.undiscounted_total == total + (order_line.undiscounted_total_price - order_line.total_price@@ -1234,6 +1253,9 @@ def test_checkout_with_voucher_on_specific_product_complete(assert order.private_metadata == checkout.metadata_storage.private_metadataorder_line = order.lines.first()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert order.total == totalassert order.undiscounted_total == total + (order_line.undiscounted_total_price - order_line.total_price@@ -1337,6 +1359,9 @@ def test_checkout_complete_with_voucher_single_use(assert order.metadata == checkout.metadata_storage.metadataassert order.private_metadata == checkout.metadata_storage.private_metadata+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert order.total == totalassert order.undiscounted_total == total + discount_amount@@ -1476,6 +1501,9 @@ def test_checkout_complete_product_on_promotion(assert order.private_metadata == checkout.metadata_storage.private_metadataorder_line = order.lines.first()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert order.total == totalassert order.undiscounted_total == total + (order_line.undiscounted_total_price - order_line.total_price@@ -1618,6 +1646,9 @@ def test_checkout_complete_product_on_old_sale(assert order.private_metadata == checkout.metadata_storage.private_metadataorder_line = order.lines.first()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert order.total == totalassert order.undiscounted_total == total + (order_line.undiscounted_total_price - order_line.total_price@@ -1805,6 +1836,9 @@ def test_checkout_complete_multiple_rules_applied(assert order.private_metadata == checkout.metadata_storage.private_metadataorder_line = order.lines.first()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert order.total == totalassert order.undiscounted_total == total + (order_line.undiscounted_total_price - order_line.total_price@@ -1940,6 +1974,9 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_promassert order.private_metadata == checkout.metadata_storage.private_metadataorder_line = order.lines.first()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert order.total == totalassert order.undiscounted_total == total + (order_line.undiscounted_total_price - order_line.total_price@@ -2087,6 +2124,10 @@ def test_checkout_complete_without_inventory_tracking(assert order.metadata == checkout.metadata_storage.metadataassert order.private_metadata == checkout.metadata_storage.private_metadata+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amount+order_line = order.lines.first()assert checkout_line_quantity == order_line.quantityassert checkout_line_variant == order_line.variant@@ -3035,6 +3076,9 @@ def test_checkout_complete_0_total_value(assert order.private_metadata == checkout.metadata_storage.private_metadataorder_line = order.lines.first()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert checkout_line_quantity == order_line.quantityassert checkout_line_variant == order_line.variantassert order.shipping_address is None@@ -3439,6 +3483,9 @@ def test_checkout_complete_with_preorder_variant(assert order_id == graphene.Node.to_global_id("Order", order.id)assert order.total.gross == total.gross+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert order.subtotal == subtotal+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert order.lines.count() == len(variants_and_quantities)for variant_id, quantity in variants_and_quantities.items():assert order.lines.get(variant_id=variant_id).quantity == quantitydiff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.pyindex 85442da38f..27e4198ac6 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py@@ -24,6 +24,7 @@ from .....giftcard.models import GiftCard, GiftCardEventfrom .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderOrigin, OrderStatusfrom .....order.models import Fulfillment, Orderfrom .....payment import TransactionEventType+from .....payment.model_helpers import get_subtotalfrom .....payment.transaction_item_calculations import recalculate_transaction_amountsfrom .....plugins.manager import PluginsManager, get_plugins_managerfrom .....product.models import VariantChannelListingPromotionRule@@ -232,6 +233,7 @@ def test_checkout_without_any_transaction_allow_to_create_order(assert order.total_authorized == zero_money(order.currency)assert order.charge_status == OrderChargeStatus.NONEassert order.authorize_status == OrderAuthorizeStatus.NONE+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossdef test_checkout_with_total_0(@@ -287,6 +289,7 @@ def test_checkout_with_total_0(assert order.total_authorized == zero_money(order.currency)assert order.charge_status == OrderChargeStatus.FULLassert order.authorize_status == OrderAuthorizeStatus.FULL+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossdef test_checkout_with_authorized(@@ -358,6 +361,7 @@ def test_checkout_with_authorized(assert order.redirect_url == redirect_urlassert order.total.gross == total.gross+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossassert order.metadata == checkout.metadata_storage.metadataassert order.private_metadata == checkout.metadata_storage.private_metadata@@ -455,6 +459,7 @@ def test_checkout_with_charged(assert order.redirect_url == redirect_urlassert order.total.gross == total.gross+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossassert order.metadata == checkout.metadata_storage.metadataassert order.private_metadata == checkout.metadata_storage.private_metadata@@ -542,6 +547,7 @@ def test_checkout_paid_with_multiple_transactions(assert order.total_authorized == zero_money(order.currency)assert order.charge_status == OrderChargeStatus.FULLassert order.authorize_status == OrderAuthorizeStatus.FULL+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossdef test_checkout_partially_paid(@@ -718,6 +724,7 @@ def test_checkout_with_pending_charged(assert order.total_authorized == zero_money(order.currency)assert order.charge_status == OrderChargeStatus.NONEassert order.authorize_status == OrderAuthorizeStatus.NONE+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossdef test_checkout_with_pending_authorized(@@ -801,6 +808,7 @@ def test_checkout_with_pending_authorized(assert order.redirect_url == redirect_urlassert order.total.gross == total.gross+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossassert order.metadata == checkout.metadata_storage.metadataassert order.private_metadata == checkout.metadata_storage.private_metadata@@ -1124,6 +1132,7 @@ def test_checkout_complete(assert str(order.id) == order_tokenassert order.redirect_url == redirect_urlassert order.total.gross == total.gross+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossassert order.metadata == checkout.metadata_storage.metadataassert order.private_metadata == checkout.metadata_storage.private_metadatatransaction = order.payment_transactions.first()@@ -1645,6 +1654,7 @@ def test_checkout_with_voucher_complete(assert order.private_metadata == checkout.metadata_storage.private_metadataassert order.total == total+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossassert order.undiscounted_total == total + discount_amountcode.refresh_from_db()@@ -1730,6 +1740,7 @@ def test_checkout_complete_with_voucher_apply_once_per_order(assert order_id == graphene.Node.to_global_id("Order", order.id)assert order.total == total+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossassert order.undiscounted_total == total + discount_amountcode.refresh_from_db()@@ -1810,6 +1821,7 @@ def test_checkout_complete_with_voucher_single_use(assert order.private_metadata == checkout.metadata_storage.private_metadataassert order.total == total+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossassert order.undiscounted_total == total + discount_amountcode.refresh_from_db()@@ -1936,6 +1948,7 @@ def test_checkout_with_voucher_complete_product_on_sale(order_line = order.lines.first()assert order.total == total+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossassert order.undiscounted_total == total + (order_line.undiscounted_total_price - order_line.total_price)@@ -2009,6 +2022,7 @@ def test_checkout_with_voucher_on_specific_product_complete(order_line = order.lines.first()assert order.total == total+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossassert order.undiscounted_total == total + (order_line.undiscounted_total_price - order_line.total_price)@@ -2126,6 +2140,7 @@ def test_checkout_complete_product_on_promotion(order_line = order.lines.first()assert order.total == total+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossassert order.undiscounted_total == total + (order_line.undiscounted_total_price - order_line.total_price)@@ -2282,6 +2297,7 @@ def test_checkout_complete_multiple_rules_applied(order_line = order.lines.first()assert order.total == total+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossassert order.undiscounted_total == total + (order_line.undiscounted_total_price - order_line.total_price)@@ -2362,6 +2378,7 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_promorder_line = order.lines.first()assert order.total == total+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossassert order.undiscounted_total == total + (order_line.undiscounted_total_price - order_line.total_price)@@ -3071,6 +3088,7 @@ def test_checkout_complete_with_preorder_variant(assert str(order.id) == order_tokenassert order_id == graphene.Node.to_global_id("Order", order.id)assert order.total.gross == total.gross+ assert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).grossassert order.lines.count() == len(variants_and_quantities)for variant_id, quantity in variants_and_quantities.items():diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.pyindex 86986098b0..5038048d0e 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py@@ -11,6 +11,7 @@ from .....order import OrderOrigin, OrderStatusfrom .....order import events as order_eventsfrom .....order.error_codes import OrderErrorCodefrom .....order.models import OrderEvent+from .....payment.model_helpers import get_subtotalfrom .....plugins.base_plugin import ExcludedShippingMethodfrom .....product.models import ProductVariantfrom .....warehouse.models import Allocation, PreorderAllocation, Stock@@ -40,6 +41,11 @@ DRAFT_ORDER_COMPLETE_MUTATION = """amount}}+ subtotal {+ net {+ amount+ }+ }undiscountedTotal {net {amount@@ -202,6 +208,11 @@ def test_draft_order_complete_with_voucher(assert data["voucher"]["code"] == voucher.codeassert data["undiscountedTotal"]["net"]["amount"] == order_totalassert data["total"]["net"]["amount"] == order_total - discount_value+ assert (+ data["total"]["net"]["amount"] == order_total - voucher_listing.discount_value+ )+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert data["subtotal"]["net"]["amount"] == subtotal.gross.amountassert order.search_vectorlines = order.lines.all()diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.pyindex 4e9ff7f779..af64c2c52a 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py@@ -15,6 +15,7 @@ from .....order import OrderStatusfrom .....order import events as order_eventsfrom .....order.error_codes import OrderErrorCodefrom .....order.models import Order, OrderEvent+from .....payment.model_helpers import get_subtotalfrom .....product.models import ProductVariantfrom .....tax import TaxCalculationStrategyfrom ....tests.utils import assert_no_permission, get_graphql_content@@ -74,6 +75,11 @@ DRAFT_ORDER_CREATE_MUTATION = """amount}}+ subtotal {+ gross {+ amount+ }+ }undiscountedTotal {gross {amount@@ -214,6 +220,9 @@ def test_draft_order_create_with_voucher()order = Order.objects.first()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert data["subtotal"]["gross"]["amount"] == subtotal.gross.amount+assert order.voucher_code == voucher.codeassert order.user == customer_userassert order.shipping_method == shipping_method@@ -435,6 +444,8 @@ def test_draft_order_create_with_voucher_code()order = Order.objects.first()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert data["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert order.voucher_code == voucher.codeassert order.user == customer_userassert order.shipping_method == shipping_method@@ -559,6 +570,8 @@ def test_draft_order_create_percentage_voucher()order = Order.objects.first()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert data["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert order.user == customer_userassert order.shipping_method == shipping_methodassert order.shipping_method_name == shipping_method.name@@ -766,6 +779,8 @@ def test_draft_order_create_with_voucher_including_drafts_in_voucher_usage()order = Order.objects.first()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert data["subtotal"]["gross"]["amount"] == subtotal.gross.amount# Ensure order discount object was properly createdassert order.discounts.count() == 1@@ -916,6 +931,8 @@ def test_draft_order_create_with_voucher_code_including_drafts_in_voucher_usage()order = Order.objects.first()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert data["subtotal"]["gross"]["amount"] == subtotal.gross.amount# Ensure order discount object was properly createdassert order.discounts.count() == 1@@ -2075,6 +2092,7 @@ def test_draft_order_create_price_recalculation(permission_group_manage_orders.user_set.add(staff_api_client.user)fake_order = Mock()fake_order.total = zero_taxed_money(channel_PLN.currency_code)+ fake_order.subtotal = zero_taxed_money(channel_PLN.currency_code)fake_order.undiscounted_total = zero_taxed_money(channel_PLN.currency_code)fake_order.shipping_price = zero_taxed_money(channel_PLN.currency_code)fetch_prices_response = Mock(return_value=(fake_order, None))diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_update.py b/saleor/graphql/order/tests/mutations/test_draft_order_update.pyindex 55a6f645ea..e568cc5c84 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py@@ -7,6 +7,7 @@ from .....discount import DiscountType, DiscountValueTypefrom .....order import OrderStatusfrom .....order.error_codes import OrderErrorCodefrom .....order.models import OrderEvent+from .....payment.model_helpers import get_subtotalfrom ....tests.utils import assert_no_permission, get_graphql_contentDRAFT_ORDER_UPDATE_MUTATION = """@@ -66,6 +67,11 @@ DRAFT_ORDER_UPDATE_MUTATION = """amount}}+ subtotal {+ gross {+ amount+ }+ }undiscountedTotal {gross {amount@@ -195,6 +201,8 @@ def test_draft_order_update_with_voucher(== external_reference== order.external_reference)+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amount# Ensure order discount object was properly createdassert order.discounts.count() == 1@@ -400,6 +408,8 @@ def test_draft_order_update_with_voucher_including_drafts_in_voucher_usage(assert not data["errors"]order.refresh_from_db()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert order.voucher_code == voucher.codeassert order.search_vector@@ -465,6 +475,8 @@ def test_draft_order_update_with_voucher_code_including_drafts_in_voucher_usage(assert not data["errors"]order.refresh_from_db()+ subtotal = get_subtotal(order.lines.all(), order.currency)+ assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amountassert order.voucher_code == voucher.codeassert order.search_vectordiff --git a/saleor/graphql/order/tests/queries/test_order.py b/saleor/graphql/order/tests/queries/test_order.pyindex 3fe9498bd5..3b25d60607 100644--- a/saleor/graphql/order/tests/queries/test_order.py+++ b/saleor/graphql/order/tests/queries/test_order.py@@ -348,7 +348,7 @@ def test_order_query(assert len(order_data["payments"]) == order.payments.count()expected_methods = ShippingMethod.objects.applicable_shipping_methods(- price=order.get_subtotal().gross,+ price=order.subtotal.gross,weight=order.get_total_weight(),country_code=order.shipping_address.country.code,channel_id=order.channel_id,@@ -996,7 +996,7 @@ def test_order_query_in_pln_channel(assert len(order_data["payments"]) == order.payments.count()expected_methods = ShippingMethod.objects.applicable_shipping_methods(- price=order.get_subtotal().gross,+ price=order.subtotal.gross,weight=order.get_total_weight(),country_code=order.shipping_address.country.code,channel_id=order.channel_id,diff --git a/saleor/order/calculations.py b/saleor/order/calculations.pyindex f519a53b05..c73925e912 100644--- a/saleor/order/calculations.py+++ b/saleor/order/calculations.py@@ -1,6 +1,6 @@from collections.abc import Iterablefrom decimal import Decimal-from typing import Optional, cast+from typing import Optionalfrom django.db import transactionfrom django.db.models import prefetch_related_objects@@ -59,9 +59,12 @@ def fetch_order_prices_if_expired(_update_order_discount_for_voucher(order)_recalculate_prices(order, manager, lines)+ order.subtotal = get_subtotal(lines, order.currency)with transaction.atomic(savepoint=False):order.save(update_fields=[+ "subtotal_net_amount",+ "subtotal_gross_amount","total_net_amount","total_gross_amount","undiscounted_total_net_amount",@@ -448,8 +451,7 @@ def order_subtotal(order, lines = fetch_order_prices_if_expired(order, manager, lines, force_update)# Lines aren't returned only if# we don't pass them to `fetch_order_prices_if_expired`.- lines = cast(Iterable[OrderLine], lines)- return quantize_price(get_subtotal(lines, currency), currency)+ return quantize_price(order.subtotal, currency)def order_total(diff --git a/saleor/order/migrations/0180_auto_20231108_0908.py b/saleor/order/migrations/0180_auto_20231108_0908.pynew file mode 100644index 0000000000..e1ba2bbdc7--- /dev/null+++ b/saleor/order/migrations/0180_auto_20231108_0908.py@@ -0,0 +1,44 @@+# Generated by Django 3.2.23 on 2023-11-08 09:08++from decimal import Decimal++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0179_merge_20231122_1348"),+ ]++ operations = [+ migrations.AddField(+ model_name="order",+ name="subtotal_gross_amount",+ field=models.DecimalField(+ decimal_places=3, default=Decimal("0"), max_digits=12+ ),+ ),+ migrations.RunSQL(+ """+ ALTER TABLE order_order+ ALTER COLUMN subtotal_gross_amount+ SET DEFAULT 0;+ """,+ migrations.RunSQL.noop,+ ),+ migrations.AddField(+ model_name="order",+ name="subtotal_net_amount",+ field=models.DecimalField(+ decimal_places=3, default=Decimal("0"), max_digits=12+ ),+ ),+ migrations.RunSQL(+ """+ ALTER TABLE order_order+ ALTER COLUMN subtotal_net_amount+ SET DEFAULT 0;+ """,+ migrations.RunSQL.noop,+ ),+ ]diff --git a/saleor/order/migrations/0181_order_subtotal_as_a_field.py b/saleor/order/migrations/0181_order_subtotal_as_a_field.pynew file mode 100644index 0000000000..14cbaa4535--- /dev/null+++ b/saleor/order/migrations/0181_order_subtotal_as_a_field.py@@ -0,0 +1,67 @@+from django.db import migrations+from django.db.models import F, Func, OuterRef, Subquery++# One batch took 0.1s and 10.54MB at its peak+BATCH_SIZE = 1000+++def update_order_subtotals(apps, schema_editor):+ Order = apps.get_model("order", "Order")+ OrderLine = apps.get_model("order", "OrderLine")++ first_order = Order.objects.last()+ if first_order is None:+ return # Exit if there are no orders+ start_number = first_order.number++ while True:+ # right here we need to find only Orders which was not populated+ # with subtotal in previous release, so the amount of rows to populate+ # shouldn't be big+ queryset = Order.objects.order_by("number").filter(+ number__gte=start_number, subtotal_gross_amount__exact=0+ )[:BATCH_SIZE]+ current_batch_order_numbers = list(queryset.values_list("number", flat=True))++ # Break the loop if there are no orders+ if not current_batch_order_numbers:+ break++ order_line = OrderLine.objects.filter(order=OuterRef("pk"))+ subtotal_net_sum = order_line.annotate(+ net_sum=Func(F("total_price_net_amount"), function="Sum")+ ).values("net_sum")++ subtotal_gross_sum = order_line.annotate(+ gross_sum=Func(F("total_price_gross_amount"), function="Sum")+ ).values("gross_sum")++ orders_with_totals = Order.objects.filter(+ number__in=current_batch_order_numbers+ ).annotate(+ subtotal_net_sum=Subquery(subtotal_net_sum),+ subtotal_gross_sum=Subquery(subtotal_gross_sum),+ )++ orders_to_update = []+ for order in orders_with_totals:+ order.subtotal_net_amount = order.subtotal_net_sum+ order.subtotal_gross_amount = order.subtotal_gross_sum+ orders_to_update.append(order)++ Order.objects.bulk_update(+ orders_to_update, ["subtotal_net_amount", "subtotal_gross_amount"]+ )+ start_number = current_batch_order_numbers[-1]+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0180_auto_20231108_0908"),+ ]++ operations = [+ migrations.RunPython(+ update_order_subtotals, reverse_code=migrations.RunPython.noop+ ),+ ]diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 7dfbfd882f..f47dd4f5e8 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -26,7 +26,6 @@ from ..discount import DiscountValueTypefrom ..discount.models import Voucherfrom ..giftcard.models import GiftCardfrom ..payment import ChargeStatus, TransactionKind-from ..payment.model_helpers import get_subtotalfrom ..payment.models import Paymentfrom ..permission.enums import OrderPermissionsfrom ..shipping.models import ShippingMethod@@ -302,6 +301,20 @@ class Order(ModelWithMetadata, ModelWithExternalReference):total_charged = MoneyField(amount_field="total_charged_amount", currency_field="currency")+ subtotal_net_amount = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=Decimal(0),+ )+ subtotal_gross_amount = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=Decimal(0),+ )+ subtotal = TaxedMoneyField(+ net_amount_field="subtotal_net_amount",+ gross_amount_field="subtotal_gross_amount",+ )voucher = models.ForeignKey(Voucher, blank=True, null=True, related_name="+", on_delete=models.SET_NULL@@ -411,9 +424,6 @@ class Order(ModelWithMetadata, ModelWithExternalReference):def is_shipping_required(self):return any(line.is_shipping_required for line in self.lines.all())- def get_subtotal(self):- return get_subtotal(self.lines.all(), self.currency)-def get_total_quantity(self):return sum([line.quantity for line in self.lines.all()])diff --git a/saleor/order/notifications.py b/saleor/order/notifications.pyindex 5e88d2c100..03b92b4b5f 100644--- a/saleor/order/notifications.py+++ b/saleor/order/notifications.py@@ -243,7 +243,7 @@ def get_default_order_payload(order: "Order", redirect_url: str = ""):order_details_url = ""if redirect_url:order_details_url = prepare_order_details_url(order, redirect_url)- subtotal = order.get_subtotal()+ subtotal = order.subtotaltax = order.total_gross_amount - order.total_net_amount or Decimal(0)lines = order.lines.prefetch_related(diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.pyindex b0f93d1126..20de9a612f 100644--- a/saleor/order/tests/test_calculations.py+++ b/saleor/order/tests/test_calculations.py@@ -1106,7 +1106,12 @@ def test_order_subtotal(mocked_fetch_order_prices_if_expired):TaxedMoney(Money(Decimal("2.00"), currency), Money(Decimal("2.00"), currency)),TaxedMoney(Money(Decimal("4.00"), currency), Money(Decimal("4.00"), currency)),]- order = Mock(currency=currency)+ order = Mock(+ currency=currency,+ subtotal=TaxedMoney(+ Money(Decimal("7.00"), currency), Money(Decimal("7.00"), currency)+ ),+ )lines = []for expected_line_total in expected_line_totals:line = Mock(total_price=expected_line_total, currency=currency)diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.pyindex a2892bb967..578be0d682 100644--- a/saleor/order/tests/test_notifications.py+++ b/saleor/order/tests/test_notifications.py@@ -19,6 +19,7 @@ from ...graphql.core.utils import to_global_id_or_nonefrom ...graphql.order.utils import OrderLineDatafrom ...order import notificationsfrom ...order.fetch import fetch_order_info+from ...payment.model_helpers import get_subtotalfrom ...plugins.manager import get_plugins_managerfrom ...product.models import DigitalContentUrlfrom ...thumbnail import THUMBNAIL_SIZES@@ -214,9 +215,10 @@ def test_get_address_payload(address):def test_get_default_order_payload(order_line):order_line.refresh_from_db()order = order_line.order+ order.subtotal = get_subtotal(order.lines.all(), order.currency)order_line_payload = get_order_line_payload(order_line)redirect_url = "http://redirect.com/path"- subtotal = order.get_subtotal()+ subtotal = order.subtotalorder.total = subtotal + order.shipping_pricetax = order.total_gross_amount - order.total_net_amountdiff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.pyindex 5f60101ddb..6551df9607 100644--- a/saleor/order/tests/test_order.py+++ b/saleor/order/tests/test_order.py@@ -80,9 +80,8 @@ def test_order_get_subtotal(order_with_lines):fetch_order_prices_if_expired(order_with_lines, get_plugins_manager(allow_replica=False), force_update=True)-target_subtotal = order_with_lines.total - order_with_lines.shipping_price- assert order_with_lines.get_subtotal() == target_subtotal+ assert order_with_lines.subtotal == target_subtotaldef test_recalculate_order_keeps_weight_unit(order_with_lines):@@ -675,7 +674,7 @@ def test_get_voucher_discount_for_order_voucher_validation():order_with_lines.voucher = voucherorder_with_lines.save()- subtotal = order_with_lines.get_subtotal()+ subtotal = order_with_lines.subtotalquantity = order_with_lines.get_total_quantity()customer_email = order_with_lines.get_customer_email()@@ -740,7 +739,7 @@ def test_value_voucher_order_discount(subtotal = Money(subtotal, "USD")subtotal = TaxedMoney(net=subtotal, gross=subtotal)order = Mock(- get_subtotal=Mock(return_value=subtotal),+ subtotal=subtotal,voucher=voucher,shipping_address=address_usa,billing_address=address_usa,@@ -833,7 +832,7 @@ def test_shipping_voucher_checkout_discount_not_applicable_returns_zero(price = Money(total, "USD")price = TaxedMoney(net=price, gross=price)order = Mock(- get_subtotal=Mock(return_value=price),+ subtotal=price,get_total_quantity=Mock(return_value=total_quantity),shipping_address=address_usa,billing_address=address_usa,diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 8bf8ed35dc..864008c686 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -615,7 +615,7 @@ def get_all_shipping_methods_for_order(shipping_methods = ShippingMethod.objects.applicable_shipping_methods_for_instance(order,channel_id=order.channel_id,- price=order.get_subtotal().gross,+ price=order.subtotal.gross,country_code=order.shipping_address.country.code,).prefetch_related("channel_listings")@@ -725,7 +725,7 @@ def get_voucher_discount_for_order(order: Order) -> Money:if not order.voucher:return zero_money(order.currency)validate_voucher_in_order(order)- subtotal = order.get_subtotal()+ subtotal = order.subtotalif order.voucher.type == VoucherType.ENTIRE_ORDER:return order.voucher.get_discount_amount_for(subtotal.gross, order.channel)if order.voucher.type == VoucherType.SHIPPING:diff --git a/saleor/tax/tests/test_order_calculations.py b/saleor/tax/tests/test_order_calculations.pyindex d4a9af81c9..15f0bd6202 100644--- a/saleor/tax/tests/test_order_calculations.py+++ b/saleor/tax/tests/test_order_calculations.py@@ -11,6 +11,7 @@ from ...order import OrderStatusfrom ...order.base_calculations import apply_order_discountsfrom ...order.calculations import fetch_order_prices_if_expiredfrom ...order.utils import get_order_country+from ...payment.model_helpers import get_subtotalfrom ...plugins.manager import get_plugins_managerfrom .. import TaxCalculationStrategyfrom ..calculations.order import (@@ -734,3 +735,5 @@ def test_use_default_country_rate_when_no_tax_class_was_set_before(assert order.shipping_tax_rate == Decimal("0.20")assert not order.shipping_tax_classassert not order.shipping_tax_class_name++ assert order.subtotal == get_subtotal(order.lines.all(), order.currency)diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex a3e681bd75..ca8d9cd9eb 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -98,6 +98,7 @@ from ..order.utils import (from ..page.models import Page, PageTranslation, PageTypefrom ..payment import ChargeStatus, TransactionKindfrom ..payment.interface import AddressData, GatewayConfig, GatewayResponse, PaymentData+from ..payment.model_helpers import get_subtotalfrom ..payment.models import Payment, TransactionEvent, TransactionItemfrom ..payment.transaction_item_calculations import recalculate_transaction_amountsfrom ..payment.utils import create_manual_adjustment_events@@ -4630,6 +4631,7 @@ def recalculate_order(order):total -= discountorder.total = total+ order.subtotal = get_subtotal(order.lines.all(), order.currency)order.undiscounted_total = undiscounted_totalif discount: