Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Extend `Order` model with `lines_count` (#17787)
Iga Karbowiaka1f6a5306b28
diff --git a/saleor/account/tests/test_account.py b/saleor/account/tests/test_account.pyindex 12eff12a50..36507eaddd 100644--- a/saleor/account/tests/test_account.py+++ b/saleor/account/tests/test_account.py@@ -331,10 +331,12 @@ def test_customers_doesnt_return_duplicates(customer_user, channel_USD):Order(user=customer_user,channel=channel_USD,+ lines_count=0,),Order(user=customer_user,channel=channel_USD,+ lines_count=0,),])@@ -346,6 +348,7 @@ def test_customers_show_staff_with_order(admin_user, channel_USD):Order.objects.create(user=admin_user,channel=channel_USD,+ lines_count=0,)assert User.objects.customers().count() == 1diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex b30f798124..2d1ae84f10 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -720,6 +720,7 @@ def _prepare_order_data("undiscounted_total": undiscounted_total,"shipping_tax_rate": shipping_tax_rate,"tax_error": checkout.tax_error,+ "lines_count": len(order_data["lines"]),})@@ -1474,6 +1475,7 @@ def _create_order_from_checkout(should_refresh_prices=False,tax_exemption=checkout_info.checkout.tax_exemption,tax_error=checkout_info.checkout.tax_error,+ lines_count=len(checkout_lines_info),**_process_shipping_data_for_order(checkout_info,undiscounted_base_shipping_price,diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 83f2a3b3b8..791ca208f0 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -806,6 +806,7 @@ def create_fake_order(max_order_lines=5, create_preorder_lines=False):"shipping_price": shipping_price,"base_shipping_price": shipping_method_channel_listing.price,"undiscounted_base_shipping_price": shipping_method_channel_listing.price,+ "lines_count": 0,})if will_be_unconfirmed:@@ -825,6 +826,7 @@ def create_fake_order(max_order_lines=5, create_preorder_lines=False):order.search_vector = FlatConcatSearchVector(*prepare_order_search_vector_value(order))+ order.lines_count = order.lines.count()order.save()create_fake_payment(order=order)diff --git a/saleor/graphql/account/tests/fixtures/benchmark.py b/saleor/graphql/account/tests/fixtures/benchmark.pyindex 3f5e3ffa17..5a5f1c746d 100644--- a/saleor/graphql/account/tests/fixtures/benchmark.py+++ b/saleor/graphql/account/tests/fixtures/benchmark.py@@ -37,6 +37,7 @@ def users_for_customers_benchmarks(channel_USD, address, shipping_method):shipping_method=shipping_method,user=users_for_customers_benchmarks[i],total=TaxedMoney(net=Money(i, "USD"), gross=Money(i, "USD")),+ lines_count=0,)for i in range(ORDER_COUNT_IN_BENCHMARKS)]diff --git a/saleor/graphql/account/tests/queries/test_customers.py b/saleor/graphql/account/tests/queries/test_customers.pyindex 245118c272..37b27e1e80 100644--- a/saleor/graphql/account/tests/queries/test_customers.py+++ b/saleor/graphql/account/tests/queries/test_customers.py@@ -80,7 +80,9 @@ def test_query_customers_pagination_with_sort(channel_USD,):Order.objects.create(- user=User.objects.get(email="[email protected]"), channel=channel_USD+ user=User.objects.get(email="[email protected]"),+ channel=channel_USD,+ lines_count=0,)page_size = 2variables = {"first": page_size, "after": None, "sortBy": customer_sort}diff --git a/saleor/graphql/account/tests/queries/test_customers_filtering.py b/saleor/graphql/account/tests/queries/test_customers_filtering.pyindex 8120b362c9..aa0805cb2c 100644--- a/saleor/graphql/account/tests/queries/test_customers_filtering.py+++ b/saleor/graphql/account/tests/queries/test_customers_filtering.py@@ -206,10 +206,10 @@ def test_query_customers_with_filter_placed_orders(customer_user,channel_USD,):- Order.objects.create(user=customer_user, channel=channel_USD)+ Order.objects.create(user=customer_user, channel=channel_USD, lines_count=0)second_customer = User.objects.create(email="[email protected]")with freeze_time("2012-01-14 11:00:00"):- Order.objects.create(user=second_customer, channel=channel_USD)+ Order.objects.create(user=second_customer, channel=channel_USD, lines_count=0)variables = {"filter": customer_filter}response = staff_api_client.post_graphql(query_customer_with_filter, variables, permissions=[permission_manage_users]@@ -282,14 +282,14 @@ def test_query_customers_with_filter_placed_orders_():Order.objects.bulk_create([- Order(user=customer_user, channel=channel_USD),- Order(user=customer_user, channel=channel_USD),- Order(user=customer_user, channel=channel_USD),+ Order(user=customer_user, channel=channel_USD, lines_count=0),+ Order(user=customer_user, channel=channel_USD, lines_count=0),+ Order(user=customer_user, channel=channel_USD, lines_count=0),])second_customer = User.objects.create(email="[email protected]")with freeze_time("2012-01-14 11:00:00"):- Order.objects.create(user=second_customer, channel=channel_USD)+ Order.objects.create(user=second_customer, channel=channel_USD, lines_count=0)variables = {"filter": customer_filter}response = staff_api_client.post_graphql(query_customer_with_filter, variables, permissions=[permission_manage_users]diff --git a/saleor/graphql/account/tests/queries/test_customers_sorting.py b/saleor/graphql/account/tests/queries/test_customers_sorting.pyindex e61a152ca3..b7f11f93f0 100644--- a/saleor/graphql/account/tests/queries/test_customers_sorting.py+++ b/saleor/graphql/account/tests/queries/test_customers_sorting.py@@ -68,7 +68,9 @@ def test_query_customers_with_sort(users[1].save()Order.objects.create(- user=User.objects.get(email="[email protected]"), channel=channel_USD+ user=User.objects.get(email="[email protected]"),+ channel=channel_USD,+ lines_count=0,)variables = {"sort_by": customer_sort}@@ -157,7 +159,9 @@ def test_query_customers_pagination_with_sort(channel_USD,):Order.objects.create(- user=User.objects.get(email="[email protected]"), channel=channel_USD+ user=User.objects.get(email="[email protected]"),+ channel=channel_USD,+ lines_count=0,)page_size = 2variables = {"first": page_size, "after": None, "sortBy": customer_sort}diff --git a/saleor/graphql/account/tests/queries/test_staff_users_sorting.py b/saleor/graphql/account/tests/queries/test_staff_users_sorting.pyindex 56cfc3e53f..c3a8569bcc 100644--- a/saleor/graphql/account/tests/queries/test_staff_users_sorting.py+++ b/saleor/graphql/account/tests/queries/test_staff_users_sorting.py@@ -60,7 +60,9 @@ def test_query_staff_members_with_sort(])Order.objects.create(- user=User.objects.get(email="[email protected]"), channel=channel_USD+ user=User.objects.get(email="[email protected]"),+ channel=channel_USD,+ lines_count=0,)variables = {"sort_by": customer_sort}staff_api_client.user.user_permissions.add(permission_manage_staff)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 d2d63af0c3..2d29963956 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@@ -281,6 +281,8 @@ def test_checkout_complete(assert order_payment == paymentassert payment.transactions.count() == 1+ assert order.lines_count == len(lines)+gift_card.refresh_from_db()assert gift_card.current_balance == zero_money(gift_card.currency)assert gift_card.last_used_ondiff --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 79c45e396e..e2e72433a4 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@@ -266,6 +266,8 @@ def test_checkout_without_any_transaction_allow_to_create_order(assert order.authorize_status == OrderAuthorizeStatus.NONEassert order.subtotal.gross == get_subtotal(order.lines.all(), order.currency).gross+ assert order.lines_count == len(lines)+def test_checkout_with_total_0(checkout_with_item_total_0,@@ -325,6 +327,8 @@ def test_checkout_with_total_0(assert order.base_shipping_price_amount == 0assert order.undiscounted_base_shipping_price_amount == 0+ assert order.lines_count == len(lines)+def test_checkout_with_authorized(user_api_client,@@ -427,6 +431,8 @@ def test_checkout_with_authorized(assert order.base_shipping_price_amount == shipping_price.amountassert order.undiscounted_base_shipping_price_amount == shipping_price.amount+ assert order.lines_count == len(lines)+assert not Checkout.objects.filter()assert not len(Reservation.objects.all())@@ -526,6 +532,8 @@ def test_checkout_with_charged(order.shipping_tax_class_private_metadata == shipping_tax_class.private_metadata)+ assert order.lines_count == len(lines)+assert not Checkout.objects.filter()assert not len(Reservation.objects.all())@@ -629,6 +637,8 @@ def test_checkout_price_override(order.shipping_tax_class_private_metadata == shipping_tax_class.private_metadata)+ assert order.lines_count == len(lines)+assert not Checkout.objects.filter()diff --git a/saleor/graphql/core/tests/test_scalars.py b/saleor/graphql/core/tests/test_scalars.pyindex cd0c7c90b8..d6871523a0 100644--- a/saleor/graphql/core/tests/test_scalars.py+++ b/saleor/graphql/core/tests/test_scalars.py@@ -88,7 +88,7 @@ def test_order_query_with_filter_created_str_as_date_value(}"""- Order.objects.create(channel=channel_USD)+ Order.objects.create(channel=channel_USD, lines_count=0)variables = {"filter": orders_filter}staff_api_client.user.user_permissions.add(permission_manage_orders)diff --git a/saleor/graphql/order/bulk_mutations/order_bulk_create.py b/saleor/graphql/order/bulk_mutations/order_bulk_create.pyindex 68c003ee70..518a4551dc 100644--- a/saleor/graphql/order/bulk_mutations/order_bulk_create.py+++ b/saleor/graphql/order/bulk_mutations/order_bulk_create.py@@ -2169,6 +2169,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):order_data.order.weight = order_input.get("weight") or zero_weight()order_data.order.currency = order_input["currency"]order_data.order.should_refresh_prices = False+ order_data.order.lines_count = len(order_data.lines)if order_data.voucher_code:order_data.order.voucher_code = order_data.voucher_code.codeorder_data.order.voucher = order_data.voucher_code.voucherdiff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.pyindex 2d8468e5b2..85619f439f 100644--- a/saleor/graphql/order/mutations/draft_order_create.py+++ b/saleor/graphql/order/mutations/draft_order_create.py@@ -252,6 +252,7 @@ class DraftOrderCreate(cls.clean_lines(cleaned_input, lines, channel)cleaned_input["status"] = OrderStatus.DRAFTcleaned_input["origin"] = OrderOrigin.DRAFT+ cleaned_input["lines_count"] = len(cleaned_input.get("lines_data", []))cls.clean_addresses(info, instance, cleaned_input, shipping_address, billing_address, manager@@ -368,8 +369,8 @@ class DraftOrderCreate(@staticmethoddef _save_lines(info, instance, lines_data, app, manager):+ lines = []if lines_data:- lines = []for line_data in lines_data:new_line = create_order_line(instance,diff --git a/saleor/graphql/order/mutations/order_line_delete.py b/saleor/graphql/order/mutations/order_line_delete.pyindex 0b0ffc7050..13058b025c 100644--- a/saleor/graphql/order/mutations/order_line_delete.py+++ b/saleor/graphql/order/mutations/order_line_delete.py@@ -95,8 +95,15 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):invalidate_order_prices(order)recalculate_order_weight(order)update_order_search_vector(order, save=False)+ order.lines_count = order.lines.count()updated_fields.extend(- ["should_refresh_prices", "weight", "search_vector", "updated_at"]+ [+ "should_refresh_prices",+ "weight",+ "search_vector",+ "updated_at",+ "lines_count",+ ])order.save(update_fields=updated_fields)call_event_by_order_status(order, manager)diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.pyindex c2a3d1e59f..c0c236672f 100644--- a/saleor/graphql/order/mutations/order_lines_create.py+++ b/saleor/graphql/order/mutations/order_lines_create.py@@ -213,12 +213,14 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):invalidate_order_prices(order)recalculate_order_weight(order)update_order_search_vector(order, save=False)+ order.lines_count = order.lines.count()order.save(update_fields=["should_refresh_prices","weight","search_vector","updated_at",+ "lines_count",])call_event_by_order_status(order, manager)diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.pyindex 5afc5c53c2..e302c9433b 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py@@ -276,6 +276,7 @@ def test_draft_order_create_with_voucher_entire_order().get_total()assert order.base_shipping_price == shipping_totalassert order.undiscounted_base_shipping_price == shipping_total+ assert order.lines_count == len(variant_list)# Ensure the correct event was createdcreated_draft_event = OrderEvent.objects.get(@@ -570,6 +571,7 @@ def test_draft_order_create_with_voucher_code(assert order.external_reference == external_referenceassert order.base_shipping_price == shipping_totalassert order.undiscounted_base_shipping_price == shipping_total+ assert order.lines_count == len(variant_list)# Ensure the correct event was createdcreated_draft_event = OrderEvent.objects.get(@@ -821,6 +823,7 @@ def test_draft_order_create_with_voucher_specific_product().get_total()assert order.base_shipping_price == shipping_totalassert order.undiscounted_base_shipping_price == shipping_total+ assert order.lines_count == len(variant_list)lines_data = data["lines"]discounted_line_data, line_1_data = lines_data@@ -975,6 +978,7 @@ def test_draft_order_create_with_voucher_apply_once_per_order().get_total()assert order.base_shipping_price == shipping_totalassert order.undiscounted_base_shipping_price == shipping_total+ assert order.lines_count == len(variant_list)lines_data = data["lines"]discounted_line_data, line_1_data = lines_data@@ -1569,6 +1573,7 @@ def test_draft_order_create_with_same_variant_and_force_new_line().get_total()assert order.base_shipping_price == shipping_totalassert order.undiscounted_base_shipping_price == shipping_total+ assert order.lines_count == len(variant_list)# Ensure the correct event was createdcreated_draft_event = OrderEvent.objects.get(diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.pyindex a74c6caa98..87f06cd9bf 100644--- a/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py@@ -381,7 +381,7 @@ def test_fulfillment_return_products_order_lines(assert replace_order["origin"] == OrderOrigin.REISSUE.upper()assert replace_order["original"] == order_idreplace_order = Order.objects.get(status=OrderStatus.DRAFT)- assert replace_order.lines.count() == 1+ assert replace_order.lines_count == replace_order.lines.count() == 1replaced_line = replace_order.lines.get()assert replaced_line.variant_id == line_to_replace.variant_idassert (@@ -679,7 +679,7 @@ def test_fulfillment_return_products_fulfillment_lines(assert replace_order["original"] == order_idreplace_order = Order.objects.get(status=OrderStatus.DRAFT)- assert replace_order.lines.count() == 1+ assert replace_order.lines_count == replace_order.lines.count() == 1replaced_line = replace_order.lines.get()assert replaced_line.variant_id == fulfillment_line_to_replace.order_line.variant_idassert (@@ -1030,7 +1030,7 @@ def test_fulfillment_return_products_fulfillment_lines_and_order_lines(assert replace_order["original"] == order_idreplace_order = Order.objects.get(status=OrderStatus.DRAFT)- assert replace_order.lines.count() == 1+ assert replace_order.lines_count == replace_order.lines.count() == 1replaced_line = replace_order.lines.get()assert replaced_line.variant_id == fulfillment_line_to_replace.order_line.variant_idassert (diff --git a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py b/saleor/graphql/order/tests/mutations/test_order_bulk_create.pyindex 5f972dbcfc..4a6589b66a 100644--- a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py+++ b/saleor/graphql/order/tests/mutations/test_order_bulk_create.py@@ -575,6 +575,9 @@ def test_order_bulk_create_unit_discount(assert db_order_line.unit_discount_value == discount_valueassert db_order_line.unit_discount_reason == discount_reasonassert db_order.lines.first() == db_order_line+ assert (+ db_order.lines_count == len(order_bulk_input["lines"]) == db_order.lines.count()+ )def test_order_bulk_create_unit_discount_mismatched_discount(@@ -768,6 +771,9 @@ def test_order_bulk_create(assert db_order.authorize_status == OrderAuthorizeStatus.PARTIAL.lower()assert db_order.shipping_address.validation_skipped is Falseassert db_order.billing_address.validation_skipped is False+ assert (+ db_order.lines_count == len(order_bulk_input["lines"]) == db_order.lines.count()+ )order_line = order["lines"][0]assert order_line["variant"]["id"] == graphene.Node.to_global_id(@@ -1099,6 +1105,9 @@ def test_order_bulk_create_multiple_lines(db_order = Order.objects.get()assert db_order.total_gross_amount == expected_order_total_grossassert db_order.total_net_amount == expected_order_total_net+ assert (+ db_order.lines_count == len(order_bulk_input["lines"]) == db_order.lines.count()+ )assert OrderLine.objects.count() == lines_count + 2@@ -1173,6 +1182,9 @@ def test_order_bulk_create_line_without_variant(db_order = Order.objects.get()assert db_order.total_gross_amount == expected_order_total_grossassert db_order.total_net_amount == expected_order_total_net+ assert (+ db_order.lines_count == len(order_bulk_input["lines"]) == db_order.lines.count()+ )error0 = content["data"]["orderBulkCreate"]["results"][0]["errors"][0]assert error0["message"] == (diff --git a/saleor/graphql/order/tests/mutations/test_order_line_delete.py b/saleor/graphql/order/tests/mutations/test_order_line_delete.pyindex 55a2589a80..b02f0d7d63 100644--- a/saleor/graphql/order/tests/mutations/test_order_line_delete.py+++ b/saleor/graphql/order/tests/mutations/test_order_line_delete.py@@ -106,6 +106,7 @@ def test_order_line_remove(permission_group_manage_orders,staff_api_client,):+ # givenquery = ORDER_LINE_DELETE_MUTATIONpermission_group_manage_orders.user_set.add(staff_api_client.user)order = order_with_lines@@ -115,7 +116,10 @@ def test_order_line_remove(line_id = graphene.Node.to_global_id("OrderLine", line.id)variables = {"id": line_id}+ # whenresponse = staff_api_client.post_graphql(query, variables)++ # thencontent = get_graphql_content(response)data = content["data"]["orderLineDelete"]assert OrderEvent.objects.count() == 1@@ -126,6 +130,9 @@ def test_order_line_remove(order, status, draft_order_updated_webhook_mock, order_updated_webhook_mock)+ order.refresh_from_db()+ assert order.lines_count == order.lines.count()+@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")@patch("saleor.plugins.manager.PluginsManager.order_updated")@@ -227,6 +234,8 @@ def test_order_line_remove_by_app(draft_order_updated_webhook_mock,order_updated_webhook_mock,)+ order.refresh_from_db()+ assert order.lines_count == order.lines.count()@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")diff --git a/saleor/graphql/order/tests/mutations/test_order_lines_create.py b/saleor/graphql/order/tests/mutations/test_order_lines_create.pyindex c2c47bb1d5..2a396ad303 100644--- a/saleor/graphql/order/tests/mutations/test_order_lines_create.py+++ b/saleor/graphql/order/tests/mutations/test_order_lines_create.py@@ -194,6 +194,7 @@ def test_order_lines_create(order = order_with_linesorder.status = statusorder.save(update_fields=["status"])+ lines_count = order.lines.count()variant = variant_with_many_stocksquantity = 1order_id = graphene.Node.to_global_id("Order", order.id)@@ -227,6 +228,8 @@ def test_order_lines_create(assert data["orderLines"][0]["productSku"] == variant.skuassert data["orderLines"][0]["productVariantId"] == variant.get_global_id()assert data["orderLines"][0]["quantity"] == quantity+ order.refresh_from_db()+ assert order.lines_count == lines_count + 1# mutation should fail when quantity is lower than 1variables = {"orderId": order_id, "variantId": variant_id, "quantity": 0}@@ -284,6 +287,7 @@ def test_order_lines_create_by_app(order = order_with_linesorder.status = OrderStatus.UNCONFIRMEDorder.save(update_fields=["status"])+ lines_count = order.lines.count()variant = variant_with_many_stocksquantity = 1order_id = graphene.Node.to_global_id("Order", order.id)@@ -296,7 +300,6 @@ def test_order_lines_create_by_app()# then-content = get_graphql_content(response)data = content["data"]["orderLinesCreate"]assert data["orderLines"][0]["productSku"] == variant.sku@@ -317,6 +320,8 @@ def test_order_lines_create_by_app(draft_order_updated_webhook_mock,order_updated_webhook_mock,)+ order.refresh_from_db()+ assert order.lines_count == lines_count + 1@pytest.mark.parametrize("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])@@ -489,7 +494,7 @@ def test_order_lines_create_with_same_variant_and_force_new_line(order.status = statusorder.save(update_fields=["status"])lines = order.lines.all()- assert len(lines) == 2+ lines_count = len(lines)line = lines[0]variant = line.variant@@ -514,7 +519,10 @@ def test_order_lines_create_with_same_variant_and_force_new_line(permission_group_manage_orders.user_set.add(staff_api_client.user)response = staff_api_client.post_graphql(query, variables)- assert order.lines.count() == 3++ order.refresh_from_db()+ assert order.lines.count() == lines_count + 1+ assert order.lines_count == lines_count + 1assert OrderEvent.objects.count() == 1assert OrderEvent.objects.last().type == order_events.OrderEvents.ADDED_PRODUCTScontent = get_graphql_content(response)@@ -549,7 +557,7 @@ def test_order_lines_create_when_variant_already_in_multiple_lines(line.id = Noneline.save()- assert order.lines.count() == 3+ lines_count = order.lines.count()quantity = 1order_id = graphene.Node.to_global_id("Order", order.id)@@ -566,7 +574,9 @@ def test_order_lines_create_when_variant_already_in_multiple_lines(response = staff_api_client.post_graphql(ORDER_LINES_CREATE_MUTATION, variables)- assert order.lines.count() == 4+ order.refresh_from_db()+ assert order.lines.count() == lines_count + 1+ assert order.lines_count == lines_count + 1assert OrderEvent.objects.count() == 1assert OrderEvent.objects.last().type == order_events.OrderEvents.ADDED_PRODUCTScontent = get_graphql_content(response)@@ -1101,7 +1111,10 @@ def test_order_lines_create_with_custom_price_force_new_line(event = OrderEvent.objects.last()assert event.type == order_events.OrderEvents.ADDED_PRODUCTSassert len(event.parameters["lines"]) == 1++ order.refresh_from_db()assert order.lines.count() == lines_count + 1+ assert order.lines_count == lines_count + 1line = OrderLine.objects.last()assert line.undiscounted_base_unit_price_amount == custom_price@@ -1163,7 +1176,9 @@ def test_order_lines_create_with_custom_price_and_catalogue_discount(new_qty = quantity + old_qty+ order.refresh_from_db()assert order.lines.count() == lines_count+ assert order.lines_count == lines_countorder_line.refresh_from_db()data = content["data"]["orderLinesCreate"]line_data = data["orderLines"][0]@@ -1220,7 +1235,9 @@ def test_order_lines_create_with_custom_price_force_new_line_and_catalogue_disco# thencontent = get_graphql_content(response)+ order.refresh_from_db()assert order.lines.count() == lines_count + 1+ assert order.lines_count == lines_count + 1data = content["data"]["orderLinesCreate"]discounted_line_data = data["orderLines"][0]@@ -1414,7 +1431,9 @@ def test_order_lines_create_with_catalogue_discount_existing_variant(content = get_graphql_content(response)new_qty = quantity + old_qty+ order.refresh_from_db()assert order.lines.count() == lines_count+ assert order.lines_count == lines_countline.refresh_from_db()data = content["data"]["orderLinesCreate"]line_data = data["orderLines"][0]diff --git a/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py b/saleor/graphql/order/tests/queries/test_draft_order_with_filter.pyindex e57e6647f0..0772aca38d 100644--- a/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py+++ b/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py@@ -94,11 +94,12 @@ def test_draft_order_query_with_filter_customer_fields(status=OrderStatus.DRAFT,user=customer_user,channel=channel_USD,+ lines_count=0,)Order.objects.bulk_create([order,- Order(status=OrderStatus.DRAFT, channel=channel_USD),+ Order(status=OrderStatus.DRAFT, channel=channel_USD, lines_count=0),])@@ -177,9 +178,11 @@ def test_draft_order_query_with_filter_created(channel_USD,):# given- Order.objects.create(status=OrderStatus.DRAFT, channel=channel_USD)+ Order.objects.create(status=OrderStatus.DRAFT, channel=channel_USD, lines_count=0)with freeze_time("2012-01-14"):- Order.objects.create(status=OrderStatus.DRAFT, channel=channel_USD)+ Order.objects.create(+ status=OrderStatus.DRAFT, channel=channel_USD, lines_count=0+ )variables = {"filter": orders_filter}permission_group_manage_orders.user_set.add(staff_api_client.user)@@ -221,16 +224,19 @@ def test_draft_orders_query_with_filter_search(user_email="[email protected]",status=OrderStatus.DRAFT,channel=channel_USD,+ lines_count=0,),Order(user_email="[email protected]",status=OrderStatus.DRAFT,channel=channel_USD,+ lines_count=0,),Order(user_email="[email protected]",status=OrderStatus.DRAFT,channel=channel_USD,+ lines_count=0,),])diff --git a/saleor/graphql/order/tests/queries/test_draft_order_with_sort.py b/saleor/graphql/order/tests/queries/test_draft_order_with_sort.pyindex 00ddb62718..050ba819ef 100644--- a/saleor/graphql/order/tests/queries/test_draft_order_with_sort.py+++ b/saleor/graphql/order/tests/queries/test_draft_order_with_sort.py@@ -46,6 +46,7 @@ def test_query_draft_orders_with_sort(status=OrderStatus.DRAFT,total=TaxedMoney(net=Money(10, "USD"), gross=Money(13, "USD")),channel=channel_USD,+ lines_count=0,))with freeze_time("2012-01-14"):@@ -58,6 +59,7 @@ def test_query_draft_orders_with_sort(status=OrderStatus.DRAFT,total=TaxedMoney(net=Money(100, "USD"), gross=Money(130, "USD")),channel=channel_USD,+ lines_count=0,))address3 = address.get_copy()@@ -69,6 +71,7 @@ def test_query_draft_orders_with_sort(status=OrderStatus.DRAFT,total=TaxedMoney(net=Money(20, "USD"), gross=Money(26, "USD")),channel=channel_USD,+ lines_count=0,))variables = {"sort_by": draft_order_sort}diff --git a/saleor/graphql/order/tests/queries/test_order_by_token.py b/saleor/graphql/order/tests/queries/test_order_by_token.pyindex 3eda4829af..a98dde02e9 100644--- a/saleor/graphql/order/tests/queries/test_order_by_token.py+++ b/saleor/graphql/order/tests/queries/test_order_by_token.py@@ -482,8 +482,7 @@ def test_query_order_without_addresses(order, user_api_client, channel_USD):query = ORDER_BY_TOKEN_QUERYorder = Order.objects.create(- channel=channel_USD,- user=user_api_client.user,+ channel=channel_USD, user=user_api_client.user, lines_count=0)# when@@ -507,6 +506,7 @@ def test_order_query_address_without_order_user(channel=channel_USD,shipping_address=shipping_address,billing_address=billing_address,+ lines_count=0,)staff_api_client.user.user_permissions.add(permission_manage_orders)response = staff_api_client.post_graphql(query, {"token": order.id})diff --git a/saleor/graphql/order/tests/queries/test_order_with_filter.py b/saleor/graphql/order/tests/queries/test_order_with_filter.pyindex 2b9ee364c4..29eff81d23 100644--- a/saleor/graphql/order/tests/queries/test_order_with_filter.py+++ b/saleor/graphql/order/tests/queries/test_order_with_filter.py@@ -84,7 +84,7 @@ def test_order_query_with_filter_channels_with_many_channel(other_channel_USD,):# given- Order.objects.create(channel=other_channel_USD)+ Order.objects.create(channel=other_channel_USD, lines_count=0)channel_usd_id = graphene.Node.to_global_id("Channel", channel_USD.pk)channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)variables = {"filter": {"channels": [channel_pln_id, channel_usd_id]}}@@ -280,9 +280,9 @@ def test_order_query_with_filter_created(channel_USD,):# given- Order.objects.create(channel=channel_USD)+ Order.objects.create(channel=channel_USD, lines_count=0)with freeze_time("2012-01-14"):- Order.objects.create(channel=channel_USD)+ Order.objects.create(channel=channel_USD, lines_count=0)variables = {"filter": orders_filter}permission_group_manage_orders.user_set.add(staff_api_client.user)@@ -324,10 +324,10 @@ def test_order_query_with_filter_updated_at():# givenwith freeze_time("2012-01-14 11:00:00"):- Order.objects.create(channel=channel_USD)+ Order.objects.create(channel=channel_USD, lines_count=0)with freeze_time("2012-01-14 12:00:00"):- Order.objects.create(channel=channel_USD)+ Order.objects.create(channel=channel_USD, lines_count=0)variables = {"filter": orders_filter}permission_group_manage_orders.user_set.add(staff_api_client.user)@@ -366,7 +366,7 @@ def test_order_query_with_filter_payment_status(payment_dummy.save()payment_dummy.id = None- payment_dummy.order = Order.objects.create(channel=channel_PLN)+ payment_dummy.order = Order.objects.create(channel=channel_PLN, lines_count=0)payment_dummy.charge_status = ChargeStatus.NOT_CHARGEDpayment_dummy.save()@@ -388,7 +388,7 @@ def test_order_query_with_filter_payment_fully_refunded_not_active(# givenpayment_dummy.charge_status = ChargeStatus.FULLY_REFUNDEDpayment_dummy.is_active = False- payment_dummy.order = Order.objects.create(channel=channel_PLN)+ payment_dummy.order = Order.objects.create(channel=channel_PLN, lines_count=0)payment_dummy.save()variables = {"filter": {"paymentStatus": "FULLY_REFUNDED"}}permission_group_manage_orders.user_set.add(staff_api_client.user)@@ -457,8 +457,20 @@ def test_order_query_with_filter_customer_fields(customer_user.save()customer_user.refresh_from_db()- order = Order(user=customer_user, channel=channel_USD)- Order.objects.bulk_create([order, Order(channel=channel_USD)])+ order = Order(+ user=customer_user,+ channel=channel_USD,+ lines_count=0,+ )+ Order.objects.bulk_create(+ [+ order,+ Order(+ channel=channel_USD,+ lines_count=0,+ ),+ ]+ )variables = {"filter": orders_filter}permission_group_manage_orders.user_set.add(staff_api_client.user)@@ -605,14 +617,17 @@ def test_orders_query_with_filter_search(user=customer_user,user_email="[email protected]",channel=channel_USD,+ lines_count=0,),Order(user_email="[email protected]",channel=channel_USD,+ lines_count=0,),Order(user_email="[email protected]",channel=channel_USD,+ lines_count=0,),])@@ -688,10 +703,12 @@ def test_orders_query_with_filter_search_by_global_payment_id(user=customer_user,channel=channel_USD,user_email="[email protected]",+ lines_count=0,),Order(channel=channel_USD,user_email="[email protected]",+ lines_count=0,),])@@ -807,11 +824,13 @@ def test_orders_query_with_filter_by_orders_id(user_email="[email protected]",status=OrderStatus.UNFULFILLED,channel=channel_USD,+ lines_count=0,),Order(user_email="[email protected]",status=OrderStatus.FULFILLED,channel=channel_USD,+ lines_count=0,),])@@ -844,12 +863,14 @@ def test_orders_query_with_filter_by_old_orders_id(status=OrderStatus.UNFULFILLED,channel=channel_USD,use_old_id=True,+ lines_count=0,),Order(user_email="[email protected]",status=OrderStatus.FULFILLED,channel=channel_USD,use_old_id=False,+ lines_count=0,),])@@ -882,11 +903,13 @@ def test_orders_query_with_filter_by_old_and_new_orders_id(status=OrderStatus.UNFULFILLED,channel=channel_USD,use_old_id=True,+ lines_count=0,),Order(user_email="[email protected]",status=OrderStatus.FULFILLED,channel=channel_USD,+ lines_count=0,),])@@ -1051,6 +1074,7 @@ def test_orders_query_with_filter_authorize_status(user_email=customer_user.email,user=customer_user,origin=OrderOrigin.CHECKOUT,+ lines_count=0,)order.payment_transactions.create(currency=order.currency, authorized_value=Decimal("10")@@ -1131,6 +1155,7 @@ def test_orders_query_with_filter_charge_status(user_email=customer_user.email,user=customer_user,origin=OrderOrigin.CHECKOUT,+ lines_count=0,)order.payment_transactions.create(currency=order.currency, charged_value=Decimal("10")diff --git a/saleor/graphql/order/tests/queries/test_order_with_sort.py b/saleor/graphql/order/tests/queries/test_order_with_sort.pyindex 346d14e4b3..30ea1ce98b 100644--- a/saleor/graphql/order/tests/queries/test_order_with_sort.py+++ b/saleor/graphql/order/tests/queries/test_order_with_sort.py@@ -52,6 +52,7 @@ def test_query_orders_with_sort(status=OrderStatus.PARTIALLY_FULFILLED,total=TaxedMoney(net=Money(10, "USD"), gross=Money(13, "USD")),channel=channel_USD,+ lines_count=0,))with freeze_time("2012-01-14"):@@ -64,6 +65,7 @@ def test_query_orders_with_sort(status=OrderStatus.FULFILLED,total=TaxedMoney(net=Money(100, "USD"), gross=Money(130, "USD")),channel=channel_USD,+ lines_count=0,))address3 = address.get_copy()@@ -75,6 +77,7 @@ def test_query_orders_with_sort(status=OrderStatus.CANCELED,total=TaxedMoney(net=Money(20, "USD"), gross=Money(26, "USD")),channel=channel_USD,+ lines_count=0,))created_orders.append(@@ -83,6 +86,7 @@ def test_query_orders_with_sort(status=OrderStatus.UNCONFIRMED,total=TaxedMoney(net=Money(60, "USD"), gross=Money(80, "USD")),channel=channel_USD,+ lines_count=0,))variables = {"sort_by": order_sort}diff --git a/saleor/graphql/order/tests/queries/test_orders.py b/saleor/graphql/order/tests/queries/test_orders.pyindex 6fa5ffdfad..4173664b6b 100644--- a/saleor/graphql/order/tests/queries/test_orders.py+++ b/saleor/graphql/order/tests/queries/test_orders.py@@ -307,14 +307,17 @@ def test_orders_query_with_search(user=customer_user,user_email="[email protected]",channel=channel_USD,+ lines_count=0,),Order(user_email="[email protected]",channel=channel_USD,+ lines_count=0,),Order(user_email="[email protected]",channel=channel_USD,+ lines_count=0,),])diff --git a/saleor/graphql/order/tests/queries/test_pagination.py b/saleor/graphql/order/tests/queries/test_pagination.pyindex 269e4423cd..32b4669ce4 100644--- a/saleor/graphql/order/tests/queries/test_pagination.py+++ b/saleor/graphql/order/tests/queries/test_pagination.py@@ -24,14 +24,17 @@ def orders_for_pagination(db, channel_USD):Order(total=TaxedMoney(net=Money(1, "USD"), gross=Money(1, "USD")),channel=channel_USD,+ lines_count=0,),Order(total=TaxedMoney(net=Money(2, "USD"), gross=Money(2, "USD")),channel=channel_USD,+ lines_count=0,),Order(total=TaxedMoney(net=Money(3, "USD"), gross=Money(3, "USD")),channel=channel_USD,+ lines_count=0,),])@@ -54,18 +57,21 @@ def draft_orders_for_pagination(db, channel_USD):status=OrderStatus.DRAFT,channel=channel_USD,should_refresh_prices=False,+ lines_count=0,),Order(total=TaxedMoney(net=Money(2, "USD"), gross=Money(2, "USD")),status=OrderStatus.DRAFT,channel=channel_USD,should_refresh_prices=False,+ lines_count=0,),Order(total=TaxedMoney(net=Money(3, "USD"), gross=Money(3, "USD")),status=OrderStatus.DRAFT,channel=channel_USD,should_refresh_prices=False,+ lines_count=0,),])@@ -205,7 +211,7 @@ def test_order_query_pagination_with_filter_created(channel_USD,):with freeze_time("2012-01-14"):- Order.objects.create(channel=channel_USD)+ Order.objects.create(channel=channel_USD, lines_count=0)page_size = 2variables = {"first": page_size, "after": None, "filter": orders_filter}permission_group_manage_orders.user_set.add(staff_api_client.user)@@ -335,7 +341,7 @@ def test_order_query_pagination_with_filter_customer_fields(customer_user.save()customer_user.refresh_from_db()- order = Order.objects.create(user=customer_user, channel=channel_USD)+ order = Order.objects.create(user=customer_user, channel=channel_USD, lines_count=0)page_size = 2variables = {"first": page_size, "after": None, "filter": orders_filter}@@ -373,9 +379,7 @@ def test_draft_order_query_pagination_with_filter_customer_fields(customer_user.refresh_from_db()order = Order.objects.create(- status=OrderStatus.DRAFT,- user=customer_user,- channel=channel_USD,+ status=OrderStatus.DRAFT, user=customer_user, channel=channel_USD, lines_count=0)page_size = 2@@ -466,6 +470,7 @@ def test_draft_order_query_pagination_with_filter_created(status=OrderStatus.DRAFT,channel=channel_USD,should_refresh_prices=False,+ lines_count=0,)page_size = 2variables = {"first": page_size, "after": None, "filter": orders_filter}@@ -511,14 +516,17 @@ def test_orders_query_pagination_with_filter_search(user=customer_user,user_email="[email protected]",channel=channel_USD,+ lines_count=0,),Order(user_email="[email protected]",channel=channel_USD,+ lines_count=0,),Order(user_email="[email protected]",channel=channel_USD,+ lines_count=0,),])@@ -595,18 +603,21 @@ def test_draft_orders_query_pagination_with_filter_search(status=OrderStatus.DRAFT,channel=channel_USD,should_refresh_prices=False,+ lines_count=0,),Order(user_email="[email protected]",status=OrderStatus.DRAFT,channel=channel_USD,should_refresh_prices=False,+ lines_count=0,),Order(user_email="[email protected]",status=OrderStatus.DRAFT,channel=channel_USD,should_refresh_prices=False,+ lines_count=0,),])@@ -716,6 +727,7 @@ def test_query_orders_pagination_with_sort(status=OrderStatus.PARTIALLY_FULFILLED,total=TaxedMoney(net=Money(10, "USD"), gross=Money(13, "USD")),channel=channel_USD,+ lines_count=0,))with freeze_time("2012-01-14"):@@ -728,6 +740,7 @@ def test_query_orders_pagination_with_sort(status=OrderStatus.FULFILLED,total=TaxedMoney(net=Money(100, "USD"), gross=Money(130, "USD")),channel=channel_USD,+ lines_count=0,))address3 = address.get_copy()@@ -739,6 +752,7 @@ def test_query_orders_pagination_with_sort(status=OrderStatus.CANCELED,total=TaxedMoney(net=Money(20, "USD"), gross=Money(26, "USD")),channel=channel_USD,+ lines_count=0,))@@ -788,18 +802,21 @@ def test_orders_with_filter_search_returns_correct_cursor(status=OrderStatus.DRAFT,channel=channel_USD,should_refresh_prices=False,+ lines_count=0,),Order(user_email=search_query,status=OrderStatus.DRAFT,channel=channel_USD,should_refresh_prices=False,+ lines_count=0,),Order(user_email=search_query,status=OrderStatus.DRAFT,channel=channel_USD,should_refresh_prices=False,+ lines_count=0,),])diff --git a/saleor/graphql/order/tests/test_filters.py b/saleor/graphql/order/tests/test_filters.pyindex 936b322c91..4496fba74f 100644--- a/saleor/graphql/order/tests/test_filters.py+++ b/saleor/graphql/order/tests/test_filters.py@@ -23,6 +23,7 @@ def similar_customers_with_orders(order, customer_user, customer_user2, channel_channel=channel_USD,user_email=customer_user2.email,user=customer_user2,+ lines_count=0,)return order, order2, customer_user, customer_user2diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 926afac755..a97796394c 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -1598,7 +1598,9 @@ def create_refund_fulfillment(return refunded_fulfillment-def _populate_replace_order_fields(original_order: "Order"):+def _populate_replace_order_fields(+ original_order: "Order", replace_lines_count: int = 0+) -> "Order":replace_order = Order()replace_order.status = OrderStatus.DRAFTreplace_order.user_id = original_order.user_id@@ -1612,6 +1614,7 @@ def _populate_replace_order_fields(original_order: "Order"):replace_order.origin = OrderOrigin.REISSUEreplace_order.metadata = original_order.metadatareplace_order.private_metadata = original_order.private_metadata+ replace_order.lines_count = replace_lines_countif original_order.billing_address:original_order.billing_address.pk = None@@ -1635,7 +1638,14 @@ def create_replace_order() -> "Order":"""Create draft order with lines to replace."""- replace_order = _populate_replace_order_fields(original_order)+ order_lines_with_fulfillment = OrderLine.objects.in_bulk(+ [line_data.line.order_line_id for line_data in fulfillment_lines_to_replace]+ )+ replace_lines_count = len(+ {line.line.id for line in order_lines_to_replace}+ | set(order_lines_with_fulfillment.keys())+ )+ replace_order = _populate_replace_order_fields(original_order, replace_lines_count)order_line_to_create: dict[OrderLineIDType, OrderLine] = {}# transaction is needed to ensure data consistency for order lineswith traced_atomic_transaction():@@ -1653,9 +1663,6 @@ def create_replace_order(# itemsorder_line_to_create[order_line_id] = order_line- order_lines_with_fulfillment = OrderLine.objects.in_bulk(- [line_data.line.order_line_id for line_data in fulfillment_lines_to_replace]- )for fulfillment_line_data in fulfillment_lines_to_replace:fulfillment_line = fulfillment_line_data.lineorder_line_id = fulfillment_line.order_line_iddiff --git a/saleor/order/migrations/0203_order_lines_count.py b/saleor/order/migrations/0203_order_lines_count.pynew file mode 100644index 0000000000..dc082b491e--- /dev/null+++ b/saleor/order/migrations/0203_order_lines_count.py@@ -0,0 +1,17 @@+# Generated by Django 4.2.20 on 2025-06-03 08:50++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0202_alter_order_undiscounted_base_shipping_price_amount"),+ ]++ operations = [+ migrations.AddField(+ model_name="order",+ name="lines_count",+ field=models.PositiveIntegerField(blank=True, null=True),+ ),+ ]diff --git a/saleor/order/migrations/0204_merge_0203_merge_20250527_1210_0203_order_lines_count.py b/saleor/order/migrations/0204_merge_0203_merge_20250527_1210_0203_order_lines_count.pynew file mode 100644index 0000000000..947cbbb16f--- /dev/null+++ b/saleor/order/migrations/0204_merge_0203_merge_20250527_1210_0203_order_lines_count.py@@ -0,0 +1,12 @@+# Generated by Django 5.2.1 on 2025-06-03 10:51++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0203_merge_20250527_1210"),+ ("order", "0203_order_lines_count"),+ ]++ operations = []diff --git a/saleor/order/migrations/0204_set_order_lines_count.py b/saleor/order/migrations/0204_set_order_lines_count.pynew file mode 100644index 0000000000..5b87740828--- /dev/null+++ b/saleor/order/migrations/0204_set_order_lines_count.py@@ -0,0 +1,44 @@+# Generated by Django 4.2.20 on 2025-06-03 08:52++from django.db import migrations, transaction++# The batch of size 250 takes ~0.3+BATCH_SIZE = 250+++def set_lines_count(apps, _schema_editor):+ Order = apps.get_model("order", "Order")+ qs = Order.objects.filter(lines_count__isnull=True).order_by("pk")+ for ids in queryset_in_batches(qs):+ orders = Order.objects.filter(id__in=ids).order_by("pk")+ with transaction.atomic():+ to_save = []+ _orders_lock = list(orders.select_for_update(of=(["self"])))+ for order in orders:+ order.lines_count = order.lines.count()+ to_save.append(order)+ Order.objects.bulk_update(to_save, ["lines_count"])+++def queryset_in_batches(queryset):+ start_pk = 0+ while True:+ qs = queryset.filter(pk__gt=start_pk)[:BATCH_SIZE]+ pks = list(qs.values_list("pk", flat=True))+ if not pks:+ break+ yield pks+ start_pk = pks[-1]+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0203_order_lines_count"),+ ]++ operations = [+ migrations.RunPython(+ set_lines_count,+ reverse_code=migrations.RunPython.noop,+ )+ ]diff --git a/saleor/order/migrations/0205_merge_20250603_1125.py b/saleor/order/migrations/0205_merge_20250603_1125.pynew file mode 100644index 0000000000..d54b287d89--- /dev/null+++ b/saleor/order/migrations/0205_merge_20250603_1125.py@@ -0,0 +1,12 @@+# Generated by Django 5.2.1 on 2025-06-03 11:25++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0204_merge_0203_merge_20250527_1210_0203_order_lines_count"),+ ("order", "0204_set_order_lines_count"),+ ]++ operations = []diff --git a/saleor/order/migrations/0206_alter_order_lines_count.py b/saleor/order/migrations/0206_alter_order_lines_count.pynew file mode 100644index 0000000000..3a46a88895--- /dev/null+++ b/saleor/order/migrations/0206_alter_order_lines_count.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.1 on 2025-06-03 11:26++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0205_merge_20250603_1125"),+ ]++ operations = [+ migrations.AlterField(+ model_name="order",+ name="lines_count",+ field=models.PositiveIntegerField(),+ ),+ ]diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 55b5ebf010..0c46c23ea0 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -259,6 +259,8 @@ class Order(ModelWithMetadata, ModelWithExternalReference):# Token of a checkout instance that this order was created fromcheckout_token = models.CharField(max_length=36, blank=True)+ lines_count = models.PositiveIntegerField()+total_net_amount = models.DecimalField(max_digits=settings.DEFAULT_MAX_DIGITS,decimal_places=settings.DEFAULT_DECIMAL_PLACES,diff --git a/saleor/order/tests/fixtures/benchmark.py b/saleor/order/tests/fixtures/benchmark.pyindex 9e1772b874..011a222e4e 100644--- a/saleor/order/tests/fixtures/benchmark.py+++ b/saleor/order/tests/fixtures/benchmark.py@@ -116,6 +116,7 @@ def orders_for_benchmarks(shipping_method=shipping_method,user=users_for_order_benchmarks[i],total=TaxedMoney(net=Money(i, "USD"), gross=Money(i, "USD")),+ lines_count=0,)for i in range(ORDER_COUNT_IN_BENCHMARKS)]@@ -133,6 +134,7 @@ def orders_for_benchmarks(new_transactions = _prepare_payment_transactions(new_payments)new_events = _prepare_events_for_order(order)new_lines = _prepare_lines_for_order(order, variant_with_image)+ order.lines_count = len(new_lines)payments.extend(new_payments)transactions.extend(new_transactions)events.extend(new_events)@@ -155,6 +157,7 @@ def orders_for_benchmarks(Fulfillment.objects.bulk_create(fulfillments)OrderLine.objects.bulk_create(lines)FulfillmentLine.objects.bulk_create(fulfillment_lines)+ Order.objects.bulk_update(created_orders, ["lines_count"])return created_ordersdiff --git a/saleor/order/tests/fixtures/order.py b/saleor/order/tests/fixtures/order.pyindex ded2a944c7..df706df363 100644--- a/saleor/order/tests/fixtures/order.py+++ b/saleor/order/tests/fixtures/order.py@@ -110,31 +110,37 @@ def orders(customer_user, channel_USD, channel_PLN):user=customer_user,status=OrderStatus.CANCELED,channel=channel_USD,+ lines_count=0,),Order(user=customer_user,status=OrderStatus.UNFULFILLED,channel=channel_USD,+ lines_count=0,),Order(user=customer_user,status=OrderStatus.PARTIALLY_FULFILLED,channel=channel_USD,+ lines_count=0,),Order(user=customer_user,status=OrderStatus.FULFILLED,channel=channel_PLN,+ lines_count=0,),Order(user=customer_user,status=OrderStatus.DRAFT,channel=channel_PLN,+ lines_count=0,),Order(user=customer_user,status=OrderStatus.UNCONFIRMED,channel=channel_PLN,+ lines_count=0,),])@@ -149,24 +155,28 @@ def orders_from_checkout(customer_user, checkout):status=OrderStatus.CANCELED,channel=checkout.channel,checkout_token=checkout.token,+ lines_count=0,),Order(user=customer_user,status=OrderStatus.UNFULFILLED,channel=checkout.channel,checkout_token=checkout.token,+ lines_count=0,),Order(user=customer_user,status=OrderStatus.FULFILLED,channel=checkout.channel,checkout_token=checkout.token,+ lines_count=0,),Order(user=customer_user,status=OrderStatus.FULFILLED,channel=checkout.channel,checkout_token=checkout.token,+ lines_count=0,),])@@ -203,6 +213,7 @@ def order_generator(customer_user, channel_USD):checkout_token=checkout_token,status=status,undiscounted_base_shipping_price_amount=Decimal("0.0"),+ lines_count=0,)if search_vector_class:search_vector = search_vector_class(@@ -236,6 +247,7 @@ def order_list(customer_user, channel_USD):"user_email": customer_user.email,"channel": channel_USD,"origin": OrderOrigin.CHECKOUT,+ "lines_count": 0,}order = Order.objects.create(**data)order1 = Order.objects.create(**data)@@ -420,6 +432,7 @@ def order_with_lines(order.base_shipping_price = netorder.undiscounted_base_shipping_price = netorder.shipping_tax_rate = calculate_tax_rate(order.shipping_price)+ order.lines_count = order.lines.count()order.save()recalculate_order(order)@@ -471,6 +484,7 @@ def order_with_lines_for_cc(user_email=customer_user.email,user=customer_user,origin=OrderOrigin.CHECKOUT,+ lines_count=1,)order.collection_point = warehouse_for_cc@@ -647,6 +661,8 @@ def order_with_lines_and_gift_promotion(amount_value=variant_listing.price_amount,currency=order.currency,)+ order.lines_count = order.lines.count()+ order.save(update_fields=["lines_count"])return order@@ -697,6 +713,7 @@ def order_with_lines_channel_PLN(user_email=customer_user.email,user=customer_user,origin=OrderOrigin.CHECKOUT,+ lines_count=0,)product = Product.objects.create(name="Test product in PLN channel",@@ -818,6 +835,7 @@ def order_with_lines_channel_PLN(order.base_shipping_price = netorder.undiscounted_base_shipping_price = netorder.shipping_tax_rate = calculate_tax_rate(order.shipping_price)+ order.lines_count = order.lines.count()order.save()recalculate_order(order)@@ -857,6 +875,8 @@ def order_with_line_without_inventory_tracking(tax_rate=Decimal("0.23"),**get_tax_class_kwargs_for_order_line(product.product_type.tax_class),)+ order.lines_count = order.lines.count()+ order.save(update_fields=["lines_count"])recalculate_order(order)@@ -934,6 +954,7 @@ def order_with_preorder_lines(order.shipping_price = TaxedMoney(net=net, gross=gross)order.base_shipping_price = netorder.undiscounted_base_shipping_price = net+ order.lines_count = order.lines.count()order.save()recalculate_order(order)@@ -1074,6 +1095,8 @@ def order_with_digital_line(order, digital_content, stock, site_settings):total_price=unit_price * quantity,tax_rate=Decimal("0.23"),)+ order.lines_count = order.lines.count()+ order.save(update_fields=["lines_count"])Allocation.objects.create(order_line=line, stock=stock, quantity_allocated=quantity)diff --git a/saleor/order/tests/fixtures/order_line.py b/saleor/order/tests/fixtures/order_line.pyindex 96e58a3906..4875e19593 100644--- a/saleor/order/tests/fixtures/order_line.py+++ b/saleor/order/tests/fixtures/order_line.py@@ -152,6 +152,7 @@ def order_line_with_allocation_in_many_stocks(channel=channel_USD,origin=OrderOrigin.CHECKOUT,undiscounted_base_shipping_price_amount=Decimal("0.0"),+ lines_count=0,)product = variant.product@@ -209,6 +210,7 @@ def order_line_with_one_allocation(user=customer_user,channel=channel_USD,origin=OrderOrigin.CHECKOUT,+ lines_count=0,)product = variant.productdiff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.pyindex 1667c4d9f8..f33965357a 100644--- a/saleor/order/tests/test_order.py+++ b/saleor/order/tests/test_order.py@@ -509,12 +509,18 @@ def test_validate_fulfillment_tracking_number_as_url(fulfilled_order):def test_order_queryset_confirmed(draft_order, channel_USD):other_orders = [- Order.objects.create(status=OrderStatus.UNFULFILLED, channel=channel_USD),Order.objects.create(- status=OrderStatus.PARTIALLY_FULFILLED, channel=channel_USD+ status=OrderStatus.UNFULFILLED, channel=channel_USD, lines_count=0+ ),+ Order.objects.create(+ status=OrderStatus.PARTIALLY_FULFILLED, channel=channel_USD, lines_count=0+ ),+ Order.objects.create(+ status=OrderStatus.FULFILLED, channel=channel_USD, lines_count=0+ ),+ Order.objects.create(+ status=OrderStatus.CANCELED, channel=channel_USD, lines_count=0),- Order.objects.create(status=OrderStatus.FULFILLED, channel=channel_USD),- Order.objects.create(status=OrderStatus.CANCELED, channel=channel_USD),]confirmed_orders = Order.objects.confirmed()@@ -525,12 +531,18 @@ def test_order_queryset_confirmed(draft_order, channel_USD):def test_order_queryset_drafts(draft_order, channel_USD):other_orders = [- Order.objects.create(status=OrderStatus.UNFULFILLED, channel=channel_USD),Order.objects.create(- status=OrderStatus.PARTIALLY_FULFILLED, channel=channel_USD+ status=OrderStatus.UNFULFILLED, channel=channel_USD, lines_count=0+ ),+ Order.objects.create(+ status=OrderStatus.PARTIALLY_FULFILLED, channel=channel_USD, lines_count=0+ ),+ Order.objects.create(+ status=OrderStatus.FULFILLED, channel=channel_USD, lines_count=0+ ),+ Order.objects.create(+ status=OrderStatus.CANCELED, channel=channel_USD, lines_count=0),- Order.objects.create(status=OrderStatus.FULFILLED, channel=channel_USD),- Order.objects.create(status=OrderStatus.CANCELED, channel=channel_USD),]draft_orders = Order.objects.drafts()@@ -547,12 +559,14 @@ def test_order_queryset_to_ship(settings, channel_USD):total=total,total_charged_amount=total.gross.amount,channel=channel_USD,+ lines_count=0,),Order.objects.create(status=OrderStatus.PARTIALLY_FULFILLED,total=total,total_charged_amount=total.gross.amount,channel=channel_USD,+ lines_count=0,),]for order in orders_to_ship:@@ -566,19 +580,28 @@ def test_order_queryset_to_ship(settings, channel_USD):orders_not_to_ship = [Order.objects.create(- status=OrderStatus.DRAFT, total=total, channel=channel_USD+ status=OrderStatus.DRAFT, total=total, channel=channel_USD, lines_count=0),Order.objects.create(- status=OrderStatus.UNFULFILLED, total=total, channel=channel_USD+ status=OrderStatus.UNFULFILLED,+ total=total,+ channel=channel_USD,+ lines_count=0,),Order.objects.create(- status=OrderStatus.PARTIALLY_FULFILLED, total=total, channel=channel_USD+ status=OrderStatus.PARTIALLY_FULFILLED,+ total=total,+ channel=channel_USD,+ lines_count=0,),Order.objects.create(- status=OrderStatus.FULFILLED, total=total, channel=channel_USD+ status=OrderStatus.FULFILLED,+ total=total,+ channel=channel_USD,+ lines_count=0,),Order.objects.create(- status=OrderStatus.CANCELED, total=total, channel=channel_USD+ status=OrderStatus.CANCELED, total=total, channel=channel_USD, lines_count=0),]@@ -592,17 +615,21 @@ def test_queryset_ready_to_capture(channel_USD):total = TaxedMoney(net=Money(10, "USD"), gross=Money(15, "USD"))preauth_order = Order.objects.create(- status=OrderStatus.UNFULFILLED, total=total, channel=channel_USD+ status=OrderStatus.UNFULFILLED, total=total, channel=channel_USD, lines_count=0)Payment.objects.create(order=preauth_order, charge_status=ChargeStatus.NOT_CHARGED, is_active=True)- Order.objects.create(status=OrderStatus.DRAFT, total=total, channel=channel_USD)Order.objects.create(- status=OrderStatus.UNFULFILLED, total=total, channel=channel_USD+ status=OrderStatus.DRAFT, total=total, channel=channel_USD, lines_count=0+ )+ Order.objects.create(+ status=OrderStatus.UNFULFILLED, total=total, channel=channel_USD, lines_count=0+ )+ Order.objects.create(+ status=OrderStatus.CANCELED, total=total, channel=channel_USD, lines_count=0)- Order.objects.create(status=OrderStatus.CANCELED, total=total, channel=channel_USD)qs = Order.objects.ready_to_capture()assert preauth_order in qsdiff --git a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.pyindex 0d0f832ae7..4bd419bb20 100644--- a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py+++ b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py@@ -362,7 +362,7 @@ def test_create_return_fulfillment_only_order_lines_with_replace_request(expected_replaced_line = order_lines_to_return[0]- assert replace_order.lines.count() == 1+ assert replace_order.lines_count == replace_order.lines.count() == 1replaced_line = replace_order.lines.first()# make sure that all data from original line is in replaced lineassert replaced_line.variant_id == expected_replaced_line.variant_id@@ -524,7 +524,7 @@ def test_create_return_fulfillment_only_fulfillment_lines_replace_order(expected_replaced_line = fulfillment_lines[0].order_line- assert replace_order.lines.count() == 1+ assert replace_order.lines_count == replace_order.lines.count() == 1replaced_line = replace_order.lines.first()# make sure that all data from original line is in replaced lineassert replaced_line.variant_id == expected_replaced_line.variant_iddiff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.pyindex 7c8f7a1e3a..414d35d451 100644--- a/saleor/order/tests/test_order_utils.py+++ b/saleor/order/tests/test_order_utils.py@@ -168,6 +168,7 @@ def test_match_draft_order_with_new_user(customer_user, channel_USD):user_email=customer_user.email,status=OrderStatus.DRAFT,channel=channel_USD,+ lines_count=0,)match_orders_with_new_user(customer_user)diff --git a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.pyindex ca968d7cfb..4c1244b6bd 100644--- a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py+++ b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py@@ -1124,7 +1124,7 @@ def test_order_calculate_taxes_empty_order(order, webhook_app, permission_handle_taxes, channel_USD):# given- order = Order.objects.create(channel=channel_USD, currency="USD")+ order = Order.objects.create(channel=channel_USD, currency="USD", lines_count=0)webhook_app.permissions.add(permission_handle_taxes)webhook = Webhook.objects.create(name="Webhook",diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.pyindex 23e5917398..2feab2ca3c 100644--- a/saleor/webhook/tests/test_webhook_payloads.py+++ b/saleor/webhook/tests/test_webhook_payloads.py@@ -78,6 +78,7 @@ def order_for_payload(fulfilled_order, voucher_percentage):new_order = Order.objects.create(channel=order.channel,billing_address=order.billing_address,+ lines_count=0,)order.origin = OrderOrigin.REISSUEorder.original = new_order