Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add a denormalised product_type_id on order_line (#17803)

Maciej Korycinski968881fb364b
diff --git a/saleor/celeryconf.py b/saleor/celeryconf.py
index b793479b44..7ccd5190e8 100644
--- a/saleor/celeryconf.py
+++ b/saleor/celeryconf.py
@@ -37,7 +37,7 @@ app.autodiscover_tasks(
packages=[
"saleor.order.migrations.tasks",
],
- related_name="saleor3_21",
+ related_name="saleor3_22",
)
app.autodiscover_tasks(lambda: discover_plugins_modules(settings.PLUGINS))
app.autodiscover_tasks(related_name="search_tasks")
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 2d1ae84f10..2e50ac937a 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -373,6 +373,7 @@ def _create_line_for_order(
translated_variant_name=translated_variant_name,
product_sku=variant.sku,
product_variant_id=variant.get_global_id(),
+ product_type_id=checkout_line_info.product.product_type_id,
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 791ca208f0..34dcf0bf49 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -718,6 +718,7 @@ def _get_new_order_line(order, variant, channel):
product_name=str(product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_type_id=product.product_type.id,
product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
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.py
index 2d29963956..4e7179ff87 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
@@ -5942,3 +5942,52 @@ def test_checkout_complete_with_different_email_than_user_email(
order = Order.objects.first()
assert order.user_email == checkout.email
assert order.user.email == checkout.user.email
+
+
+def test_checkout_complete_sets_product_type_id_for_all_order_lines(
+ user_api_client,
+ checkout_ready_to_complete,
+ payment_dummy,
+ address,
+):
+ # given
+ checkout = checkout_ready_to_complete
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ variant_id_to_product_type_id_map = {
+ line.variant.id: line.product_type.id for line in lines
+ }
+
+ total = calculations.checkout_total(
+ manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ )
+ payment = payment_dummy
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.save()
+ assert not payment.transactions.exists()
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+
+ order = Order.objects.first()
+ for line in order.lines.all():
+ assert (
+ line.product_type_id == variant_id_to_product_type_id_map[line.variant_id]
+ )
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
index e2e72433a4..5e3f4e6d21 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
@@ -5421,3 +5421,52 @@ def test_checkout_complete_with_different_email_than_user_email(
order = Order.objects.first()
assert order.user_email == checkout.email
assert order.user.email == checkout.user.email
+
+
+def test_checkout_complete_sets_product_type_id_for_all_order_lines(
+ user_api_client,
+ checkout_ready_to_complete,
+ address,
+ address_usa,
+ shipping_method,
+ transaction_events_generator,
+ transaction_item_generator,
+ customer_user,
+):
+ # given
+ checkout = prepare_checkout_for_test(
+ checkout_ready_to_complete,
+ address,
+ address_usa,
+ shipping_method,
+ transaction_item_generator,
+ transaction_events_generator,
+ user=customer_user,
+ save_billing_address=True,
+ save_shipping_address=True,
+ )
+
+ lines, _ = fetch_checkout_lines(checkout)
+
+ variant_id_to_product_type_id_map = {
+ line.variant.id: line.product_type.id for line in lines
+ }
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+
+ order = Order.objects.first()
+ for line in order.lines.all():
+ assert (
+ line.product_type_id == variant_id_to_product_type_id_map[line.variant_id]
+ )
diff --git a/saleor/graphql/order/bulk_mutations/order_bulk_create.py b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
index 518a4551dc..e9405d0ac9 100644
--- a/saleor/graphql/order/bulk_mutations/order_bulk_create.py
+++ b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
@@ -47,7 +47,7 @@ from ....order.utils import update_order_display_gross_prices, updates_amounts_f
from ....payment import TransactionEventType
from ....payment.models import TransactionEvent, TransactionItem
from ....permission.enums import OrderPermissions
-from ....product.models import ProductVariant
+from ....product.models import Product, ProductVariant
from ....shipping.models import ShippingMethod, ShippingMethodChannelListing
from ....tax.models import TaxClass, TaxConfiguration
from ....warehouse.management import stock_bulk_update
@@ -800,6 +800,12 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
orders = Order.objects.filter(
external_reference__in=identifiers.order_external_references.keys
)
+ product_ids = {variant.product_id for variant in variants}
+ product_id_to_product_type_id_map = dict(
+ Product.objects.filter(pk__in=product_ids).values_list(
+ "id", "product_type_id"
+ )
+ )
# Create dictionary
object_storage: dict[str, Any] = {}
@@ -842,6 +848,10 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
for object in [*warehouses, *shipping_methods, *tax_classes, *apps]:
object_storage[f"{object.__class__.__name__}.id.{object.pk}"] = object
+ object_storage["product_id_to_product_type_id_map"] = (
+ product_id_to_product_type_id_map
+ )
+
return object_storage
@classmethod
@@ -1756,10 +1766,15 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
code=OrderBulkCreateErrorCode.FUTURE_DATE,
)
)
-
+ product_type_id = None
+ if variant:
+ product_type_id = object_storage.get(
+ "product_id_to_product_type_id_map"
+ ).get(variant.product_id)
order_line = OrderLine(
order=order_data.order,
variant=variant,
+ product_type_id=product_type_id,
product_name=order_line_input.get("product_name") or variant.product.name,
variant_name=order_line_input.get("variant_name")
or (variant.name if variant else ""),
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
index e302c9433b..599baced18 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -4113,3 +4113,45 @@ def test_draft_order_create_create_with_language_code(
order = Order.objects.get(id=order_pk)
assert order.language_code == "pl"
+
+
+def test_draft_order_create_sets_product_type_id_for_order_line(
+ app_api_client,
+ permission_manage_orders,
+ customer_user,
+ product_available_in_many_channels,
+ channel_PLN,
+):
+ # given
+ variant = product_available_in_many_channels.variants.first()
+ query = DRAFT_ORDER_CREATE_MUTATION
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ expected_product_type_id = variant.product.product_type_id
+
+ variant_list = [
+ {"variantId": variant_id, "quantity": 2},
+ ]
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+
+ variables = {
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "channelId": channel_id,
+ }
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["draftOrderCreate"]["errors"]
+
+ order_line = OrderLine.objects.first()
+ assert order_line.product_type_id == expected_product_type_id
diff --git a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py b/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
index 4a6589b66a..8d4250fd5f 100644
--- a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
@@ -578,6 +578,7 @@ def test_order_bulk_create_unit_discount(
assert (
db_order.lines_count == len(order_bulk_input["lines"]) == db_order.lines.count()
)
+ assert db_order_line.product_type_id == variant.product.product_type_id
def test_order_bulk_create_unit_discount_mismatched_discount(
diff --git a/saleor/graphql/order/tests/mutations/test_order_lines_create.py b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
index 2a396ad303..18e09349f2 100644
--- a/saleor/graphql/order/tests/mutations/test_order_lines_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
@@ -2185,3 +2185,37 @@ def test_order_lines_create_existing_variant_and_custom_price_unset_expiration_d
line.refresh_from_db()
assert line.quantity == old_quantity + extra_quantity
assert line.draft_base_price_expire_at is None
+
+
[email protected]("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])
+def test_order_lines_create_sets_product_type_id_for_order_line(
+ status,
+ order,
+ permission_group_manage_orders,
+ staff_api_client,
+ variant_with_many_stocks,
+):
+ # given
+ query = ORDER_LINES_CREATE_MUTATION
+ order.status = status
+ order.save(update_fields=["status"])
+ variant = variant_with_many_stocks
+
+ quantity = 1
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}
+
+ expected_product_type_id = variant.product.product_type_id
+
+ # when
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["orderLinesCreate"]["errors"]
+
+ order.refresh_from_db()
+ assert len(order.lines.all()) == 1
+ assert order.lines.first().product_type_id == expected_product_type_id
diff --git a/saleor/order/migrations/0209_orderline_product_type_id.py b/saleor/order/migrations/0209_orderline_product_type_id.py
new file mode 100644
index 0000000000..f15d53096d
--- /dev/null
+++ b/saleor/order/migrations/0209_orderline_product_type_id.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.1 on 2025-06-03 11:22
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0208_order_lines_count_idx"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="orderline",
+ name="product_type_id",
+ field=models.IntegerField(blank=True, null=True),
+ ),
+ ]
diff --git a/saleor/order/migrations/0210_populated_order_line_product_type_id.py b/saleor/order/migrations/0210_populated_order_line_product_type_id.py
new file mode 100644
index 0000000000..6642ecce6f
--- /dev/null
+++ b/saleor/order/migrations/0210_populated_order_line_product_type_id.py
@@ -0,0 +1,26 @@
+from django.apps import apps as registry
+from django.db import migrations
+from django.db.models.signals import post_migrate
+
+from .tasks.saleor3_22 import populate_order_line_product_type_id_task
+
+
+def populate_order_line_product_id(apps, _schema_editor):
+ def on_migrations_complete(sender=None, **kwargs):
+ populate_order_line_product_type_id_task.delay()
+
+ sender = registry.get_app_config("order")
+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0209_orderline_product_type_id"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ populate_order_line_product_id,
+ reverse_code=migrations.RunPython.noop,
+ )
+ ]
diff --git a/saleor/order/migrations/tasks/saleor3_22.py b/saleor/order/migrations/tasks/saleor3_22.py
new file mode 100644
index 0000000000..4f8dd9956e
--- /dev/null
+++ b/saleor/order/migrations/tasks/saleor3_22.py
@@ -0,0 +1,55 @@
+from django.db import transaction
+
+from ....celeryconf import app
+from ....core.db.connection import allow_writer
+from ....product.models import Product, ProductVariant
+from ...models import OrderLine
+
+ORDER_LINE_PRODUCT_ID_BATCH_SIZE = 250
+
+
+@allow_writer()
+def populate_order_line_product_type_id_task(line_pk=None):
+ """Populate product id for order lines."""
+ if line_pk is None:
+ line_pk = 0
+ lines = OrderLine.objects.filter(
+ pk__gte=line_pk, variant__isnull=False, product_type_id__isnull=True
+ )
+ qs = lines.order_by("pk")
+
+ line_id_with_variant_id = qs.values_list("pk", "variant_id")[
+ :ORDER_LINE_PRODUCT_ID_BATCH_SIZE
+ ]
+
+ variant_id_to_product_id = dict(
+ ProductVariant.objects.filter(
+ pk__in=[variant_id for _, variant_id in line_id_with_variant_id]
+ ).values_list("id", "product_id")
+ )
+
+ product_id_to_product_type_id_map = dict(
+ Product.objects.filter(pk__in=variant_id_to_product_id.values()).values_list(
+ "id", "product_type_id"
+ )
+ )
+ variant_id_to_product_type_id = {
+ variant_id: product_id_to_product_type_id_map[product_id]
+ for variant_id, product_id in variant_id_to_product_id.items()
+ }
+
+ line_pks = [line_id for (line_id, _) in line_id_with_variant_id]
+ if line_pks:
+ lines = OrderLine.objects.filter(pk__in=line_pks).order_by("pk")
+ with transaction.atomic():
+ to_save = []
+ _lines_lock = list(lines.select_for_update(of=(["self"])))
+ for line in lines:
+ product_type_id = variant_id_to_product_type_id.get(line.variant_id)
+ if not product_type_id:
+ continue
+ line.product_type_id = product_type_id
+ to_save.append(line)
+ OrderLine.objects.bulk_update(to_save, ["product_type_id"])
+ populate_order_line_product_type_id_task.delay(line_pks[-1])
diff --git a/saleor/order/models.py b/saleor/order/models.py
index db5ea1c2ef..354ce57510 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -571,6 +571,10 @@ class OrderLine(ModelWithMetadata):
product_sku = models.CharField(max_length=255, null=True, blank=True)
# str with GraphQL ID used as fallback when product SKU is not available
product_variant_id = models.CharField(max_length=255, null=True, blank=True)
+
+ # denormalized product type id
+ product_type_id = models.IntegerField(null=True, blank=True)
+
is_shipping_required = models.BooleanField()
is_gift_card = models.BooleanField()
quantity = models.IntegerField(validators=[MinValueValidator(1)])
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 8ba5600cfb..714485c776 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -307,6 +307,7 @@ def create_order_line(
product_sku=variant.sku,
product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
+ product_type_id=product.product_type_id,
is_gift_card=variant.is_gift_card(),
quantity=quantity,
unit_price=unit_price,