Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add `undiscounted_base_shipping_price` to `Order` (#16279)
Iga Karbowiak14a682044ca4
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex f16e831473..ac723651f9 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -170,6 +170,7 @@ def _release_checkout_voucher_usage(def _process_shipping_data_for_order(checkout_info: "CheckoutInfo",+ undiscounted_base_shipping_price: Money,base_shipping_price: Money,shipping_price: TaxedMoney,manager: "PluginsManager",@@ -197,6 +198,7 @@ def _process_shipping_data_for_order(tax_class = getattr(shipping_method, "tax_class", None)result: dict[str, Any] = {+ "undiscounted_base_shipping_price": undiscounted_base_shipping_price,"shipping_address": shipping_address,"base_shipping_price": base_shipping_price,"shipping_price": shipping_price,@@ -531,7 +533,12 @@ def _prepare_order_data()order_data.update(_process_shipping_data_for_order(- checkout_info, base_shipping_price, shipping_total, manager, lines+ checkout_info,+ undiscounted_base_shipping_price,+ base_shipping_price,+ shipping_total,+ manager,+ lines,))order_data.update(_process_user_data_for_order(checkout_info, manager))@@ -1283,6 +1290,7 @@ def _create_order_from_checkout(tax_exemption=checkout_info.checkout.tax_exemption,**_process_shipping_data_for_order(checkout_info,+ undiscounted_base_shipping_price,base_shipping_price,shipping_total,manager,diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.pyindex ff7b80a3c3..5854b8a1fc 100644--- a/saleor/checkout/tests/test_checkout_complete.py+++ b/saleor/checkout/tests/test_checkout_complete.py@@ -1796,7 +1796,12 @@ def test_process_shipping_data_for_order_store_customer_shipping_address(# when_ = _process_shipping_data_for_order(- checkout_info, base_shipping_price, shipping_price, manager, lines+ checkout_info,+ base_shipping_price,+ base_shipping_price,+ shipping_price,+ manager,+ lines,)# then@@ -1831,7 +1836,12 @@ def test_process_shipping_data_for_order_dont_store_customer_click_and_collect_a# when_ = _process_shipping_data_for_order(- checkout_info, base_shipping_price, shipping_price, manager, lines+ checkout_info,+ base_shipping_price,+ base_shipping_price,+ shipping_price,+ manager,+ lines,)# then@@ -1917,6 +1927,7 @@ def test_create_order_store_shipping_prices()# then+ assert order.undiscounted_base_shipping_price == expected_base_shipping_priceassert order.base_shipping_price == expected_base_shipping_priceassert order.shipping_price == expected_shipping_pricemanager.calculate_checkout_shipping.assert_called_once_with(@@ -1941,6 +1952,9 @@ def test_create_order_store_shipping_prices_with_free_shipping_voucher(checkout = checkout_with_voucher_free_shippingmanager = get_plugins_manager(allow_replica=False)+ expected_undiscounted_shipping_price = shipping_method.channel_listings.get(+ channel=checkout.channel+ ).priceexpected_base_shipping_price = zero_money(checkout.currency)expected_shipping_price = zero_taxed_money(checkout.currency)expected_shipping_tax_rate = Decimal("0.0")@@ -1971,8 +1985,23 @@ def test_create_order_store_shipping_prices_with_free_shipping_voucher()# then+ assert (+ order.undiscounted_base_shipping_price == expected_undiscounted_shipping_price+ )assert order.base_shipping_price == expected_base_shipping_priceassert order.shipping_price == expected_shipping_price+ undiscounted_subtotal = sum(+ [line.undiscounted_total_price for line in order.lines.all()],+ zero_taxed_money(order.currency),+ )+ assert (+ order.undiscounted_total+ == TaxedMoney(+ net=expected_undiscounted_shipping_price,+ gross=expected_undiscounted_shipping_price,+ )+ + undiscounted_subtotal+ )manager.calculate_checkout_shipping.assert_called_once_with(checkout_info, lines, checkout.shipping_address, plugin_ids=None)diff --git a/saleor/checkout/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.pyindex 2c0714f777..bef6917707 100644--- a/saleor/checkout/tests/test_order_from_checkout.py+++ b/saleor/checkout/tests/test_order_from_checkout.py@@ -670,6 +670,7 @@ def test_create_order_from_checkout_store_shipping_prices()# then+ assert order.undiscounted_base_shipping_price == expected_base_shipping_priceassert order.base_shipping_price == expected_base_shipping_priceassert order.shipping_price == expected_shipping_pricemanager.calculate_checkout_shipping.assert_called_once_with(@@ -749,6 +750,9 @@ def test_create_order_from_store_shipping_prices_with_free_shipping_voucher(# givencheckout = checkout_with_voucher_free_shipping+ expected_undiscounted_shipping_price = shipping_method.channel_listings.get(+ channel=checkout.channel+ ).priceexpected_base_shipping_price = zero_money(checkout.currency)expected_shipping_price = zero_taxed_money(checkout.currency)expected_shipping_tax_rate = Decimal("0.0")@@ -773,6 +777,9 @@ def test_create_order_from_store_shipping_prices_with_free_shipping_voucher()# then+ assert (+ order.undiscounted_base_shipping_price == expected_undiscounted_shipping_price+ )assert order.base_shipping_price == expected_base_shipping_priceassert order.shipping_price == expected_shipping_pricemanager.calculate_checkout_shipping.assert_called_once_with(diff --git a/saleor/discount/utils/order.py b/saleor/discount/utils/order.pyindex 2e3b22cf8f..09289e882f 100644--- a/saleor/discount/utils/order.py+++ b/saleor/discount/utils/order.py@@ -199,7 +199,7 @@ def _set_order_base_prices(order: Order, lines_info: Iterable["EditableOrderLine"""Set base order prices that includes only catalogue discounts."""lines = [line_info.line for line_info in lines_info]subtotal = base_order_subtotal(order, lines)- shipping_price = order.base_shipping_price+ shipping_price = order.undiscounted_base_shipping_pricetotal = subtotal + shipping_priceupdate_fields = []diff --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 cd9e54656a..8e8ef7d0e2 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@@ -191,6 +191,10 @@ def test_checkout_complete(checkout_line_quantity = checkout_line.quantitycheckout_line_variant = checkout_line.variant+ shipping_price = checkout.shipping_method.channel_listings.get(+ channel=checkout.channel+ ).price+manager = get_plugins_manager(allow_replica=False)lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)@@ -260,6 +264,9 @@ def test_checkout_complete(assert (order.shipping_tax_class_private_metadata == shipping_tax_class.private_metadata)+ assert order.shipping_price_gross_amount == shipping_price.amount+ assert order.base_shipping_price_amount == shipping_price.amount+ assert order.undiscounted_base_shipping_price_amount == shipping_price.amountassert order.payments.exists()assert order.search_vectororder_payment = order.payments.first()@@ -3433,6 +3440,9 @@ def test_checkout_complete_0_total_value(assert checkout_line_variant == order_line.variantassert order.shipping_address is Noneassert order.shipping_method is None+ assert order.shipping_price_gross_amount == 0+ assert order.base_shipping_price_amount == 0+ assert order.undiscounted_base_shipping_price_amount == 0assert order.payments.exists()order_payment = order.payments.first()assert order_payment == paymentdiff --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 3e09a3d8ad..43ce928272 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@@ -303,6 +303,9 @@ def test_checkout_with_total_0(assert order.charge_status == OrderChargeStatus.FULLassert order.authorize_status == OrderAuthorizeStatus.FULLassert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).gross+ assert order.shipping_price_gross_amount == 0+ assert order.base_shipping_price_amount == 0+ assert order.undiscounted_base_shipping_price_amount == 0def test_checkout_with_authorized(@@ -334,6 +337,10 @@ def test_checkout_with_authorized(channel.automatically_confirm_all_new_orders = Truechannel.save()+ shipping_price = checkout.shipping_method.channel_listings.get(+ channel=checkout.channel+ ).price+manager = get_plugins_manager(allow_replica=False)lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)@@ -398,6 +405,9 @@ def test_checkout_with_authorized(assert (order.shipping_tax_class_private_metadata == shipping_tax_class.private_metadata)+ assert order.shipping_price_gross_amount == shipping_price.amount+ assert order.base_shipping_price_amount == shipping_price.amount+ assert order.undiscounted_base_shipping_price_amount == shipping_price.amountassert not Checkout.objects.filter()assert not len(Reservation.objects.all())diff --git a/saleor/graphql/core/types/taxes.py b/saleor/graphql/core/types/taxes.pyindex 5597d5275f..5ff5410b55 100644--- a/saleor/graphql/core/types/taxes.py+++ b/saleor/graphql/core/types/taxes.py@@ -362,20 +362,7 @@ class TaxableObject(BaseObjectType):]).then(calculate_shipping_price)- # TODO (SHOPX-875): after adding `undiscounted_base_shipping_price` to- # Order model, the `root.base_shipping_price` should be used- def shipping_price_with_discount(tax_config):- return (- root.shipping_price_gross- if tax_config.prices_entered_with_tax- else root.shipping_price_net- )-- return (- TaxConfigurationByChannelId(info.context)- .load(root.channel_id)- .then(shipping_price_with_discount)- )+ return root.base_shipping_price@staticmethoddef resolve_discounts(root: Union[Checkout, Order], info: ResolveInfo):diff --git a/saleor/graphql/order/bulk_mutations/order_bulk_create.py b/saleor/graphql/order/bulk_mutations/order_bulk_create.pyindex ff91515909..04af6ae247 100644--- a/saleor/graphql/order/bulk_mutations/order_bulk_create.py+++ b/saleor/graphql/order/bulk_mutations/order_bulk_create.py@@ -1947,6 +1947,9 @@ class OrderBulkCreate(BaseMutation, I18nMixin):)order_data.order.shipping_price_net_amount = order_amounts.shipping_price_netorder_data.order.base_shipping_price_amount = order_amounts.shipping_price_net+ order_data.order.undiscounted_base_shipping_price_amount = (+ order_amounts.shipping_price_net+ )order_data.order.total_gross_amount = order_amounts.total_grossorder_data.order.undiscounted_total_gross_amount = (order_amounts.undiscounted_total_grossdiff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.pyindex 5e19174c5a..19ed9c0db7 100644--- a/saleor/graphql/order/mutations/draft_order_create.py+++ b/saleor/graphql/order/mutations/draft_order_create.py@@ -560,6 +560,12 @@ class DraftOrderCreate(cls._update_shipping_price(instance, shipping_channel_listing)updated_fields.extend(SHIPPING_METHOD_UPDATE_FIELDS)+ if instance.undiscounted_base_shipping_price_amount is None:+ instance.undiscounted_base_shipping_price_amount = (+ instance.base_shipping_price_amount+ )+ updated_fields.append("undiscounted_base_shipping_price_amount")+# Save any changes create/update the draftcls._commit_changes(info, instance, cleaned_input, is_new_instance, app)diff --git a/saleor/graphql/order/mutations/utils.py b/saleor/graphql/order/mutations/utils.pyindex ee0e49e342..b0addd8f19 100644--- a/saleor/graphql/order/mutations/utils.py+++ b/saleor/graphql/order/mutations/utils.py@@ -62,6 +62,7 @@ class ShippingMethodUpdateMixin:def clear_shipping_method_from_order(cls, order):order.shipping_method = Noneorder.base_shipping_price = zero_money(order.currency)+ order.undiscounted_base_shipping_price = zero_money(order.currency)order.shipping_price = zero_taxed_money(order.currency)order.shipping_method_name = Noneorder.shipping_tax_rate = None@@ -108,6 +109,7 @@ class ShippingMethodUpdateMixin:):if not shipping_channel_listing:order.base_shipping_price = zero_money(order.currency)+ order.undiscounted_base_shipping_price = zero_money(order.currency)returnif (@@ -116,8 +118,10 @@ class ShippingMethodUpdateMixin:and order.is_shipping_required()):order.base_shipping_price = shipping_channel_listing.price+ order.undiscounted_base_shipping_price = shipping_channel_listing.priceelse:order.base_shipping_price = zero_money(order.currency)+ order.undiscounted_base_shipping_price = zero_money(order.currency)def clean_order_update_shipping(diff --git a/saleor/graphql/order/tests/deprecated/test_order.py b/saleor/graphql/order/tests/deprecated/test_order.pyindex b1e2dd61b1..8fa07e0b49 100644--- a/saleor/graphql/order/tests/deprecated/test_order.py+++ b/saleor/graphql/order/tests/deprecated/test_order.py@@ -623,7 +623,7 @@ def test_update_order_line_discount_old_id(order.refresh_from_db()order_discount = order.discounts.get()order_discount_amount = order_discount.amount- base_shipping = order.base_shipping_price+ base_shipping = order.undiscounted_base_shipping_pricediscount_applied_to_lines = order_discount_amount - (base_shipping - order.shipping_price.gross)diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.pyindex 896104189e..1671eb60f2 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py@@ -3418,3 +3418,45 @@ def test_draft_order_create_with_voucher_without_user(assert order.user is Noneassert data["order"]["voucherCode"] == voucher_percentage.code == order.voucher_codeassert data["order"]["status"] == OrderStatus.DRAFT.upper() == order.status.upper()+++def test_draft_order_create_create_no_shipping_method(+ staff_api_client,+ permission_group_manage_orders,+ variant,+ channel_USD,+ graphql_address_data,+):+ # given+ # display_gross_prices is disabled and there is no country-specific configuration+ # order.display_gross_prices should be also disabled as a result+ permission_group_manage_orders.user_set.add(staff_api_client.user)++ variant_0 = variant+ query = DRAFT_ORDER_CREATE_MUTATION++ variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)+ variant_list = [{"variantId": variant_0_id, "quantity": 2}]+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)++ variables = {+ "input": {+ "lines": variant_list,+ "billingAddress": graphql_address_data,+ "shippingAddress": graphql_address_data,+ "channelId": channel_id,+ }+ }++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["draftOrderCreate"]["errors"]+ order_id = content["data"]["draftOrderCreate"]["order"]["id"]+ _, order_pk = graphene.Node.from_global_id(order_id)++ order = Order.objects.get(id=order_pk)+ assert order.undiscounted_base_shipping_price_amount == 0+ assert order.base_shipping_price_amount == 0diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_update.py b/saleor/graphql/order/tests/mutations/test_draft_order_update.pyindex f3b63de7f5..f718bbe770 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py@@ -1805,3 +1805,38 @@ def test_draft_order_update_with_cc_warehouse_as_shipping_method(assert len(errors) == 1assert errors[0]["code"] == OrderErrorCode.INVALID.nameassert errors[0]["field"] == "shippingMethod"+++def test_draft_order_update_undiscounted_base_shipping_price_set(+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+ graphql_address_data,+):+ # given+ order = order_with_lines+ order.status = OrderStatus.DRAFT+ order.save(update_fields=["status"])++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ query = DRAFT_ORDER_UPDATE_MUTATION+ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {+ "id": order_id,+ "input": {+ "billingAddress": graphql_address_data,+ },+ }++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["draftOrderUpdate"]["errors"]++ order.refresh_from_db()+ assert (+ order.undiscounted_base_shipping_price_amount+ == order.base_shipping_price_amount+ )diff --git a/saleor/graphql/order/tests/queries/test_order.py b/saleor/graphql/order/tests/queries/test_order.pyindex a026a280c2..9bb37a33fa 100644--- a/saleor/graphql/order/tests/queries/test_order.py+++ b/saleor/graphql/order/tests/queries/test_order.py@@ -68,6 +68,9 @@ query OrdersQuery {amountcurrency}+ undiscountedShippingPrice{+ amount+ }shippingPrice {gross {amount@@ -276,10 +279,14 @@ def test_order_query():# givenorder = fulfilled_order- net = Money(amount=Decimal("10"), currency="USD")- gross = Money(amount=net.amount * Decimal(1.23), currency="USD").quantize()- shipping_price = TaxedMoney(net=net, gross=gross)+ shipping_net = Money(amount=Decimal("10"), currency="USD")+ shipping_gross = Money(+ amount=shipping_net.amount * Decimal(1.23), currency="USD"+ ).quantize()+ shipping_price = TaxedMoney(net=shipping_net, gross=shipping_gross)order.shipping_price = shipping_price+ order.base_shipping_price = shipping_net+ order.undiscounted_base_shipping_price = shipping_netshipping_tax_rate = Decimal("0.23")order.shipping_tax_rate = shipping_tax_rateprivate_value = "abc123"@@ -316,6 +323,7 @@ def test_order_query(expected_price = Money(amount=str(order_data["shippingPrice"]["gross"]["amount"]), currency="USD")+ assert order_data["undiscountedShippingPrice"]["amount"] == shipping_net.amountassert expected_price == shipping_price.grossassert order_data["shippingTaxRate"] == float(shipping_tax_rate)shipping_tax_class = order.shipping_method.tax_classdiff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 6f84c2b6ac..880fed83fa 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -1334,6 +1334,11 @@ class Order(ModelObjectType[models.Order]):description="Shipping method for this order.",deprecation_reason=(f"{DEPRECATED_IN_3X_FIELD} Use `deliveryMethod` instead."),)+ undiscounted_shipping_price = graphene.Field(+ Money,+ description="Undiscounted total price of shipping." + ADDED_IN_319,+ required=True,+ )shipping_price = graphene.Field(TaxedMoney, description="Total price of shipping.", required=True)@@ -1720,6 +1725,21 @@ class Order(ModelObjectType[models.Order]):.then(_resolve_shipping_address))+ @staticmethod+ @traced_resolver+ @prevent_sync_event_circular_query+ def resolve_undiscounted_shipping_price(root: models.Order, info):+ def _resolve_undiscounted_shipping_price(data):+ lines, manager = data+ database_connection_name = get_database_connection_name(info.context)+ return calculations.order_undiscounted_shipping(+ root, manager, lines, database_connection_name=database_connection_name+ )++ lines = OrderLinesByOrderIdLoader(info.context).load(root.id)+ manager = get_plugin_manager_promise(info.context)+ return Promise.all([lines, manager]).then(_resolve_undiscounted_shipping_price)+@staticmethod@traced_resolver@prevent_sync_event_circular_querydiff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex a14524560d..e4f7b0eba3 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -11825,6 +11825,13 @@ type Order implements Node & ObjectWithMetadata @doc(category: "Orders") {"""Shipping method for this order."""shippingMethod: ShippingMethod @deprecated(reason: "This field will be removed in Saleor 4.0. Use `deliveryMethod` instead.")+ """+ Undiscounted total price of shipping.++ Added in Saleor 3.19.+ """+ undiscountedShippingPrice: Money!+"""Total price of shipping."""shippingPrice: TaxedMoney!diff --git a/saleor/order/base_calculations.py b/saleor/order/base_calculations.pyindex a32a67e163..6530e21c9f 100644--- a/saleor/order/base_calculations.py+++ b/saleor/order/base_calculations.py@@ -94,11 +94,8 @@ def propagate_order_discount_on_order_prices(discount."""base_subtotal = base_order_subtotal(order, lines)- # TODO (SHOPX-875): add undiscounted_base_shipping_price field to Order model,- # and use it here- base_shipping_price = order.base_shipping_pricesubtotal = base_subtotal- shipping_price = base_shipping_price+ shipping_price = order.undiscounted_base_shipping_pricecurrency = order.currencyorder_discounts_to_update = []@@ -328,9 +325,8 @@ def assign_order_prices(shipping_price: Money,database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):- # TODO (SHOPX-875): set order.base_shipping_price as this price should include- # the shipping discount - must be done together with adding- # undiscounted_base_shipping_price to Order model+ shipping_price = quantize_price(shipping_price, order.currency)+ order.base_shipping_price_amount = shipping_price.amountorder.shipping_price_net_amount = shipping_price.amountorder.shipping_price_gross_amount = shipping_price.amountorder.total_net_amount = subtotal.amount + shipping_price.amountdiff --git a/saleor/order/calculations.py b/saleor/order/calculations.pyindex d89abe085b..6ed375bdb8 100644--- a/saleor/order/calculations.py+++ b/saleor/order/calculations.py@@ -89,6 +89,7 @@ def fetch_order_prices_if_expired("undiscounted_total_gross_amount","shipping_price_net_amount","shipping_price_gross_amount",+ "base_shipping_price_amount","shipping_tax_rate","should_refresh_prices","tax_error",@@ -351,8 +352,9 @@ def _recalculate_with_plugins(except TaxError:pass+ undiscounted_shipping_price = order.undiscounted_base_shipping_priceorder.undiscounted_total = undiscounted_subtotal + TaxedMoney(- net=order.base_shipping_price, gross=order.base_shipping_price+ net=undiscounted_shipping_price, gross=undiscounted_shipping_price)order.subtotal = get_subtotal(lines, order.currency)order.total = manager.calculate_order_total(order, lines, plugin_ids=plugin_ids)@@ -584,6 +586,30 @@ def order_line_unit_discount_type(return order_line.unit_discount_type+def order_undiscounted_shipping(+ order: Order,+ manager: PluginsManager,+ lines: Optional[Iterable[OrderLine]] = None,+ force_update: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+) -> TaxedMoney:+ """Return the undiscounted shipping price of the order.++ It takes into account all plugins.+ If the prices are expired, call all order price calculation methods+ and save them in the model directly.+ """+ currency = order.currency+ order, _ = fetch_order_prices_if_expired(+ order,+ manager,+ lines,+ force_update,+ database_connection_name=database_connection_name,+ )+ return quantize_price(order.undiscounted_base_shipping_price, currency)++def order_shipping(order: Order,manager: PluginsManager,diff --git a/saleor/order/migrations/0188_order_undiscounted_base_shipping_price_amount.py b/saleor/order/migrations/0188_order_undiscounted_base_shipping_price_amount.pynew file mode 100644index 0000000000..656e8b0d10--- /dev/null+++ b/saleor/order/migrations/0188_order_undiscounted_base_shipping_price_amount.py@@ -0,0 +1,19 @@+# Generated by Django 3.2.25 on 2024-07-08 08:11++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0187_merge_20240624_1245"),+ ]++ operations = [+ migrations.AddField(+ model_name="order",+ name="undiscounted_base_shipping_price_amount",+ field=models.DecimalField(+ blank=True, decimal_places=3, max_digits=12, null=True+ ),+ ),+ ]diff --git a/saleor/order/migrations/0189_merge_20240708_0813.py b/saleor/order/migrations/0189_merge_20240708_0813.pynew file mode 100644index 0000000000..8e3d8aa172--- /dev/null+++ b/saleor/order/migrations/0189_merge_20240708_0813.py@@ -0,0 +1,12 @@+# Generated by Django 3.2.25 on 2024-07-08 08:13++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0188_merge_20240624_1308"),+ ("order", "0188_order_undiscounted_base_shipping_price_amount"),+ ]++ operations = []diff --git a/saleor/order/migrations/0189_set_undiscounted_base_shipping_price.py b/saleor/order/migrations/0189_set_undiscounted_base_shipping_price.pynew file mode 100644index 0000000000..856cb16a7e--- /dev/null+++ b/saleor/order/migrations/0189_set_undiscounted_base_shipping_price.py@@ -0,0 +1,162 @@+# Generated by Django 3.2.25 on 2024-07-03 08:18++from django.db import migrations, transaction+from django.db.models import Exists, F, OuterRef, Q++# The batch of size 250 takes ~0.2 second and consumes ~20MB memory at peak+ORDER_SET_SHIPPING_PRICE_BATCH_SIZE = 250+++def set_udniscounted_base_shipping_price(apps, _schema_editor):+ Order = apps.get_model("order", "Order")+ Voucher = apps.get_model("discount", "Voucher")+ OrderDiscount = apps.get_model("discount", "OrderDiscount")+ OrderLine = apps.get_model("order", "OrderLine")++ qs = Order.objects.filter(undiscounted_base_shipping_price_amount__isnull=True)+ for batch_numbers in queryset_in_batches(qs):+ orders = Order.objects.filter(number__in=batch_numbers)++ # get orders created from checkout that has shipping discount+ # for draft orders the `base_shipping_price_amount` is the undiscounted price+ # so we can use it as a base for the undiscounted price+ orders_with_shipping_discount = _get_orders_with_shipping_discount(+ Voucher, OrderLine, OrderDiscount, orders+ )++ orders_no_shipping_discount = orders.exclude(+ Exists(orders_with_shipping_discount.filter(pk=OuterRef("pk")))+ )++ if orders_no_shipping_discount:+ _set_undiscounted_base_shipping_price(orders_no_shipping_discount)+ if orders_with_shipping_discount:+ _calculate_and_set_undiscounted_base_shipping_price(+ OrderDiscount, Order, orders_with_shipping_discount+ )+++def _get_orders_with_shipping_discount(Voucher, OrderLine, OrderDiscount, orders):+ orders_with_shipping_voucher = _get_orders_with_shipping_voucher(Voucher, orders)+ orders_with_shipping_voucher_no_voucher_instance = (+ _get_orders_with_shipping_voucher_no_voucher_instance(+ OrderLine, OrderDiscount, orders+ )+ )+ return (+ orders_with_shipping_voucher | orders_with_shipping_voucher_no_voucher_instance+ )+++def _get_orders_with_shipping_voucher(Voucher, orders):+ shipping_vouchers = Voucher.objects.filter(type="shipping")+ return orders.filter(+ origin__in=["checkout"],+ voucher_code__isnull=False,+ voucher__isnull=False,+ ).filter(Exists(shipping_vouchers.filter(pk=OuterRef("voucher_id"))))+++def _get_orders_with_shipping_voucher_no_voucher_instance(+ OrderLine, OrderDiscount, orders+):+ # lines with applied line voucher+ lines_with_voucher = OrderLine.objects.filter(voucher_code__isnull=False)++ # lines without applied order voucher on line+ # this excludes the cases when entire order voucher was applied+ # (for `ENTIRE_ORDER` voucher type, the voucher_code is stored on the order itself,+ # not on the line, but the discount is propagated to the line level and it's visible+ # in the `unit_price`)+ # - `base_unit_price_amount` is the price with the sale and line voucher applied+ # - `unit_price` is the price with all discounts applied - sales,+ # line and order voucher+ lines_with_not_applicable_voucher = OrderLine.objects.filter(+ Q(voucher_code__isnull=True)+ & (+ Q(base_unit_price_amount=F("unit_price_net_amount"))+ | Q(base_unit_price_amount=F("unit_price_gross_amount"))+ )+ )++ # order discount must be present for such orders+ order_discounts = OrderDiscount.objects.filter(+ order_id__in=orders.values("pk"), type="voucher"+ )++ # orders with voucher code, no voucher instance, without line vouchers+ # and not applicable order voucher+ return (+ orders.filter(+ origin__in=["checkout"],+ voucher_code__isnull=False,+ voucher__isnull=True,+ )+ .exclude(Exists(lines_with_voucher.filter(order_id=OuterRef("pk"))))+ .filter(+ Exists(lines_with_not_applicable_voucher.filter(order_id=OuterRef("pk")))+ )+ .filter(Exists(order_discounts.filter(order_id=OuterRef("pk"))))+ )+++def _calculate_and_set_undiscounted_base_shipping_price(OrderDiscount, Order, orders):+ order_discounts = OrderDiscount.objects.filter(+ order_id__in=orders.values("pk"), type="voucher"+ )+ order_to_discount_amount = {+ order_discount["order_id"]: order_discount["amount_value"]+ for order_discount in order_discounts.values("order_id", "amount_value")+ }+ for order in orders:+ order.undiscounted_base_shipping_price_amount = (+ order.base_shipping_price_amount + order_to_discount_amount[order.pk]+ )+ with transaction.atomic():+ _orders = list(orders.select_for_update(of=(["self"])))+ Order.objects.bulk_update(orders, ["undiscounted_base_shipping_price_amount"])+++def _set_undiscounted_base_shipping_price(orders):+ with transaction.atomic():+ _orders = list(orders.select_for_update(of=(["self"])))+ orders.update(+ undiscounted_base_shipping_price_amount=F("base_shipping_price_amount")+ )+++def queryset_in_batches(queryset):+ """Slice a queryset into batches.++ Input queryset should be sorted be pk.+ """+ start_number = None++ while True:+ lookup = {}+ if start_number is not None:+ lookup["number__gt"] = start_number+ qs = queryset.order_by("number").filter(**lookup)[+ :ORDER_SET_SHIPPING_PRICE_BATCH_SIZE+ ]+ numbers = list(qs.values_list("number", flat=True))++ if not numbers:+ break++ yield numbers++ start_number = numbers[-1]+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0188_order_undiscounted_base_shipping_price_amount"),+ ]++ operations = [+ migrations.RunPython(+ set_udniscounted_base_shipping_price,+ reverse_code=migrations.RunPython.noop,+ )+ ]diff --git a/saleor/order/migrations/0190_merge_20240708_0814.py b/saleor/order/migrations/0190_merge_20240708_0814.pynew file mode 100644index 0000000000..e5b5313e44--- /dev/null+++ b/saleor/order/migrations/0190_merge_20240708_0814.py@@ -0,0 +1,12 @@+# Generated by Django 3.2.25 on 2024-07-08 08:14++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0189_merge_20240708_0813"),+ ("order", "0189_set_undiscounted_base_shipping_price"),+ ]++ operations = []diff --git a/saleor/order/migrations/0191_alter_order_undiscounted_base_shipping_price_amount.py b/saleor/order/migrations/0191_alter_order_undiscounted_base_shipping_price_amount.pynew file mode 100644index 0000000000..c0c2498fa0--- /dev/null+++ b/saleor/order/migrations/0191_alter_order_undiscounted_base_shipping_price_amount.py@@ -0,0 +1,29 @@+# Generated by Django 3.2.25 on 2024-07-08 09:06++from decimal import Decimal++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0190_merge_20240708_0814"),+ ]++ operations = [+ migrations.AlterField(+ model_name="order",+ name="undiscounted_base_shipping_price_amount",+ field=models.DecimalField(+ decimal_places=3, default=Decimal("0.0"), max_digits=12+ ),+ ),+ migrations.RunSQL(+ """+ ALTER TABLE order_order+ ALTER COLUMN undiscounted_base_shipping_price_amount+ SET DEFAULT 0;+ """,+ migrations.RunSQL.noop,+ ),+ ]diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 76f1cb1a8e..eec2600f11 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -209,22 +209,31 @@ class Order(ModelWithMetadata, ModelWithExternalReference):amount_field="shipping_price_gross_amount", currency_field="currency")+ # Price with applied shipping voucher discountshipping_price = TaxedMoneyField(net_amount_field="shipping_price_net_amount",gross_amount_field="shipping_price_gross_amount",currency_field="currency",)- # Price with applied shipping voucher discount- # (for draft order - price without discount)- # FIXME (SHOPX-875)base_shipping_price_amount = models.DecimalField(max_digits=settings.DEFAULT_MAX_DIGITS,decimal_places=settings.DEFAULT_DECIMAL_PLACES,default=Decimal("0.0"),)+ # Shipping price with applied shipping voucher discount, without taxbase_shipping_price = MoneyField(amount_field="base_shipping_price_amount", currency_field="currency")+ undiscounted_base_shipping_price_amount = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=Decimal("0.0"),+ )+ # Shipping price before applying any discounts+ undiscounted_base_shipping_price = MoneyField(+ amount_field="undiscounted_base_shipping_price_amount",+ currency_field="currency",+ )shipping_tax_rate = models.DecimalField(max_digits=5, decimal_places=4, blank=True, null=True)diff --git a/saleor/order/tests/test_apply_order_discount.py b/saleor/order/tests/test_apply_order_discount.pyindex 7b05dd9abf..52356fed5a 100644--- a/saleor/order/tests/test_apply_order_discount.py+++ b/saleor/order/tests/test_apply_order_discount.py@@ -425,8 +425,13 @@ def test_apply_order_discounts_voucher_entire_order_and_manual_discount_fixed(# thenassert discounted_shipping_price == expected_shippingassert discounted_subtotal == expected_subtotal- assert order.total_net == expected_shipping + expected_subtotal- assert order.total_gross == expected_shipping + expected_subtotal+ assert quantize_price(order.total_net, currency) == quantize_price(+ expected_shipping + expected_subtotal, currency+ )+ assert quantize_price(order.total_gross, currency) == quantize_price(+ expected_shipping + expected_subtotal, currency+ )+ discounted_shipping_price = quantize_price(discounted_shipping_price, currency)assert order.shipping_price_net == discounted_shipping_priceassert order.shipping_price_gross == discounted_shipping_priceassert order.undiscounted_total_net == undiscounted_totaldiff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.pyindex 859888393d..8a53131b46 100644--- a/saleor/order/tests/test_calculations.py+++ b/saleor/order/tests/test_calculations.py@@ -344,6 +344,7 @@ def test_recalculate_with_plugins_order_discounts_and_total_undiscounted_price_cshipping_listing.price = new_shipping_priceshipping_listing.save(update_fields=["price_amount"])+ order.undiscounted_base_shipping_price = new_shipping_priceorder.base_shipping_price = new_shipping_priceorder.shipping_method = shipping_method_weight_basedorder.shipping_method_name = shipping_method_weight_based.name@@ -412,6 +413,7 @@ def test_recalculate_prices_total_shipping_price_changed(shipping_listing.save(update_fields=["price_amount"])order.base_shipping_price = new_shipping_price+ order.undiscounted_base_shipping_price = new_shipping_priceorder.shipping_method = shipping_method_weight_basedorder.shipping_method_name = shipping_method_weight_based.nameorder.save(@@ -828,7 +830,7 @@ def test_fetch_order_prices_when_tax_exemption_and_not_include_taxes_in_prices(assert order_with_lines.discounts.first().amount_value == expected_discount_amountsubtotal = zero_taxed_money(currency)undiscounted_subtotal = zero_taxed_money(currency)- undiscounted_shipping = order_with_lines.base_shipping_price+ undiscounted_shipping = order_with_lines.undiscounted_base_shipping_priceshipping_price = order_with_lines.shipping_priceassert shipping_price.net == undiscounted_shipping * discount / 100assert shipping_price.net == shipping_price.gross@@ -897,6 +899,7 @@ def test_fetch_order_prices_if_expired_use_base_shipping_price()expected_price = Money("2.00", currency)order.base_shipping_price = expected_price+ order.undiscounted_base_shipping_price = expected_priceorder.save()# whendiff --git a/saleor/order/tests/test_fetch_order_prices.py b/saleor/order/tests/test_fetch_order_prices.pyindex 6b6cc441c9..6efca4f243 100644--- a/saleor/order/tests/test_fetch_order_prices.py+++ b/saleor/order/tests/test_fetch_order_prices.py@@ -974,7 +974,7 @@ def test_fetch_order_prices_manual_discount_and_order_discount_flat_rates(line_2.unit_price_net_amount * tax_rate, currency)- undiscounted_shipping_price = order.base_shipping_price_amount+ undiscounted_shipping_price = order.undiscounted_base_shipping_price_amounttotal_net_amount = quantize_price(order.undiscounted_total_net_amount * discount_value / 100, currency)@@ -1115,7 +1115,7 @@ def test_fetch_order_prices_manual_discount_and_gift_discount_flat_rates(line_2.unit_price_net_amount * tax_rate, currency)- undiscounted_shipping_price = order.base_shipping_price_amount+ undiscounted_shipping_price = order.undiscounted_base_shipping_price_amounttotal_net_amount = quantize_price(order.undiscounted_total_net_amount * discount_value / 100, currency)@@ -1284,7 +1284,7 @@ def test_fetch_order_prices_manual_discount_and_catalogue_discount_flat_rates(line_2.unit_price_net_amount * tax_rate, currency)- undiscounted_shipping_price = order.base_shipping_price_amount+ undiscounted_shipping_price = order.undiscounted_base_shipping_price_amounttotal_net_amount = quantize_price((order.undiscounted_total_net_amount - catalogue_discount.amount_value)* manual_discount_value@@ -1894,7 +1894,8 @@ def test_fetch_order_prices_manual_order_discount_voucher_specific_product()assert order.undiscounted_total_gross == subtotal + shipping_priceassert order.shipping_price_gross == shipping_price - shipping_discount- assert order.base_shipping_price == shipping_price+ assert order.base_shipping_price == shipping_price - shipping_discount+ assert order.undiscounted_base_shipping_price == shipping_priceassert (discounted_line.base_unit_price_amount@@ -1956,6 +1957,7 @@ def test_fetch_order_prices_manual_order_discount_and_voucher_apply_once_per_ordlines = order.lines.all()order.voucher = voucherorder.voucher_code = voucher.codes.first().code+ order.save(update_fields=["voucher", "voucher_code"])# create manual order discountorder_discount_amount = Decimal("10")@@ -1980,6 +1982,7 @@ def test_fetch_order_prices_manual_order_discount_and_voucher_apply_once_per_ord# thendiscounted_line, line_1 = linesvoucher_discount_amount = discount_amount+ order.refresh_from_db()assert (order.total_gross_amount== subtotal.amount@@ -1995,7 +1998,8 @@ def test_fetch_order_prices_manual_order_discount_and_voucher_apply_once_per_ord)assert order.undiscounted_total_gross == subtotal + shipping_priceassert order.shipping_price_gross == shipping_price - shipping_discount- assert order.base_shipping_price == shipping_price+ assert order.base_shipping_price == shipping_price - shipping_discount+ assert order.undiscounted_base_shipping_price == shipping_priceunit_discount_amount = discount_amount / discounted_line.quantityassert (diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.pyindex c89c6a8529..d09105d06b 100644--- a/saleor/plugins/avatax/tests/test_avatax.py+++ b/saleor/plugins/avatax/tests/test_avatax.py@@ -1155,6 +1155,7 @@ def test_calculate_order_shipping_order_not_valid()order.shipping_address = Noneorder.base_shipping_price = Money("10.00", "USD")+ order.undiscounted_base_shipping_price = Money("10.00", "USD")order_set_shipping_method(order, shipping_method)order.save()diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.pyindex 9be5f01e01..8e0035c853 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py@@ -494,6 +494,7 @@ def test_draft_order_calculate_taxes_line_discount(# givenorder = order_line.orderexpected_shipping_price = Money("2.00", order.currency)+ order.undiscounted_base_shipping_price = expected_shipping_priceorder.base_shipping_price = expected_shipping_priceorder.shipping_price = TaxedMoney(net=expected_shipping_price, gross=expected_shipping_price@@ -504,6 +505,7 @@ def test_draft_order_calculate_taxes_line_discount("base_shipping_price_amount","shipping_price_net_amount","shipping_price_gross_amount",+ "undiscounted_base_shipping_price_amount","status",])@@ -588,6 +590,7 @@ def test_draft_order_calculate_taxes_entire_order_voucher(order_discount.value = discount_amountorder_discount.save(update_fields=["value"])+ order.undiscounted_base_shipping_price = expected_shipping_priceorder.base_shipping_price = expected_shipping_priceorder.shipping_price = TaxedMoney(net=expected_shipping_price, gross=expected_shipping_price@@ -597,6 +600,7 @@ def test_draft_order_calculate_taxes_entire_order_voucher("base_shipping_price_amount","shipping_price_net_amount","shipping_price_gross_amount",+ "undiscounted_base_shipping_price_amount",])@@ -669,6 +673,7 @@ def test_draft_order_calculate_taxes_apply_once_per_order_voucher(order_discount.value = discount_amountorder_discount.save(update_fields=["value"])+ order.undiscounted_base_shipping_price = expected_shipping_priceorder.base_shipping_price = expected_shipping_priceorder.shipping_price = TaxedMoney(net=expected_shipping_price, gross=expected_shipping_price@@ -678,6 +683,7 @@ def test_draft_order_calculate_taxes_apply_once_per_order_voucher("base_shipping_price_amount","shipping_price_net_amount","shipping_price_gross_amount",+ "undiscounted_base_shipping_price_amount",])@@ -746,6 +752,7 @@ def test_order_calculate_taxes_specific_product_voucher(order = order_line.orderwebhook = subscription_calculate_taxes_for_orderexpected_shipping_price = Money("2.00", order.currency)+ order.undiscounted_base_shipping_price = expected_shipping_priceorder.base_shipping_price = expected_shipping_priceorder.shipping_price = TaxedMoney(net=expected_shipping_price, gross=expected_shipping_price@@ -758,6 +765,7 @@ def test_order_calculate_taxes_specific_product_voucher("base_shipping_price_amount","shipping_price_net_amount","shipping_price_gross_amount",+ "undiscounted_base_shipping_price_amount","voucher_code","voucher","status",diff --git a/saleor/tax/calculations/order.py b/saleor/tax/calculations/order.pyindex d05c7bf174..dda9487bc1 100644--- a/saleor/tax/calculations/order.py+++ b/saleor/tax/calculations/order.py@@ -102,7 +102,7 @@ def _set_order_totals(shipping_tax_rate = order.shipping_tax_rate or 0undiscounted_shipping_price = calculate_flat_rate_tax(- order.base_shipping_price,+ order.undiscounted_base_shipping_price,Decimal(shipping_tax_rate * 100),prices_entered_with_tax,)diff --git a/saleor/tax/tests/test_order_calculations.py b/saleor/tax/tests/test_order_calculations.pyindex 4c139f2c98..d32084f7ba 100644--- a/saleor/tax/tests/test_order_calculations.py+++ b/saleor/tax/tests/test_order_calculations.py@@ -330,7 +330,9 @@ def test_calculate_order_shipping(order_line, shipping_zone):order.shipping_address = order.billing_address.get_copy()order.shipping_method_name = method.nameorder.shipping_method = method- order.base_shipping_price = method.channel_listings.get(channel=order.channel).price+ base_shipping_price = method.channel_listings.get(channel=order.channel).price+ order.base_shipping_price = base_shipping_price+ order.undiscounted_base_shipping_price = base_shipping_priceorder.save()apply_order_discounts(order, lines)diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 05816d92ac..b897876953 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -5084,6 +5084,7 @@ def order_with_lines(gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)order.shipping_price = TaxedMoney(net=net, gross=gross)order.base_shipping_price = net+ order.undiscounted_base_shipping_price = netorder.shipping_tax_rate = calculate_tax_rate(order.shipping_price)order.save()@@ -5478,6 +5479,7 @@ def order_with_lines_channel_PLN(gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)order.shipping_price = TaxedMoney(net=net, gross=gross)order.base_shipping_price = net+ order.undiscounted_base_shipping_price = netorder.shipping_tax_rate = calculate_tax_rate(order.shipping_price)order.save()@@ -5594,6 +5596,7 @@ def order_with_preorder_lines(gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)order.shipping_price = TaxedMoney(net=net, gross=gross)order.base_shipping_price = net+ order.undiscounted_base_shipping_price = netorder.save()recalculate_order(order)