Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix missing subtotal for orders created from orderBulkCreate (#16827)
Maciej Korycinski7a1b06ec9104
diff --git a/saleor/graphql/order/bulk_mutations/order_bulk_create.py b/saleor/graphql/order/bulk_mutations/order_bulk_create.pyindex af71976b02..e64d016b86 100644--- a/saleor/graphql/order/bulk_mutations/order_bulk_create.py+++ b/saleor/graphql/order/bulk_mutations/order_bulk_create.py@@ -259,6 +259,8 @@ class OrderAmounts:shipping_price_net: Decimaltotal_gross: Decimaltotal_net: Decimal+ subtotal_net: Decimal+ subtotal_gross: Decimalundiscounted_total_gross: Decimalundiscounted_total_net: Decimalshipping_tax_rate: Decimal@@ -1180,14 +1182,16 @@ class OrderBulkCreate(BaseMutation, I18nMixin):if shipping_price_gross_amount < shipping_price_net_amount:order_data.errors.append(OrderBulkError(- message="Net price can't be greater then gross price.",+ message="Net price can't be greater than gross price.",path="delivery_method.shipping_price",code=OrderBulkCreateErrorCode.PRICE_ERROR,))order_data.is_critical_error = Trueshipping_tax_rate = (- shipping_price_gross_amount / shipping_price_net_amount - 1+ (shipping_price_gross_amount / shipping_price_net_amount - 1)+ if shipping_price_net_amount+ else Decimal(0))else:assert order_data.channel@@ -1211,16 +1215,16 @@ class OrderBulkCreate(BaseMutation, I18nMixin):# Calculate linesorder_lines = order_data.all_order_lines- order_total_gross_amount = Decimal(+ order_subtotal_gross_amount = Decimal(sum(line.total_price_gross_amount for line in order_lines))- order_undiscounted_total_gross_amount = Decimal(+ order_undiscounted_subtotal_gross_amount = Decimal(sum(line.undiscounted_total_price_gross_amount for line in order_lines))- order_total_net_amount = Decimal(+ order_subtotal_net_amount = Decimal(sum(line.total_price_net_amount for line in order_lines))- order_undiscounted_total_net_amount = Decimal(+ order_undiscounted_subtotal_net_amount = Decimal(sum(line.undiscounted_total_price_net_amount for line in order_lines))@@ -1228,10 +1232,14 @@ class OrderBulkCreate(BaseMutation, I18nMixin):shipping_price_gross=shipping_price_gross_amount,shipping_price_net=shipping_price_net_amount,shipping_tax_rate=shipping_tax_rate,- total_gross=order_total_gross_amount,- total_net=order_total_net_amount,- undiscounted_total_gross=order_undiscounted_total_gross_amount,- undiscounted_total_net=order_undiscounted_total_net_amount,+ total_gross=order_subtotal_gross_amount + shipping_price_gross_amount,+ total_net=order_subtotal_net_amount + shipping_price_net_amount,+ subtotal_net=order_subtotal_net_amount,+ subtotal_gross=order_subtotal_gross_amount,+ undiscounted_total_gross=order_undiscounted_subtotal_gross_amount+ + shipping_price_gross_amount,+ undiscounted_total_net=order_undiscounted_subtotal_net_amount+ + shipping_price_net_amount,)@classmethod@@ -1989,6 +1997,9 @@ class OrderBulkCreate(BaseMutation, I18nMixin):order_data.order.undiscounted_total_net_amount = (order_amounts.undiscounted_total_net)+ order_data.order.subtotal_net_amount = order_amounts.subtotal_net+ order_data.order.subtotal_gross_amount = order_amounts.subtotal_gross+order_data.order.customer_note = order_input.get("customer_note") or ""order_data.order.redirect_url = order_input.get("redirect_url")order_data.order.origin = OrderOrigin.BULK_CREATEdiff --git a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py b/saleor/graphql/order/tests/mutations/test_order_bulk_create.pyindex c357373221..ae05949cd9 100644--- a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py+++ b/saleor/graphql/order/tests/mutations/test_order_bulk_create.py@@ -9,6 +9,7 @@ from django.utils import timezonefrom .....account.models import Addressfrom .....core import JobStatus+from .....core.prices import quantize_pricefrom .....discount.models import OrderDiscountfrom .....invoice.models import Invoicefrom .....order import (@@ -162,6 +163,14 @@ ORDER_BULK_CREATE = """amount}}+ subtotal{+ gross {+ amount+ }+ net {+ amount+ }+ }total{gross {amount@@ -301,8 +310,8 @@ def order_bulk_input(),"shippingTaxClassName": "Denormalized name","shippingPrice": {- "gross": 120,- "net": 100,+ "gross": 60,+ "net": 50,},"shippingTaxRate": 0.2,"shippingTaxClassMetadata": [@@ -510,6 +519,29 @@ def test_order_bulk_create(discount_count = OrderDiscount.objects.count()voucher_code = "mirumee"+ expected_shipping_net_price = Decimal(50)+ expected_shipping_gross_price = Decimal(60)++ expected_order_line_quantity = Decimal(5)+ expected_order_line_unit_net = Decimal(20)+ expected_order_line_unit_gross = Decimal(24)+ expected_order_line_total_net = Decimal(100)+ expected_order_line_total_gross = Decimal(120)++ expected_order_subtotal_net = quantize_price(+ expected_order_line_unit_net * expected_order_line_quantity,+ channel_PLN.currency_code,+ )+ expected_order_subtotal_gross = quantize_price(+ expected_order_line_unit_gross * expected_order_line_quantity,+ channel_PLN.currency_code,+ )++ expected_order_total_gross = (+ expected_order_subtotal_gross + expected_shipping_gross_price+ )+ expected_order_total_net = expected_order_subtotal_net + expected_shipping_net_price+order = order_bulk_inputorder["externalReference"] = "ext-ref-1"@@ -543,12 +575,14 @@ def test_order_bulk_create(assert order["shippingTaxClassMetadata"][0]["value"] == "md value"assert order["shippingTaxClassPrivateMetadata"][0]["key"] == "pmd key"assert order["shippingTaxClassPrivateMetadata"][0]["value"] == "pmd value"- assert order["shippingPrice"]["gross"]["amount"] == 120- assert order["shippingPrice"]["net"]["amount"] == 100- assert order["total"]["gross"]["amount"] == 120- assert order["total"]["net"]["amount"] == 100- assert order["undiscountedTotal"]["gross"]["amount"] == 120- assert order["undiscountedTotal"]["net"]["amount"] == 100+ assert order["shippingPrice"]["gross"]["amount"] == expected_shipping_gross_price+ assert order["shippingPrice"]["net"]["amount"] == expected_shipping_net_price+ assert order["subtotal"]["gross"]["amount"] == expected_order_subtotal_gross+ assert order["subtotal"]["net"]["amount"] == expected_order_subtotal_net+ assert order["total"]["gross"]["amount"] == expected_order_total_gross+ assert order["total"]["net"]["amount"] == expected_order_total_net+ assert order["undiscountedTotal"]["gross"]["amount"] == expected_order_total_gross+ assert order["undiscountedTotal"]["net"]["amount"] == expected_order_total_netassert order["redirectUrl"] == "https://www.example.com"assert order["origin"] == OrderOrigin.BULK_CREATE.upper()assert order["weight"]["value"] == 10.15@@ -576,14 +610,18 @@ def test_order_bulk_create(assert db_order.shipping_tax_rate == Decimal("0.2")assert db_order.shipping_tax_class_metadata["md key"] == "md value"assert db_order.shipping_tax_class_private_metadata["pmd key"] == "pmd value"- assert db_order.shipping_price_gross_amount == 120- assert db_order.shipping_price_net_amount == 100- assert db_order.base_shipping_price_amount == 100- assert db_order.undiscounted_base_shipping_price_amount == 100- assert db_order.total_gross_amount == 120- assert db_order.total_net_amount == 100- assert db_order.undiscounted_total_gross_amount == 120- assert db_order.undiscounted_total_net_amount == 100+ assert db_order.shipping_price_gross_amount == expected_shipping_gross_price+ assert db_order.shipping_price_net_amount == expected_shipping_net_price+ assert db_order.base_shipping_price_amount == expected_shipping_net_price+ assert (+ db_order.undiscounted_base_shipping_price_amount == expected_shipping_net_price+ )+ assert db_order.subtotal_gross_amount == expected_order_subtotal_gross+ assert db_order.subtotal_net_amount == expected_order_subtotal_net+ assert db_order.total_gross_amount == expected_order_total_gross+ assert db_order.total_net_amount == expected_order_total_net+ assert db_order.undiscounted_total_gross_amount == expected_order_total_gross+ assert db_order.undiscounted_total_net_amount == expected_order_total_netassert db_order.redirect_url == "https://www.example.com"assert db_order.origin == OrderOrigin.BULK_CREATEassert db_order.weight.g == 10.15 * 1000@@ -609,15 +647,23 @@ def test_order_bulk_create(assert order_line["translatedProductName"] == "Nazwa Produktu"assert order_line["translatedVariantName"] == "Nazwa Wariantu"assert order_line["isShippingRequired"]- assert order_line["quantity"] == 5+ assert order_line["quantity"] == expected_order_line_quantityassert order_line["quantityFulfilled"] == 5- assert order_line["unitPrice"]["gross"]["amount"] == Decimal(120 / 5)- assert order_line["unitPrice"]["net"]["amount"] == Decimal(100 / 5)- assert order_line["undiscountedUnitPrice"]["gross"]["amount"] == Decimal(120 / 5)- assert order_line["undiscountedUnitPrice"]["net"]["amount"] == Decimal(100 / 5)+ assert order_line["unitPrice"]["gross"]["amount"] == expected_order_line_unit_gross+ assert order_line["unitPrice"]["net"]["amount"] == expected_order_line_unit_net+ assert (+ order_line["undiscountedUnitPrice"]["gross"]["amount"]+ == expected_order_line_unit_gross+ )+ assert (+ order_line["undiscountedUnitPrice"]["net"]["amount"]+ == expected_order_line_unit_net+ )assert order_line["unitDiscount"]["amount"] == 0- assert order_line["totalPrice"]["gross"]["amount"] == 120- assert order_line["totalPrice"]["net"]["amount"] == 100+ assert (+ order_line["totalPrice"]["gross"]["amount"] == expected_order_line_total_gross+ )+ assert order_line["totalPrice"]["net"]["amount"] == expected_order_line_total_netassert order_line["metadata"][0]["key"] == "md key"assert order_line["metadata"][0]["value"] == "md value"assert order_line["privateMetadata"][0]["key"] == "pmd key"@@ -639,17 +685,28 @@ def test_order_bulk_create(assert db_order_line.translated_product_name == "Nazwa Produktu"assert db_order_line.translated_variant_name == "Nazwa Wariantu"assert db_order_line.is_shipping_required- assert db_order_line.quantity == 5+ assert db_order_line.quantity == expected_order_line_quantityassert db_order_line.quantity_fulfilled == 5- assert db_order_line.unit_price.gross.amount == Decimal(120 / 5)- assert db_order_line.unit_price.net.amount == Decimal(100 / 5)- assert db_order_line.undiscounted_unit_price.gross.amount == Decimal(120 / 5)- assert db_order_line.undiscounted_unit_price.net.amount == Decimal(100 / 5)+ assert db_order_line.unit_price.gross.amount == expected_order_line_unit_gross+ assert db_order_line.unit_price.net.amount == expected_order_line_unit_net+ assert (+ db_order_line.undiscounted_unit_price.gross.amount+ == expected_order_line_unit_gross+ )+ assert (+ db_order_line.undiscounted_unit_price.net.amount == expected_order_line_unit_net+ )assert db_order_line.unit_discount_amount == 0- assert db_order_line.total_price.gross.amount == 120- assert db_order_line.total_price.net.amount == 100- assert db_order_line.undiscounted_total_price.gross.amount == 120- assert db_order_line.undiscounted_total_price.net.amount == 100+ assert db_order_line.total_price.gross.amount == expected_order_line_total_gross+ assert db_order_line.total_price.net.amount == expected_order_line_total_net+ assert (+ db_order_line.undiscounted_total_price.gross.amount+ == expected_order_line_total_gross+ )+ assert (+ db_order_line.undiscounted_total_price.net.amount+ == expected_order_line_total_net+ )assert db_order_line.metadata["md key"] == "md value"assert db_order_line.private_metadata["pmd key"] == "pmd value"assert db_order_line.tax_class == default_tax_class@@ -815,19 +872,55 @@ def test_order_bulk_create_multiple_lines(permission_manage_orders_import,order_bulk_input,product_variant_list,+ channel_PLN,):# givenlines_count = OrderLine.objects.count()order = order_bulk_input++ assert len(order["lines"]) == 1++ expected_shipping_net_price = Decimal(50)+ expected_shipping_gross_price = Decimal(60)++ expected_first_order_line_quantity = Decimal(5)+ expected_first_order_line_unit_net = Decimal(20)+ expected_first_order_line_unit_gross = Decimal(24)++ expected_second_order_line_quantity = Decimal(3)+ expected_second_order_line_unit_net = Decimal(10)+ expected_second_order_line_unit_gross = Decimal(12)+line_2 = copy.deepcopy(order["lines"][0])variant_2 = product_variant_list[2]line_2["variantId"] = graphene.Node.to_global_id("ProductVariant", variant_2.id)- line_2["totalPrice"]["gross"] = 60- line_2["totalPrice"]["net"] = 50+ line_2["totalPrice"]["gross"] = (+ expected_second_order_line_unit_gross * expected_second_order_line_quantity+ )+ line_2["totalPrice"]["net"] = (+ expected_second_order_line_unit_net * expected_second_order_line_quantity+ )+ line_2["quantity"] = expected_second_order_line_quantityline_2["productSku"] = "TEST-SKU"order["lines"].append(line_2)+ expected_order_subtotal_net = quantize_price(+ expected_first_order_line_unit_net * expected_first_order_line_quantity+ + expected_second_order_line_unit_net * expected_second_order_line_quantity,+ channel_PLN.currency_code,+ )+ expected_order_subtotal_gross = quantize_price(+ expected_first_order_line_unit_gross * expected_first_order_line_quantity+ + expected_second_order_line_unit_gross * expected_second_order_line_quantity,+ channel_PLN.currency_code,+ )++ expected_order_total_gross = (+ expected_order_subtotal_gross + expected_shipping_gross_price+ )+ expected_order_total_net = expected_order_subtotal_net + expected_shipping_net_price+staff_api_client.user.user_permissions.add(permission_manage_orders_import,permission_manage_orders,@@ -847,29 +940,33 @@ def test_order_bulk_create_multiple_lines(order = content["data"]["orderBulkCreate"]["results"][0]["order"]line_1 = order["lines"][0]- assert line_1["unitPrice"]["gross"]["amount"] == Decimal(120 / 5)- assert line_1["unitPrice"]["net"]["amount"] == Decimal(100 / 5)+ assert (+ line_1["unitPrice"]["gross"]["amount"] == expected_first_order_line_unit_gross+ )+ assert line_1["unitPrice"]["net"]["amount"] == expected_first_order_line_unit_netassert line_1["productSku"] is Noneline_2 = order["lines"][1]- assert line_2["unitPrice"]["gross"]["amount"] == Decimal(60 / 5)- assert line_2["unitPrice"]["net"]["amount"] == Decimal(50 / 5)+ assert (+ line_2["unitPrice"]["gross"]["amount"] == expected_second_order_line_unit_gross+ )+ assert line_2["unitPrice"]["net"]["amount"] == expected_second_order_line_unit_netassert line_2["productSku"] == "TEST-SKU"db_lines = OrderLine.objects.all()db_line_1 = db_lines[0]- assert db_line_1.unit_price.gross.amount == Decimal(120 / 5)- assert db_line_1.unit_price.net.amount == Decimal(100 / 5)+ assert db_line_1.unit_price.gross.amount == expected_first_order_line_unit_gross+ assert db_line_1.unit_price.net.amount == expected_first_order_line_unit_netassert db_line_1.product_sku is Nonedb_line_2 = db_lines[1]- assert db_line_2.unit_price.gross.amount == Decimal(60 / 5)- assert db_line_2.unit_price.net.amount == Decimal(50 / 5)+ assert db_line_2.unit_price.gross.amount == expected_second_order_line_unit_gross+ assert db_line_2.unit_price.net.amount == expected_second_order_line_unit_netassert db_line_2.product_sku == "TEST-SKU"- assert order["total"]["gross"]["amount"] == 180- assert order["total"]["net"]["amount"] == 150+ assert order["total"]["gross"]["amount"] == expected_order_total_gross+ assert order["total"]["net"]["amount"] == expected_order_total_netdb_order = Order.objects.get()- assert db_order.total_gross_amount == 180- assert db_order.total_net_amount == 150+ assert db_order.total_gross_amount == expected_order_total_gross+ assert db_order.total_net_amount == expected_order_total_netassert OrderLine.objects.count() == lines_count + 2@@ -879,6 +976,7 @@ def test_order_bulk_create_line_without_variant(permission_manage_orders,permission_manage_orders_import,order_bulk_input,+ channel_PLN,):# givenlines_count = OrderLine.objects.count()@@ -888,6 +986,27 @@ def test_order_bulk_create_line_without_variant(order["lines"][0]["variantName"] = Noneorder["fulfillments"][0]["lines"][0]["variantId"] = None+ expected_shipping_net_price = Decimal(50)+ expected_shipping_gross_price = Decimal(60)++ expected_order_line_quantity = Decimal(5)+ expected_order_line_unit_net = Decimal(20)+ expected_order_line_unit_gross = Decimal(24)++ expected_order_subtotal_net = quantize_price(+ expected_order_line_unit_net * expected_order_line_quantity,+ channel_PLN.currency_code,+ )+ expected_order_subtotal_gross = quantize_price(+ expected_order_line_unit_gross * expected_order_line_quantity,+ channel_PLN.currency_code,+ )++ expected_order_total_gross = (+ expected_order_subtotal_gross + expected_shipping_gross_price+ )+ expected_order_total_net = expected_order_subtotal_net + expected_shipping_net_price+staff_api_client.user.user_permissions.add(permission_manage_orders_import,permission_manage_orders,@@ -909,19 +1028,19 @@ def test_order_bulk_create_line_without_variant(order = content["data"]["orderBulkCreate"]["results"][0]["order"]line_1 = order["lines"][0]- assert line_1["unitPrice"]["gross"]["amount"] == Decimal(120 / 5)- assert line_1["unitPrice"]["net"]["amount"] == Decimal(100 / 5)+ assert line_1["unitPrice"]["gross"]["amount"] == expected_order_line_unit_gross+ assert line_1["unitPrice"]["net"]["amount"] == expected_order_line_unit_netdb_lines = OrderLine.objects.all()db_line_1 = db_lines[0]- assert db_line_1.unit_price.gross.amount == Decimal(120 / 5)- assert db_line_1.unit_price.net.amount == Decimal(100 / 5)+ assert db_line_1.unit_price.gross.amount == expected_order_line_unit_gross+ assert db_line_1.unit_price.net.amount == expected_order_line_unit_net- assert order["total"]["gross"]["amount"] == 120- assert order["total"]["net"]["amount"] == 100+ assert order["total"]["gross"]["amount"] == expected_order_total_gross+ assert order["total"]["net"]["amount"] == expected_order_total_netdb_order = Order.objects.get()- assert db_order.total_gross_amount == 120- assert db_order.total_net_amount == 100+ assert db_order.total_gross_amount == expected_order_total_gross+ assert db_order.total_net_amount == expected_order_total_neterror0 = content["data"]["orderBulkCreate"]["results"][0]["errors"][0]assert error0["message"] == (@@ -1157,34 +1276,37 @@ def test_order_bulk_create_multiple_transactions():# giventransactions_count = TransactionItem.objects.count()-+ authorized_amount = Decimal("80")transaction_1 = {- "name": "Authorized for 10$",+ "name": "Authorized for 80$","amountAuthorized": {- "amount": Decimal("20"),+ "amount": authorized_amount,"currency": "PLN",},}+ charged_amount = Decimal("100")transaction_2 = {"message": "Credit Card","amountCharged": {- "amount": Decimal("100"),+ "amount": charged_amount,"currency": "PLN",},}+ refunded_amount = Decimal("15")transaction_3 = {"pspReference": "PSP reference - 123","amountRefunded": {- "amount": Decimal("15"),+ "amount": refunded_amount,"currency": "PLN",},}+ canceled_amount = Decimal("20")transaction_4 = {"amountCanceled": {- "amount": Decimal("20"),+ "amount": canceled_amount,"currency": "PLN",},}@@ -1216,15 +1338,15 @@ def test_order_bulk_create_multiple_transactions(order = data[0]["order"]transaction_1, transaction_2, transaction_3, transaction_4 = order["transactions"]- assert transaction_1["name"] == "Authorized for 10$"- assert transaction_1["authorizedAmount"]["amount"] == Decimal("20")+ assert transaction_1["name"] == "Authorized for 80$"+ assert transaction_1["authorizedAmount"]["amount"] == authorized_amountassert transaction_2["message"] == "Credit Card"- assert transaction_2["chargedAmount"]["amount"] == Decimal("100")+ assert transaction_2["chargedAmount"]["amount"] == charged_amountassert transaction_2["chargedAmount"]["currency"] == "PLN"assert transaction_3["pspReference"] == "PSP reference - 123"- assert transaction_3["refundedAmount"]["amount"] == Decimal("15")+ assert transaction_3["refundedAmount"]["amount"] == refunded_amountassert transaction_3["refundedAmount"]["currency"] == "PLN"- assert transaction_4["canceledAmount"]["amount"] == Decimal("20")+ assert transaction_4["canceledAmount"]["amount"] == canceled_amountassert transaction_4["canceledAmount"]["currency"] == "PLN"db_order = Order.objects.get()@@ -1234,20 +1356,20 @@ def test_order_bulk_create_multiple_transactions(db_transaction_3,db_transaction_4,) = TransactionItem.objects.all()- assert db_transaction_1.name == "Authorized for 10$"- assert db_transaction_1.authorized_value == Decimal("20")+ assert db_transaction_1.name == "Authorized for 80$"+ assert db_transaction_1.authorized_value == authorized_amountassert db_transaction_2.message == "Credit Card"- assert db_transaction_2.charged_value == Decimal("100")+ assert db_transaction_2.charged_value == charged_amountassert db_transaction_3.psp_reference == "PSP reference - 123"- assert db_transaction_3.refunded_value == Decimal("15")- assert db_transaction_4.canceled_value == Decimal("20")+ assert db_transaction_3.refunded_value == refunded_amount+ assert db_transaction_4.canceled_value == canceled_amountassert db_transaction_1.order_id == db_order.idassert db_transaction_2.order_id == db_order.idassert db_transaction_3.order_id == db_order.idassert db_transaction_4.order_id == db_order.id- assert db_order.total_authorized_amount == Decimal("20")- assert db_order.total_charged_amount == Decimal("100")+ assert db_order.total_authorized_amount == authorized_amount+ assert db_order.total_charged_amount == charged_amountassert db_order.authorize_status == OrderAuthorizeStatus.FULL.lower()assert db_order.charge_status == OrderChargeStatus.PARTIAL.lower()@@ -3163,7 +3285,7 @@ def test_order_bulk_create_error_invoice_invalid_url([(DiscountValueTypeEnum.FIXED.name,- "The value (999999) cannot be higher than 120 PLN",+ "The value (999999) cannot be higher than 180 PLN",),(DiscountValueTypeEnum.PERCENTAGE.name,@@ -3769,3 +3891,41 @@ def test_order_bulk_create_skip_address_validation(assert db_order.shipping_address.validation_skipped is Trueassert db_order.billing_address.postal_code == invalid_postal_codeassert db_order.billing_address.validation_skipped is True+++def test_order_bulk_create_shipping_price_zero(+ staff_api_client,+ permission_manage_orders,+ permission_manage_orders_import,+ order_bulk_input,+):+ # given+ order_data = order_bulk_input+ order_data["deliveryMethod"]["shippingPrice"] = {+ "gross": 0,+ "net": 0,+ }++ staff_api_client.user.user_permissions.add(+ permission_manage_orders_import,+ permission_manage_orders,+ )+ variables = {+ "orders": [order_data],+ "stockUpdatePolicy": StockUpdatePolicyEnum.SKIP.name,+ }++ # when+ response = staff_api_client.post_graphql(ORDER_BULK_CREATE, variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["orderBulkCreate"]["results"][0]+ assert not data["errors"]+ order_data = data["order"]+ assert order_data["shippingPrice"]["gross"]["amount"] == 0+ assert order_data["shippingPrice"]["net"]["amount"] == 0++ db_order = Order.objects.last()+ assert db_order.shipping_price_net_amount == 0+ assert db_order.shipping_price_gross_amount == 0diff --git a/saleor/order/migrations/0193_fix_subtotal_value_for_order_from_bulk.py b/saleor/order/migrations/0193_fix_subtotal_value_for_order_from_bulk.pynew file mode 100644index 0000000000..34a350effb--- /dev/null+++ b/saleor/order/migrations/0193_fix_subtotal_value_for_order_from_bulk.py@@ -0,0 +1,193 @@+# Generated by Django 3.2.25 on 2024-08-05 07:27+from decimal import Decimal++from babel.numbers import get_currency_precision+from django.db import migrations, transaction+from django.db.models import Exists, OuterRef, Sum++# The batch of size 100 takes ~0.2 second and consumes 6.5MB memory+ORDER_SET_SUBTOTAL_PRICE_FOR_ORDER_FROM_BULK = 100+++def quantize_price(price, currency):+ precision = get_currency_precision(currency)+ number_places = Decimal(10) ** -precision+ return price.quantize(number_places)+++def update_order_authorize_status(order, granted_refund_amount):+ """Update the current authorize status for the order.++ The order is fully authorized when total_authorized or total_charged funds+ cover the order.total - order granted refunds+ The order is partially authorized when total_authorized or total_charged+ funds cover only part of the order.total - order granted refunds+ The order is not authorized when total_authorized and total_charged funds are 0.+ """+ total_covered = (+ order.total_authorized_amount + order.total_charged_amount+ ) or Decimal(0)+ total_covered = quantize_price(total_covered, order.currency)+ current_total_gross = order.total_gross_amount - granted_refund_amount+ current_total_gross = max(current_total_gross, Decimal("0"))+ current_total_gross = quantize_price(current_total_gross, order.currency)++ if total_covered == Decimal(0) and order.total.gross.amount == Decimal(0):+ order.authorize_status = "full"+ elif total_covered == Decimal(0):+ order.authorize_status = "none"+ elif total_covered >= current_total_gross:+ order.authorize_status = "full"+ else:+ order.authorize_status = "partial"+++def update_order_charge_status(order, granted_refund_amount):+ """Update the current charge status for the order.++ We treat the order as overcharged when the charged amount is bigger that+ order.total - order granted refund+ We treat the order as fully charged when the charged amount is equal to+ order.total - order granted refund.+ We treat the order as partially charged when the charged amount covers only part of+ the order.total - order granted refund+ We treat the order as not charged when the charged amount is 0.+ """+ total_charged = order.total_charged_amount or Decimal("0")+ total_charged = quantize_price(total_charged, order.currency)++ current_total_gross = order.total_gross_amount - granted_refund_amount+ current_total_gross = max(current_total_gross, Decimal("0"))+ current_total_gross = quantize_price(current_total_gross, order.currency)++ if total_charged == current_total_gross:+ order.charge_status = "full"+ elif total_charged <= Decimal(0):+ order.charge_status = "none"+ elif total_charged < current_total_gross:+ order.charge_status = "partial"+ else:+ order.charge_status = "overcharged"+++def _set_subtotal_for_orders_created_from_bulk(orders, order_model):+ order_ids = set()+ for order in orders:+ order.subtotal_net_amount = order.sum_line_total_price_net_amount+ order.subtotal_gross_amount = order.sum_line_total_price_gross_amount+ order.total_net_amount = (+ order.subtotal_net_amount + order.shipping_price_net_amount+ )+ order.total_gross_amount = (+ order.subtotal_gross_amount + order.shipping_price_gross_amount+ )++ # using order.shipping_price as this value is used for storing undiscounted+ # shipping price, received as mutation input or fetched from db.+ order.undiscounted_total_net_amount = (+ order.sum_line_undiscounted_total_price_net_amount+ + order.shipping_price_net_amount+ )+ order.undiscounted_total_gross_amount = (+ order.sum_line_undiscounted_total_price_gross_amount+ + order.shipping_price_gross_amount+ )+ update_order_authorize_status(+ order, granted_refund_amount=order.sum_granted_refunds or Decimal(0)+ )+ update_order_charge_status(+ order, granted_refund_amount=order.sum_granted_refunds or Decimal(0)+ )+ order_ids.add(order.id)++ with transaction.atomic():+ _orders = list(+ order_model.objects.filter(id__in=order_ids).select_for_update(+ of=(["self"])+ )+ )+ order_model.objects.bulk_update(+ orders,+ [+ "subtotal_net_amount",+ "subtotal_gross_amount",+ "total_net_amount",+ "total_gross_amount",+ "undiscounted_total_gross_amount",+ "undiscounted_total_net_amount",+ "charge_status",+ "authorize_status",+ ],+ )+++def fix_order_subtotal_for_orders_from_bulk(apps, _schema_editor):+ Order = apps.get_model("order", "Order")+ OrderLine = apps.get_model("order", "OrderLine")++ order_lines_qs = OrderLine.objects.filter(total_price_gross_amount__gt=0).values(+ "order_id"+ )+ qs = Order.objects.filter(+ Exists(order_lines_qs.filter(order_id=OuterRef("id"))),+ origin="bulk_create",+ subtotal_gross_amount=Decimal(0),+ )+ for batch_numbers in queryset_in_batches(qs):+ orders = (+ Order.objects.prefetch_related(+ "payments", "payment_transactions", "granted_refunds"+ )+ .filter(number__in=batch_numbers)+ .annotate(+ sum_line_total_price_net_amount=Sum("lines__total_price_net_amount"),+ sum_line_total_price_gross_amount=Sum(+ "lines__total_price_gross_amount"+ ),+ sum_line_undiscounted_total_price_net_amount=Sum(+ "lines__undiscounted_total_price_net_amount"+ ),+ sum_line_undiscounted_total_price_gross_amount=Sum(+ "lines__undiscounted_total_price_gross_amount"+ ),+ sum_granted_refunds=Sum("granted_refunds__amount_value"),+ )+ )+ _set_subtotal_for_orders_created_from_bulk(orders, order_model=Order)+++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_SUBTOTAL_PRICE_FOR_ORDER_FROM_BULK+ ]+ numbers = list(qs.values_list("number", flat=True))++ if not numbers:+ break++ yield numbers++ start_number = numbers[-1]+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0192_set_undiscounted_base_shipping_price_on_draft_orders"),+ ]++ operations = [+ migrations.RunPython(+ fix_order_subtotal_for_orders_from_bulk,+ reverse_code=migrations.RunPython.noop,+ )+ ]diff --git a/saleor/order/migrations/0195_merge_20241014_0617.py b/saleor/order/migrations/0195_merge_20241014_0617.pynew file mode 100644index 0000000000..c043ebeb8c--- /dev/null+++ b/saleor/order/migrations/0195_merge_20241014_0617.py@@ -0,0 +1,12 @@+# Generated by Django 4.2.16 on 2024-10-14 06:17++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0193_fix_subtotal_value_for_order_from_bulk"),+ ("order", "0194_alter_orderevent_type"),+ ]++ operations = []diff --git a/saleor/order/migrations/0196_merge_20241014_0631.py b/saleor/order/migrations/0196_merge_20241014_0631.pynew file mode 100644index 0000000000..e38e6ec8e3--- /dev/null+++ b/saleor/order/migrations/0196_merge_20241014_0631.py@@ -0,0 +1,12 @@+# Generated by Django 4.2.15 on 2024-10-14 06:31++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0195_merge_20241004_0811"),+ ("order", "0195_merge_20241014_0617"),+ ]++ operations = []