Skip to content

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

Migrate order line id from int to UUID (#9637)

Iga Karbowiak722309619d21
diff --git a/CHANGELOG.md b/CHANGELOG.md
index da12d73e08..5b250e3dfa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,9 @@
All notable, unreleased changes to this project will be documented in this file. For the released changes, please visit the [Releases](https://github.com/mirumee/saleor/releases) page.
# Unreleased
+- Migrate order line id from int to UUID - #9637 by @IKarbowiak
+ - Changed the order line `id` from `int` to `UUID`, the old ids still can be used
+ for old order lines.
- Fix invalid `ADDED_PRODUCTS` event parameter for `OrderLinesCreate` mutation - #9653 by @IKarbowiak
### Other changes
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index 413b6b2291..bef916608d 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -1,3 +1,4 @@
+import uuid
from typing import List
import graphene
@@ -197,7 +198,7 @@ class CustomerEvent(ModelObjectType):
def resolve_order_line(root: models.CustomerEvent, info):
if "order_line_pk" in root.parameters:
return OrderLineByIdLoader(info.context).load(
- root.parameters["order_line_pk"]
+ uuid.UUID(root.parameters["order_line_pk"])
)
return None
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index 039dffc4c2..36668dfac7 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -27,7 +27,13 @@ from ...core.permissions import (
)
from ..utils import get_nodes, resolve_global_ids_to_primary_keys
from .descriptions import DEPRECATED_IN_3X_FIELD
-from .types import File, NonNullList, Upload, UploadError
+from .types import (
+ TYPES_WITH_DOUBLE_ID_AVAILABLE,
+ File,
+ NonNullList,
+ Upload,
+ UploadError,
+)
from .utils import from_global_id_or_error, snake_to_camel_case
from .utils.error_codes import get_error_code_from_error
@@ -177,26 +183,24 @@ class BaseMutation(graphene.Mutation):
Whether by using the provided query set object or by calling type's get_node().
"""
if qs is not None:
- if str(graphene_type) == "Order":
- return cls._get_order_node_by_pk(pk, qs)
- return qs.filter(pk=pk).first()
+ lookup = Q(pk=pk)
+ if pk is not None and str(graphene_type) in TYPES_WITH_DOUBLE_ID_AVAILABLE:
+ # This is temporary solution that allows fetching objects with use of
+ # new and old id.
+ try:
+ UUID(str(pk))
+ except ValueError:
+ lookup = (
+ Q(number=pk) & Q(use_old_id=True)
+ if str(graphene_type) == "Order"
+ else Q(old_id=pk) & Q(old_id__isnull=False)
+ )
+ return qs.filter(lookup).first()
get_node = getattr(graphene_type, "get_node", None)
if get_node:
return get_node(info, pk)
return None
- @classmethod
- def _get_order_node_by_pk(cls, pk: Union[int, str], qs):
- # This is temporary method that allows fetching orders with use of
- # new and old id.
- lookup = Q(pk=pk)
- if pk is not None:
- try:
- UUID(str(pk))
- except ValueError:
- lookup = Q(number=pk) & Q(use_old_id=True)
- return qs.filter(lookup).first()
-
@classmethod
def get_global_id_or_error(
cls, id: str, only_type: Union[ObjectType, str] = None, field: str = "id"
diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.py
index 1667997c78..7c5b139e6d 100644
--- a/saleor/graphql/core/types/__init__.py
+++ b/saleor/graphql/core/types/__init__.py
@@ -1,5 +1,6 @@
# flake8: noqa
from .common import (
+ TYPES_WITH_DOUBLE_ID_AVAILABLE,
AccountError,
AppError,
AttributeError,
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index d54e3710f1..54f6888d4b 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -47,6 +47,10 @@ from ..enums import (
from ..scalars import PositiveDecimal
from .money import VAT
+# deprecated - this is temporary constant that contains the graphql types
+# which has double id available - uuid and old int id
+TYPES_WITH_DOUBLE_ID_AVAILABLE = ["Order", "OrderLine"]
+
class NonNullList(graphene.List):
"""A list type that automatically adds non-null constraint on contained items."""
diff --git a/saleor/graphql/core/types/model.py b/saleor/graphql/core/types/model.py
index a49e3a46c5..0b02125ebc 100644
--- a/saleor/graphql/core/types/model.py
+++ b/saleor/graphql/core/types/model.py
@@ -3,6 +3,8 @@ from uuid import UUID
from django.db.models import Model, Q
from graphene.types.objecttype import ObjectType, ObjectTypeOptions
+from . import TYPES_WITH_DOUBLE_ID_AVAILABLE
+
class ModelObjectOptions(ObjectTypeOptions):
model = None
@@ -46,24 +48,23 @@ class ModelObjectType(ObjectType):
@classmethod
def get_node(cls, _, id):
model = cls._meta.model
- try:
- if cls._meta.name == "Order":
- return cls._get_order(id, model)
- return model.objects.get(pk=id)
- except model.DoesNotExist:
- return None
-
- @classmethod
- def _get_order(cls, id, model):
- # This is temporary method that allows fetching orders with use of
- # new (uuid type) and old (int type) id
+ type_name = cls._meta.name
lookup = Q(pk=id)
- if id is not None:
+ if id is not None and type_name in TYPES_WITH_DOUBLE_ID_AVAILABLE:
+ # This is temporary solution that allows fetching orders with use of
+ # new (uuid type) and old (int type) id
try:
UUID(str(id))
except ValueError:
- lookup = Q(number=id) & Q(use_old_id=True)
- return model.objects.get(lookup)
+ lookup = (
+ Q(number=id) & Q(use_old_id=True)
+ if type_name == "Order"
+ else Q(old_id=id) & Q(old_id__isnull=False)
+ )
+ try:
+ return model.objects.get(lookup)
+ except model.DoesNotExist:
+ return None
@classmethod
def get_model(cls):
diff --git a/saleor/graphql/order/dataloaders.py b/saleor/graphql/order/dataloaders.py
index 94fef309f6..2228da08f2 100644
--- a/saleor/graphql/order/dataloaders.py
+++ b/saleor/graphql/order/dataloaders.py
@@ -65,7 +65,7 @@ class OrderLinesByOrderIdLoader(DataLoader):
lines = (
OrderLine.objects.using(self.database_connection_name)
.filter(order_id__in=keys)
- .order_by("pk")
+ .order_by("created_at")
)
line_map = defaultdict(list)
for line in lines.iterator():
diff --git a/saleor/graphql/order/tests/deprecated/test_order.py b/saleor/graphql/order/tests/deprecated/test_order.py
index 13c3d6d5d6..be1f373de6 100644
--- a/saleor/graphql/order/tests/deprecated/test_order.py
+++ b/saleor/graphql/order/tests/deprecated/test_order.py
@@ -1,11 +1,36 @@
import warnings
+from decimal import Decimal
+from functools import partial
+from unittest.mock import ANY, patch
-from prices import Money
+import graphene
+import pytest
+from prices import Money, TaxedMoney, fixed_discount
from .....channel.utils import DEPRECATION_WARNING_MESSAGE
+from .....core.prices import quantize_price
+from .....discount import DiscountValueType
+from .....order import OrderEvents, OrderOrigin, OrderStatus
+from .....order import events as order_events
+from .....order.fetch import OrderLineInfo
+from .....order.interface import OrderTaxedPricesData
+from .....order.models import FulfillmentStatus, Order, OrderEvent, OrderLine
+from .....payment import ChargeStatus
+from .....payment.interface import RefundData
from ....core.enums import ReportingPeriod
+from ....discount.enums import DiscountValueTypeEnum
from ....tests.utils import get_graphql_content
+
+def assert_proper_webhook_called_once(order, status, draft_mock, order_mock):
+ if status == OrderStatus.DRAFT:
+ draft_mock.assert_called_once_with(order)
+ order_mock.assert_not_called()
+ else:
+ draft_mock.assert_not_called()
+ order_mock.assert_called_once_with(order)
+
+
QUERY_ORDER_TOTAL = """
query Orders($period: ReportingPeriod, $channel: String) {
ordersTotal(period: $period, channel: $channel ) {
@@ -40,3 +65,659 @@ def test_orders_total(staff_api_client, permission_manage_orders, order_with_lin
assert any(
[str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
)
+
+
+ORDER_LINE_DELETE_MUTATION = """
+ mutation OrderLineDelete($id: ID!) {
+ orderLineDelete(id: $id) {
+ errors {
+ field
+ message
+ }
+ orderLine {
+ id
+ }
+ order {
+ id
+ total{
+ gross{
+ currency
+ amount
+ }
+ }
+ }
+ }
+ }
+"""
+
+
[email protected]("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
+@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+def test_order_line_remove_by_old_line_id(
+ order_updated_webhook_mock,
+ draft_order_updated_webhook_mock,
+ status,
+ order_with_lines,
+ permission_manage_orders,
+ staff_api_client,
+):
+ query = ORDER_LINE_DELETE_MUTATION
+ order = order_with_lines
+ order.status = status
+ order.save(update_fields=["status"])
+ line = order.lines.first()
+ line.old_id = 1
+ line.save(update_fields=["old_id"])
+
+ line_id = graphene.Node.to_global_id("OrderLine", line.old_id)
+ variables = {"id": line_id}
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderLineDelete"]
+ assert OrderEvent.objects.count() == 1
+ assert OrderEvent.objects.last().type == order_events.OrderEvents.REMOVED_PRODUCTS
+ assert data["orderLine"]["id"] == graphene.Node.to_global_id("OrderLine", line.pk)
+ assert line not in order.lines.all()
+ assert_proper_webhook_called_once(
+ order, status, draft_order_updated_webhook_mock, order_updated_webhook_mock
+ )
+
+
+ORDER_LINE_UPDATE_MUTATION = """
+ mutation OrderLineUpdate($lineId: ID!, $quantity: Int!) {
+ orderLineUpdate(id: $lineId, input: {quantity: $quantity}) {
+ errors {
+ field
+ message
+ }
+ orderLine {
+ id
+ quantity
+ }
+ order {
+ total {
+ gross {
+ amount
+ }
+ }
+ }
+ }
+ }
+"""
+
+
[email protected]("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
+@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+def test_order_line_update_by_old_line_id(
+ order_updated_webhook_mock,
+ draft_order_updated_webhook_mock,
+ status,
+ order_with_lines,
+ permission_manage_orders,
+ staff_api_client,
+ staff_user,
+):
+ # given
+ query = ORDER_LINE_UPDATE_MUTATION
+ order = order_with_lines
+ order.status = status
+ order.save(update_fields=["status"])
+ line = order.lines.first()
+ line.old_id = 1
+ line.save(update_fields=["old_id"])
+
+ new_quantity = 1
+ removed_quantity = 2
+ line_id = graphene.Node.to_global_id("OrderLine", line.old_id)
+ variables = {"lineId": line_id, "quantity": new_quantity}
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # Ensure the line has the expected quantity
+ assert line.quantity == 3
+
+ # No event should exist yet
+ assert not OrderEvent.objects.exists()
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderLineUpdate"]
+ assert data["orderLine"]["quantity"] == new_quantity
+ assert_proper_webhook_called_once(
+ order, status, draft_order_updated_webhook_mock, order_updated_webhook_mock
+ )
+ removed_items_event = OrderEvent.objects.last() # type: OrderEvent
+ assert removed_items_event.type == order_events.OrderEvents.REMOVED_PRODUCTS
+ assert removed_items_event.user == staff_user
+ assert removed_items_event.parameters == {
+ "lines": [
+ {"quantity": removed_quantity, "line_pk": str(line.pk), "item": str(line)}
+ ]
+ }
+
+
+ORDER_FULFILL_QUERY = """
+ mutation fulfillOrder(
+ $order: ID, $input: OrderFulfillInput!
+ ) {
+ orderFulfill(
+ order: $order,
+ input: $input
+ ) {
+ errors {
+ field
+ code
+ message
+ warehouse
+ orderLines
+ }
+ }
+ }
+"""
+
+
[email protected]("fulfillment_auto_approve", [True, False])
+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+def test_order_fulfill_old_line_id(
+ mock_create_fulfillments,
+ fulfillment_auto_approve,
+ staff_api_client,
+ staff_user,
+ order_with_lines,
+ permission_manage_orders,
+ warehouse,
+ site_settings,
+):
+ site_settings.fulfillment_auto_approve = fulfillment_auto_approve
+ site_settings.save(update_fields=["fulfillment_auto_approve"])
+ order = order_with_lines
+ query = ORDER_FULFILL_QUERY
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ order_line, order_line2 = order.lines.all()
+ order_line.old_id = 1
+ order_line2.old_id = 2
+ OrderLine.objects.bulk_update([order_line, order_line2], ["old_id"])
+
+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.old_id)
+ order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id)
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ variables = {
+ "order": order_id,
+ "input": {
+ "notifyCustomer": True,
+ "lines": [
+ {
+ "orderLineId": order_line_id,
+ "stocks": [{"quantity": 3, "warehouse": warehouse_id}],
+ },
+ {
+ "orderLineId": order_line2_id,
+ "stocks": [{"quantity": 2, "warehouse": warehouse_id}],
+ },
+ ],
+ },
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfill"]
+ assert not data["errors"]
+
+ fulfillment_lines_for_warehouses = {
+ str(warehouse.pk): [
+ {"order_line": order_line, "quantity": 3},
+ {"order_line": order_line2, "quantity": 2},
+ ]
+ }
+ mock_create_fulfillments.assert_called_once_with(
+ staff_user,
+ None,
+ order,
+ fulfillment_lines_for_warehouses,
+ ANY,
+ site_settings,
+ True,
+ allow_stock_to_be_exceeded=False,
+ approved=fulfillment_auto_approve,
+ )
+
+
+ORDER_FULFILL_REFUND_MUTATION = """
+mutation OrderFulfillmentRefundProducts(
+ $order: ID!, $input: OrderRefundProductsInput!
+) {
+ orderFulfillmentRefundProducts(
+ order: $order,
+ input: $input
+ ) {
+ fulfillment{
+ id
+ status
+ lines{
+ id
+ quantity
+ orderLine{
+ id
+ }
+ }
+ }
+ errors {
+ field
+ code
+ message
+ warehouse
+ orderLines
+ }
+ }
+}
+"""
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_fulfillment_refund_products_order_lines_by_old_id(
+ mocked_refund,
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ payment_dummy,
+):
+ # given
+ payment_dummy.total = order_with_lines.total_gross_amount
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ order_with_lines.payments.add(payment_dummy)
+ line_to_refund = order_with_lines.lines.first()
+ line_to_refund.old_id = 1
+ line_to_refund.save(update_fields=["old_id"])
+ order_id = graphene.Node.to_global_id("Order", order_with_lines.pk)
+ line_id = graphene.Node.to_global_id("OrderLine", line_to_refund.old_id)
+ variables = {
+ "order": order_id,
+ "input": {"orderLines": [{"orderLineId": line_id, "quantity": 2}]},
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentRefundProducts"]
+ refund_fulfillment = data["fulfillment"]
+ errors = data["errors"]
+ assert not errors
+ assert refund_fulfillment["status"] == FulfillmentStatus.REFUNDED.upper()
+ assert len(refund_fulfillment["lines"]) == 1
+ assert refund_fulfillment["lines"][0]["orderLine"][
+ "id"
+ ] == graphene.Node.to_global_id("OrderLine", line_to_refund.pk)
+ assert refund_fulfillment["lines"][0]["quantity"] == 2
+ mocked_refund.assert_called_with(
+ payment_dummy,
+ ANY,
+ amount=line_to_refund.unit_price_gross_amount * 2,
+ channel_slug=order_with_lines.channel.slug,
+ refund_data=RefundData(
+ order_lines_to_refund=[
+ OrderLineInfo(
+ line=line_to_refund,
+ quantity=2,
+ variant=line_to_refund.variant,
+ )
+ ],
+ ),
+ )
+
+
+ORDER_FULFILL_RETURN_MUTATION = """
+mutation OrderFulfillmentReturnProducts(
+ $order: ID!, $input: OrderReturnProductsInput!
+) {
+ orderFulfillmentReturnProducts(
+ order: $order,
+ input: $input
+ ) {
+ returnFulfillment{
+ id
+ status
+ lines{
+ id
+ quantity
+ orderLine{
+ id
+ }
+ }
+ }
+ replaceFulfillment{
+ id
+ status
+ lines{
+ id
+ quantity
+ orderLine{
+ id
+ }
+ }
+ }
+ order{
+ id
+ status
+ }
+ replaceOrder{
+ id
+ status
+ original
+ origin
+ }
+ errors {
+ field
+ code
+ message
+ warehouse
+ orderLines
+ }
+ }
+}
+"""
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_fulfillment_return_products_order_lines_by_old_line_id(
+ mocked_refund,
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ payment_dummy,
+):
+ payment_dummy.total = order_with_lines.total_gross_amount
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ order_with_lines.payments.add(payment_dummy)
+ line_to_return = order_with_lines.lines.first()
+ line_to_replace = order_with_lines.lines.last()
+ line_to_return.old_id = 10
+ line_to_return.save(update_fields=["old_id"])
+
+ line_unfulfilled_quantity = line_to_return.quantity_unfulfilled
+ line_quantity_to_return = 2
+
+ line_quantity_to_replace = 1
+
+ order_id = graphene.Node.to_global_id("Order", order_with_lines.pk)
+ line_id = graphene.Node.to_global_id("OrderLine", line_to_return.old_id)
+ replace_line_id = graphene.Node.to_global_id("OrderLine", line_to_replace.pk)
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "includeShippingCosts": True,
+ "orderLines": [
+ {
+ "orderLineId": line_id,
+ "quantity": line_quantity_to_return,
+ "replace": False,
+ },
+ {
+ "orderLineId": replace_line_id,
+ "quantity": line_quantity_to_replace,
+ "replace": True,
+ },
+ ],
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ order_with_lines.refresh_from_db()
+ order_return_fulfillment = order_with_lines.fulfillments.get(
+ status=FulfillmentStatus.REFUNDED_AND_RETURNED
+ )
+ return_fulfillment_line = order_return_fulfillment.lines.filter(
+ order_line_id=line_to_return.pk
+ ).first()
+ assert return_fulfillment_line
+ assert return_fulfillment_line.quantity == line_quantity_to_return
+
+ order_replace_fulfillment = order_with_lines.fulfillments.get(
+ status=FulfillmentStatus.REPLACED
+ )
+ replace_fulfillment_line = order_replace_fulfillment.lines.filter(
+ order_line_id=line_to_replace.pk
+ ).first()
+ assert replace_fulfillment_line
+ assert replace_fulfillment_line.quantity == line_quantity_to_replace
+
+ line_to_return.refresh_from_db()
+ assert (
+ line_to_return.quantity_unfulfilled
+ == line_unfulfilled_quantity - line_quantity_to_return
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ return_fulfillment = data["returnFulfillment"]
+ replace_fulfillment = data["replaceFulfillment"]
+ replace_order = data["replaceOrder"]
+ errors = data["errors"]
+
+ assert not errors
+ assert (
+ return_fulfillment["status"] == FulfillmentStatus.REFUNDED_AND_RETURNED.upper()
+ )
+ assert len(return_fulfillment["lines"]) == 1
+ assert return_fulfillment["lines"][0]["orderLine"][
+ "id"
+ ] == graphene.Node.to_global_id("OrderLine", line_to_return.pk)
+ assert return_fulfillment["lines"][0]["quantity"] == line_quantity_to_return
+
+ assert replace_fulfillment["status"] == FulfillmentStatus.REPLACED.upper()
+ assert len(replace_fulfillment["lines"]) == 1
+ assert replace_fulfillment["lines"][0]["orderLine"]["id"] == replace_line_id
+ assert replace_fulfillment["lines"][0]["quantity"] == line_quantity_to_replace
+
+ assert replace_order["status"] == OrderStatus.DRAFT.upper()
+ assert replace_order["origin"] == OrderOrigin.REISSUE.upper()
+ assert replace_order["original"] == order_id
+ replace_order = Order.objects.get(status=OrderStatus.DRAFT)
+ assert replace_order.lines.count() == 1
+ replaced_line = replace_order.lines.get()
+ assert replaced_line.variant_id == line_to_replace.variant_id
+ assert (
+ replaced_line.unit_price_gross_amount == line_to_replace.unit_price_gross_amount
+ )
+ assert replaced_line.quantity == line_quantity_to_replace
+
+ amount = line_to_return.unit_price_gross_amount * line_quantity_to_return
+ amount += order_with_lines.shipping_price_gross_amount
+ mocked_refund.assert_called_with(
+ payment_dummy,
+ ANY,
+ amount=amount,
+ channel_slug=order_with_lines.channel.slug,
+ refund_data=RefundData(
+ order_lines_to_refund=[
+ OrderLineInfo(
+ line=line_to_return,
+ quantity=line_quantity_to_return,
+ variant=line_to_return.variant,
+ ),
+ ],
+ refund_shipping_costs=True,
+ ),
+ )
+
+
+ORDER_LINE_DISCOUNT_UPDATE = """
+mutation OrderLineDiscountUpdate($input: OrderDiscountCommonInput!, $orderLineId: ID!){
+ orderLineDiscountUpdate(orderLineId: $orderLineId, input: $input){
+ orderLine{
+ unitPrice{
+ gross{
+ amount
+ }
+ }
+ }
+ errors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
+
[email protected]("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
+def test_update_order_line_discount_old_id(
+ status,
+ draft_order_with_fixed_discount_order,
+ staff_api_client,
+ permission_manage_orders,
+):
+ order = draft_order_with_fixed_discount_order
+ order.status = status
+ order.save(update_fields=["status"])
+ line_to_discount = order.lines.first()
+ unit_price = Money(Decimal(7.3), currency="USD")
+ line_to_discount.unit_price = TaxedMoney(unit_price, unit_price)
+ line_to_discount.undiscounted_unit_price = line_to_discount.unit_price
+ total_price = line_to_discount.unit_price * line_to_discount.quantity
+ line_to_discount.total_price = total_price
+ line_to_discount.undiscounted_total_price = total_price
+ line_to_discount.old_id = 1
+ line_to_discount.save()
+
+ line_price_before_discount = line_to_discount.unit_price
+
+ value = Decimal("5")
+ reason = "New reason for unit discount"
+ variables = {
+ "orderLineId": graphene.Node.to_global_id("OrderLine", line_to_discount.old_id),
+ "input": {
+ "valueType": DiscountValueTypeEnum.FIXED.name,
+ "value": value,
+ "reason": reason,
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_UPDATE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderLineDiscountUpdate"]
+
+ line_to_discount.refresh_from_db()
+
+ errors = data["errors"]
+ assert not errors
+
+ discount = partial(
+ fixed_discount,
+ discount=Money(value, currency=order.currency),
+ )
+ expected_line_price = discount(line_price_before_discount)
+
+ assert line_to_discount.unit_price == quantize_price(expected_line_price, "USD")
+ unit_discount = line_to_discount.unit_discount
+ assert unit_discount == (line_price_before_discount - expected_line_price).gross
+
+ event = order.events.get()
+ assert event.type == OrderEvents.ORDER_LINE_DISCOUNT_UPDATED
+ parameters = event.parameters
+ lines = parameters.get("lines", {})
+ assert len(lines) == 1
+
+ line_data = lines[0]
+ assert line_data.get("line_pk") == str(line_to_discount.pk)
+ discount_data = line_data.get("discount")
+
+ assert discount_data["value"] == str(value)
+ assert discount_data["value_type"] == DiscountValueTypeEnum.FIXED.value
+ assert discount_data["amount_value"] == str(unit_discount.amount)
+
+
+ORDER_LINE_DISCOUNT_REMOVE = """
+mutation OrderLineDiscountRemove($orderLineId: ID!){
+ orderLineDiscountRemove(orderLineId: $orderLineId){
+ orderLine{
+ id
+ }
+ errors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
+
+@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_unit")
+@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_total")
+def test_delete_discount_from_order_line_by_old_id(
+ mocked_calculate_order_line_total,
+ mocked_calculate_order_line_unit,
+ draft_order_with_fixed_discount_order,
+ staff_api_client,
+ permission_manage_orders,
+):
+ order = draft_order_with_fixed_discount_order
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+ line = order.lines.first()
+ line.old_id = 1
+ line.save(update_fields=["old_id"])
+
+ line_undiscounted_price = line.undiscounted_unit_price
+ line_undiscounted_total_price = line.undiscounted_total_price
+
+ mocked_calculate_order_line_unit.return_value = OrderTaxedPricesData(
+ undiscounted_price=line_undiscounted_price,
+ price_with_discounts=line_undiscounted_price,
+ )
+ mocked_calculate_order_line_total.return_value = OrderTaxedPricesData(
+ undiscounted_price=line_undiscounted_total_price,
+ price_with_discounts=line_undiscounted_total_price,
+ )
+
+ line.unit_discount_amount = Decimal("2.5")
+ line.unit_discount_type = DiscountValueType.FIXED
+ line.unit_discount_value = Decimal("2.5")
+ line.save()
+
+ variables = {
+ "orderLineId": graphene.Node.to_global_id("OrderLine", line.old_id),
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_REMOVE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderLineDiscountRemove"]
+
+ errors = data["errors"]
+ assert len(errors) == 0
+
+ line.refresh_from_db()
+
+ assert line.unit_price == line_undiscounted_price
+ assert line.total_price == line_undiscounted_total_price
+ unit_discount = line.unit_discount
+ currency = order.currency
+ assert unit_discount == Money(Decimal(0), currency=currency)
+
+ event = order.events.get()
+ assert event.type == OrderEvents.ORDER_LINE_DISCOUNT_REMOVED
+ parameters = event.parameters
+ lines = parameters.get("lines", {})
+ assert len(lines) == 1
+
+ line_data = lines[0]
+ assert line_data.get("line_pk") == str(line.pk)
diff --git a/saleor/graphql/order/tests/test_discount_order.py b/saleor/graphql/order/tests/test_discount_order.py
index 813218a794..0fa4c7da36 100644
--- a/saleor/graphql/order/tests/test_discount_order.py
+++ b/saleor/graphql/order/tests/test_discount_order.py
@@ -557,7 +557,7 @@ def test_update_order_line_discount(
assert len(lines) == 1
line_data = lines[0]
- assert line_data.get("line_pk") == line_to_discount.pk
+ assert line_data.get("line_pk") == str(line_to_discount.pk)
discount_data = line_data.get("discount")
assert discount_data["value"] == str(value)
@@ -640,7 +640,7 @@ def test_update_order_line_discount_line_with_discount(
assert len(lines) == 1
line_data = lines[0]
- assert line_data.get("line_pk") == line_to_discount.pk
+ assert line_data.get("line_pk") == str(line_to_discount.pk)
discount_data = line_data.get("discount")
assert discount_data["value"] == str(value)
@@ -760,7 +760,7 @@ def test_delete_discount_from_order_line(
assert len(lines) == 1
line_data = lines[0]
- assert line_data.get("line_pk") == line.pk
+ assert line_data.get("line_pk") == str(line.pk)
def test_delete_order_line_discount_order_is_not_draft(
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index fcfad20400..9bbd984843 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -1997,11 +1997,11 @@ def test_draft_order_create(
order_lines = list(order.lines.all())
assert event_parameters["lines"][0]["item"] == str(order_lines[0])
- assert event_parameters["lines"][0]["line_pk"] == order_lines[0].pk
+ assert event_parameters["lines"][0]["line_pk"] == str(order_lines[0].pk)
assert event_parameters["lines"][0]["quantity"] == 2
assert event_parameters["lines"][1]["item"] == str(order_lines[1])
- assert event_parameters["lines"][1]["line_pk"] == order_lines[1].pk
+ assert event_parameters["lines"][1]["line_pk"] == str(order_lines[1].pk)
assert event_parameters["lines"][1]["quantity"] == 1
@@ -4260,7 +4260,7 @@ def test_order_lines_create(
assert len(event.parameters["lines"]) == 1
line = OrderLine.objects.last()
assert event.parameters["lines"] == [
- {"item": str(line), "line_pk": line.pk, "quantity": quantity}
+ {"item": str(line), "line_pk": str(line.pk), "quantity": quantity}
]
content = get_graphql_content(response)
@@ -4827,7 +4827,9 @@ def test_order_line_update(
assert removed_items_event.type == order_events.OrderEvents.REMOVED_PRODUCTS
assert removed_items_event.user == staff_user
assert removed_items_event.parameters == {
- "lines": [{"quantity": removed_quantity, "line_pk": line.pk, "item": str(line)}]
+ "lines": [
+ {"quantity": removed_quantity, "line_pk": str(line.pk), "item": str(line)}
+ ]
}
# mutation should fail when quantity is lower than 1
@@ -4880,7 +4882,9 @@ def test_order_line_update_without_sku(
assert removed_items_event.type == order_events.OrderEvents.REMOVED_PRODUCTS
assert removed_items_event.user == staff_user
assert removed_items_event.parameters == {
- "lines": [{"quantity": removed_quantity, "line_pk": line.pk, "item": str(line)}]
+ "lines": [
+ {"quantity": removed_quantity, "line_pk": str(line.pk), "item": str(line)}
+ ]
}
line.refresh_from_db()
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 0ed22dd045..37d25fdba0 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -362,11 +362,11 @@ class OrderEvent(ModelObjectType):
for entry in raw_lines:
line_pk = entry.get("line_pk", None)
if line_pk:
- line_pks.append(line_pk)
+ line_pks.append(UUID(line_pk))
def _resolve_lines(lines):
results = []
- lines_dict = {line.pk: line for line in lines if line}
+ lines_dict = {str(line.pk): line for line in lines if line}
for raw_line in raw_lines:
line_pk = raw_line.get("line_pk")
line_object = lines_dict.get(line_pk)
diff --git a/saleor/graphql/utils/__init__.py b/saleor/graphql/utils/__init__.py
index bc6063cc55..64e4eda887 100644
--- a/saleor/graphql/utils/__init__.py
+++ b/saleor/graphql/utils/__init__.py
@@ -9,7 +9,7 @@ from graphql import GraphQLDocument
from graphql.error import GraphQLError
from ..core.enums import PermissionEnum
-from ..core.types import Permission
+from ..core.types import TYPES_WITH_DOUBLE_ID_AVAILABLE, Permission
from ..core.utils import from_global_id_or_error
ERROR_COULD_NO_RESOLVE_GLOBAL_ID = (
@@ -94,9 +94,9 @@ def get_nodes(
elif model is not None:
qs = model.objects
- is_order_object_type = str(graphene_type) == "Order"
- if is_order_object_type:
- nodes = _get_nodes_for_order(qs, pks)
+ is_object_type_with_double_id = str(graphene_type) in TYPES_WITH_DOUBLE_ID_AVAILABLE
+ if is_object_type_with_double_id:
+ nodes = _get_node_for_types_with_double_id(qs, pks, graphene_type)
else:
nodes = list(qs.filter(pk__in=pks))
nodes.sort(key=lambda e: pks.index(str(e.pk))) # preserve order in pks
@@ -105,8 +105,9 @@ def get_nodes(
raise GraphQLError(ERROR_COULD_NO_RESOLVE_GLOBAL_ID % ids)
nodes_pk_list = [str(node.pk) for node in nodes]
- if is_order_object_type:
- nodes_pk_list.extend([str(node.number) for node in nodes])
+ if is_object_type_with_double_id:
+ old_id_field = "number" if str(graphene_type) == "Order" else "old_id"
+ nodes_pk_list.extend([str(getattr(node, old_id_field)) for node in nodes])
for pk in pks:
assert pk in nodes_pk_list, "There is no node of type {} with pk {}".format(
graphene_type, pk
@@ -114,20 +115,27 @@ def get_nodes(
return nodes
-def _get_nodes_for_order(qs, pks):
+def _get_node_for_types_with_double_id(qs, pks, graphene_type):
uuid_pks = []
old_pks = []
+ is_order_type = str(graphene_type) == "Order"
for pk in pks:
try:
uuid_pks.append(UUID(str(pk)))
except ValueError:
old_pks.append(pk)
- nodes = list(
- qs.filter(Q(id__in=uuid_pks) | (Q(use_old_id=True) & Q(number__in=old_pks)))
- )
+ if is_order_type:
+ lookup = Q(id__in=uuid_pks) | (Q(use_old_id=True) & Q(number__in=old_pks))
+ else:
+ lookup = Q(id__in=uuid_pks) | (Q(old_id__isnull=False) & Q(old_id__in=old_pks))
+ nodes = list(qs.filter(lookup))
+ old_id_field = "number" if is_order_type else "old_id"
return sorted(
- nodes, key=lambda e: pks.index(str(e.pk) if e.pk in uuid_pks else str(e.number))
+ nodes,
+ key=lambda e: pks.index(
+ str(e.pk) if e.pk in uuid_pks else str(getattr(e, old_id_field))
+ ),
) # preserve order in pks
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 8374244556..d8d6eeac30 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -3,6 +3,7 @@ from collections import defaultdict
from copy import deepcopy
from decimal import Decimal
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple
+from uuid import UUID
from django.contrib.sites.models import Site
from django.db import transaction
@@ -72,7 +73,7 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
-OrderLineIDType = int
+OrderLineIDType = UUID
QuantityType = int
@@ -826,7 +827,7 @@ def _get_fulfillment_line_if_exists(
def _get_fulfillment_line(
target_fulfillment: Fulfillment,
lines_in_target_fulfillment: List[FulfillmentLine],
- order_line_id: int,
+ order_line_id: OrderLineIDType,
stock_id: Optional[int] = None,
) -> Tuple[FulfillmentLine, bool]:
"""Get fulfillment line if extists or create new fulfillment line object."""
diff --git a/saleor/order/migrations/0138_add_orderline_token_old_id_created_at.py b/saleor/order/migrations/0138_add_orderline_token_old_id_created_at.py
new file mode 100644
index 0000000000..dd1b75d5f3
--- /dev/null
+++ b/saleor/order/migrations/0138_add_orderline_token_old_id_created_at.py
@@ -0,0 +1,33 @@
+# Generated by Django 3.2.12 on 2022-04-11 12:28
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0137_alter_orderevent_type"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="orderline",
+ name="token",
+ field=models.UUIDField(null=True, unique=True),
+ ),
+ migrations.AddField(
+ model_name="orderline",
+ name="old_id",
+ field=models.PositiveIntegerField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="fulfillmentline",
+ name="order_line_token",
+ field=models.UUIDField(null=True),
+ ),
+ migrations.AddField(
+ model_name="orderline",
+ name="created_at",
+ field=models.DateTimeField(null=True),
+ ),
+ ]
diff --git a/saleor/order/migrations/0139_fulfil_orderline_token_old_id_created_at.py b/saleor/order/migrations/0139_fulfil_orderline_token_old_id_created_at.py
new file mode 100644
index 0000000000..2f5f9ad334
--- /dev/null
+++ b/saleor/order/migrations/0139_fulfil_orderline_token_old_id_created_at.py
@@ -0,0 +1,66 @@
+# Generated by Django 3.2.12 on 2022-04-11 12:32
+
+from django.db import migrations
+from django.db.models import F
+import uuid
+
+BATCH_SIZE = 10000
+
+
+def set_order_line_token_and_created_at(apps, _schema_editor):
+ OrderLine = apps.get_model("order", "OrderLine")
+ Order = apps.get_model("order", "Order")
+
+ queryset = OrderLine.objects.filter(token__isnull=True)
+ for batch_pks in queryset_in_batches(queryset):
+ order_lines = OrderLine.objects.filter(pk__in=batch_pks)
+ order_in_bulk = Order.objects.in_bulk(
+ order_lines.values_list("order_id", flat=True)
+ )
+ for order_line in order_lines:
+ order = order_in_bulk.get(order_line.order_id)
+ order_line.created_at = order.created_at.replace(second=order_line.pk)
+ order_line.token = uuid.uuid4()
+
+ OrderLine.objects.bulk_update(order_lines, ["token", "created_at"])
+
+
+def queryset_in_batches(queryset):
+ """Slice a queryset into batches.
+
+ Input queryset should be sorted be pk.
+ """
+ start_pk = 0
+
+ while True:
+ qs = queryset.order_by("pk").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]
+
+
+def set_order_line_old_id(apps, schema_editor):
+ OrderLine = apps.get_model("order", "OrderLine")
+ OrderLine.objects.all().update(old_id=F("id"))
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0138_add_orderline_token_old_id_created_at"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ set_order_line_token_and_created_at,
+ migrations.RunPython.noop,
+ ),
+ migrations.RunPython(
+ set_order_line_old_id, reverse_code=migrations.RunPython.noop
+ ),
+ ]
diff --git a/saleor/order/migrations/0140_alter_orderline_old_id_and_created_at.py b/saleor/order/migrations/0140_alter_orderline_old_id_and_created_at.py
new file mode 100644
index 0000000000..8d4055e9b1
--- /dev/null
+++ b/saleor/order/migrations/0140_alter_orderline_old_id_and_created_at.py
@@ -0,0 +1,23 @@
+# Generated by Django 3.2.12 on 2022-04-12 13:51
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0139_fulfil_orderline_token_old_id_created_at"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="orderline",
+ name="old_id",
+ field=models.PositiveIntegerField(null=True, unique=True, blank=True),
+ ),
+ migrations.AlterField(
+ model_name="orderline",
+ name="created_at",
+ field=models.DateTimeField(auto_now_add=True),
+ ),
+ ]
diff --git a/saleor/order/migrations/0141_fulfil_fulfillmentline_orderline_token.py b/saleor/order/migrations/0141_fulfil_fulfillmentline_orderline_token.py
new file mode 100644
index 0000000000..15e6e19565
--- /dev/null
+++ b/saleor/order/migrations/0141_fulfil_fulfillmentline_orderline_token.py
@@ -0,0 +1,25 @@
+# Generated by Django 3.2.12 on 2022-04-13 07:04
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0140_alter_orderline_old_id_and_created_at"),
+ ]
+
+ operations = [
+ migrations.RunSQL(
+ """
+ UPDATE order_fulfillmentline
+ SET order_line_token = (
+ SELECT token
+ FROM order_orderline
+ WHERE order_fulfillmentline.order_line_id = order_orderline.id
+ )
+ WHERE order_line_id IS NOT NULL;
+ """,
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/order/migrations/0142_alter_fulfillmentline_line.py b/saleor/order/migrations/0142_alter_fulfillmentline_line.py
new file mode 100644
index 0000000000..4b055e2418
--- /dev/null
+++ b/saleor/order/migrations/0142_alter_fulfillmentline_line.py
@@ -0,0 +1,24 @@
+# Generated by Django 3.2.12 on 2022-04-12 13:51
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0141_fulfil_fulfillmentline_orderline_token"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="fulfillmentline",
+ name="order_line",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="fulfillment_lines",
+ to="order.orderline",
+ to_field="old_id",
+ ),
+ ),
+ ]
diff --git a/saleor/order/migrations/0143_update_orderline_pk.py b/saleor/order/migrations/0143_update_orderline_pk.py
new file mode 100644
index 0000000000..7d56bd51af
--- /dev/null
+++ b/saleor/order/migrations/0143_update_orderline_pk.py
@@ -0,0 +1,40 @@
+# Generated by Django 3.2.12 on 2022-04-13 07:27
+
+from django.db import migrations, models
+import uuid
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0142_alter_fulfillmentline_line"),
+ ("warehouse", "0023_alter_orderline_relations"),
+ ("product", "0169_alter_digitalcontenturl_line"),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name="orderline",
+ name="id",
+ ),
+ migrations.AlterField(
+ model_name="orderline",
+ name="token",
+ field=models.UUIDField(
+ default=uuid.uuid4,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ unique=True,
+ ),
+ ),
+ migrations.RenameField(
+ model_name="orderline",
+ old_name="token",
+ new_name="id",
+ ),
+ migrations.AlterModelOptions(
+ name="orderline",
+ options={"ordering": ("created_at",)},
+ ),
+ ]
diff --git a/saleor/order/migrations/0144_rewrite_fulfillmentline_orderline_relation.py b/saleor/order/migrations/0144_rewrite_fulfillmentline_orderline_relation.py
new file mode 100644
index 0000000000..fc10d236a6
--- /dev/null
+++ b/saleor/order/migrations/0144_rewrite_fulfillmentline_orderline_relation.py
@@ -0,0 +1,39 @@
+# Generated by Django 3.2.12 on 2022-04-13 07:33
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0143_update_orderline_pk"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="fulfillmentline",
+ name="order_line_token",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE, to="order.orderline"
+ ),
+ ),
+ migrations.RemoveField(
+ model_name="fulfillmentline",
+ name="order_line",
+ ),
+ migrations.RenameField(
+ model_name="fulfillmentline",
+ old_name="order_line_token",
+ new_name="order_line",
+ ),
+ migrations.AlterField(
+ model_name="fulfillmentline",
+ name="order_line",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="fulfillment_lines",
+ to="order.orderline",
+ ),
+ ),
+ ]
diff --git a/saleor/order/migrations/0145_rewrite_order_events.py b/saleor/order/migrations/0145_rewrite_order_events.py
new file mode 100644
index 0000000000..8f0ea385b3
--- /dev/null
+++ b/saleor/order/migrations/0145_rewrite_order_events.py
@@ -0,0 +1,64 @@
+# Generated by Django 3.2.12 on 2022-04-25 08:31
+
+from django.db import migrations
+from django.db.models import Exists, OuterRef
+
+BATCH_SIZE = 5000
+
+
+def rewrite_order_events_parameters(apps, _schema_editor):
+ """Rewrite order events that have old `line_pk` value to `uuid` value."""
+ Order = apps.get_model("order", "Order")
+ OrderLine = apps.get_model("order", "OrderLine")
+ OrderEvent = apps.get_model("order", "OrderEvent")
+
+ queryset = OrderEvent.objects.filter(parameters__lines__isnull=False)
+ for batch_pks in queryset_in_batches(queryset):
+ events = OrderEvent.objects.filter(pk__in=batch_pks)
+ orders = Order.objects.filter(Exists(events.filter(order_id=OuterRef("id"))))
+ order_line_old_id_to_new_mapping = {
+ line_ids["old_id"]: str(line_ids["id"])
+ for line_ids in OrderLine.objects.filter(order__in=orders).values(
+ "old_id", "id"
+ )
+ }
+ for event in events:
+ lines = event.parameters["lines"]
+ for line_data in lines:
+ line_data["line_pk"] = order_line_old_id_to_new_mapping.get(
+ line_data["line_pk"]
+ )
+ OrderEvent.objects.bulk_update(events, ["parameters"])
+
+
+def queryset_in_batches(queryset):
+ """Slice a queryset into batches.
+
+ Input queryset should be sorted be pk.
+ """
+ start_pk = 0
+
+ while True:
+ qs = queryset.order_by("pk").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", "0144_rewrite_fulfillmentline_orderline_relation"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ rewrite_order_events_parameters,
+ migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index cf2167fe42..cdacc7858b 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -427,6 +427,9 @@ class OrderLineQueryset(models.QuerySet):
class OrderLine(models.Model):
+ id = models.UUIDField(primary_key=True, editable=False, unique=True, default=uuid4)
+ old_id = models.PositiveIntegerField(unique=True, null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
order = models.ForeignKey(
Order,
related_name="lines",
@@ -571,7 +574,7 @@ class OrderLine(models.Model):
objects = models.Manager.from_queryset(OrderLineQueryset)()
class Meta:
- ordering = ("pk",)
+ ordering = ("created_at",)
def __str__(self):
return (
@@ -658,7 +661,9 @@ class Fulfillment(ModelWithMetadata):
class FulfillmentLine(models.Model):
order_line = models.ForeignKey(
- OrderLine, related_name="fulfillment_lines", on_delete=models.CASCADE
+ OrderLine,
+ related_name="fulfillment_lines",
+ on_delete=models.CASCADE,
)
fulfillment = models.ForeignKey(
Fulfillment, related_name="lines", on_delete=models.CASCADE
diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.py
index 3011a77416..5fb8febc21 100644
--- a/saleor/order/tests/test_order_utils.py
+++ b/saleor/order/tests/test_order_utils.py
@@ -49,6 +49,7 @@ def test_change_quantity_generates_proper_event(
line = order_with_lines.lines.last()
line.quantity = previous_quantity
+
line_info = OrderLineInfo(
line=line,
quantity=line.quantity,
@@ -84,9 +85,14 @@ def test_change_quantity_generates_proper_event(
new_event = OrderEvent.objects.last() # type: OrderEvent
assert new_event.type == expected_type
assert new_event.user == staff_user
+ expected_line_pk = None if new_quantity == 0 else str(line.pk)
assert new_event.parameters == {
"lines": [
- {"quantity": expected_quantity, "line_pk": line.pk, "item": str(line)}
+ {
+ "quantity": expected_quantity,
+ "line_pk": expected_line_pk,
+ "item": str(line),
+ }
]
}
diff --git a/saleor/product/migrations/0167_digitalcontenturl_order_line_token.py b/saleor/product/migrations/0167_digitalcontenturl_order_line_token.py
new file mode 100644
index 0000000000..908726e810
--- /dev/null
+++ b/saleor/product/migrations/0167_digitalcontenturl_order_line_token.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.2.12 on 2022-04-12 13:59
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0166_update_publication_date_and_available_for_purchase"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="digitalcontenturl",
+ name="order_line_token",
+ field=models.UUIDField(null=True),
+ ),
+ ]
diff --git a/saleor/product/migrations/0168_fulfil_digitalcontenturl_orderline_token.py b/saleor/product/migrations/0168_fulfil_digitalcontenturl_orderline_token.py
new file mode 100644
index 0000000000..211ce10aee
--- /dev/null
+++ b/saleor/product/migrations/0168_fulfil_digitalcontenturl_orderline_token.py
@@ -0,0 +1,26 @@
+# Generated by Django 3.2.12 on 2022-04-12 14:00
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0167_digitalcontenturl_order_line_token"),
+ ("order", "0140_alter_orderline_old_id_and_created_at"),
+ ]
+
+ operations = [
+ migrations.RunSQL(
+ """
+ UPDATE product_digitalcontenturl
+ SET order_line_token = (
+ SELECT token
+ FROM order_orderline
+ WHERE product_digitalcontenturl.line_id = order_orderline.id
+ )
+ WHERE line_id IS NOT NULL;
+ """,
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/product/migrations/0169_alter_digitalcontenturl_line.py b/saleor/product/migrations/0169_alter_digitalcontenturl_line.py
new file mode 100644
index 0000000000..4aa582e0e8
--- /dev/null
+++ b/saleor/product/migrations/0169_alter_digitalcontenturl_line.py
@@ -0,0 +1,26 @@
+# Generated by Django 3.2.12 on 2022-04-12 14:03
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0168_fulfil_digitalcontenturl_orderline_token"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="digitalcontenturl",
+ name="line",
+ field=models.OneToOneField(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="digital_content_url",
+ to="order.orderline",
+ to_field="old_id",
+ ),
+ ),
+ ]
diff --git a/saleor/product/migrations/0170_rewrite_digitalcontenturl_orderline_relation.py b/saleor/product/migrations/0170_rewrite_digitalcontenturl_orderline_relation.py
new file mode 100644
index 0000000000..eed24d42f2
--- /dev/null
+++ b/saleor/product/migrations/0170_rewrite_digitalcontenturl_orderline_relation.py
@@ -0,0 +1,45 @@
+# Generated by Django 3.2.12 on 2022-04-13 07:33
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0143_update_orderline_pk"),
+ ("product", "0169_alter_digitalcontenturl_line"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="digitalcontenturl",
+ name="order_line_token",
+ field=models.OneToOneField(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="order.orderline",
+ ),
+ ),
+ migrations.RemoveField(
+ model_name="digitalcontenturl",
+ name="line",
+ ),
+ migrations.RenameField(
+ model_name="digitalcontenturl",
+ old_name="order_line_token",
+ new_name="line",
+ ),
+ migrations.AlterField(
+ model_name="digitalcontenturl",
+ name="line",
+ field=models.OneToOneField(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="digital_content_url",
+ to="order.orderline",
+ ),
+ ),
+ ]
diff --git a/saleor/product/tests/test_product.py b/saleor/product/tests/test_product.py
index b090e2a71c..e2d6de332a 100644
--- a/saleor/product/tests/test_product.py
+++ b/saleor/product/tests/test_product.py
@@ -329,7 +329,9 @@ def test_digital_product_increment_download(
assert download_event.type == account_events.CustomerEvents.DIGITAL_LINK_DOWNLOADED
assert download_event.user == expected_user
assert download_event.order == digital_content_url.line.order
- assert download_event.parameters == {"order_line_pk": digital_content_url.line.pk}
+ assert download_event.parameters == {
+ "order_line_pk": str(digital_content_url.line.pk)
+ }
def test_digital_product_view_url_downloaded_max_times(client, digital_content):
diff --git a/saleor/warehouse/migrations/0021_allocation_order_line_token.py b/saleor/warehouse/migrations/0021_allocation_order_line_token.py
new file mode 100644
index 0000000000..72696a70c9
--- /dev/null
+++ b/saleor/warehouse/migrations/0021_allocation_order_line_token.py
@@ -0,0 +1,23 @@
+# Generated by Django 3.2.12 on 2022-04-12 09:04
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("warehouse", "0020_merge_20220217_1316"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="allocation",
+ name="order_line_token",
+ field=models.UUIDField(null=True),
+ ),
+ migrations.AddField(
+ model_name="preorderallocation",
+ name="order_line_token",
+ field=models.UUIDField(null=True),
+ ),
+ ]
diff --git a/saleor/warehouse/migrations/0022_fulfil_allocation_order_line_token.py b/saleor/warehouse/migrations/0022_fulfil_allocation_order_line_token.py
new file mode 100644
index 0000000000..7bbbe009c9
--- /dev/null
+++ b/saleor/warehouse/migrations/0022_fulfil_allocation_order_line_token.py
@@ -0,0 +1,38 @@
+# Generated by Django 3.2.12 on 2022-04-12 09:05
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("warehouse", "0021_allocation_order_line_token"),
+ ("order", "0140_alter_orderline_old_id_and_created_at"),
+ ]
+
+ operations = [
+ migrations.RunSQL(
+ """
+ UPDATE warehouse_allocation
+ SET order_line_token = (
+ SELECT token
+ FROM order_orderline
+ WHERE warehouse_allocation.order_line_id = order_orderline.id
+ )
+ WHERE order_line_id IS NOT NULL;
+ """,
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ migrations.RunSQL(
+ """
+ UPDATE warehouse_preorderallocation
+ SET order_line_token = (
+ SELECT token
+ FROM order_orderline
+ WHERE warehouse_preorderallocation.order_line_id = order_orderline.id
+ )
+ WHERE order_line_id IS NOT NULL;
+ """,
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/warehouse/migrations/0023_alter_orderline_relations.py b/saleor/warehouse/migrations/0023_alter_orderline_relations.py
new file mode 100644
index 0000000000..e32676075d
--- /dev/null
+++ b/saleor/warehouse/migrations/0023_alter_orderline_relations.py
@@ -0,0 +1,34 @@
+# Generated by Django 3.2.12 on 2022-04-12 13:55
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("warehouse", "0022_fulfil_allocation_order_line_token"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="allocation",
+ name="order_line",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="allocations",
+ to="order.orderline",
+ to_field="old_id",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="preorderallocation",
+ name="order_line",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="preorder_allocations",
+ to="order.orderline",
+ to_field="old_id",
+ ),
+ ),
+ ]
diff --git a/saleor/warehouse/migrations/0024_rewrite_order_line_relations.py b/saleor/warehouse/migrations/0024_rewrite_order_line_relations.py
new file mode 100644
index 0000000000..543bdebf24
--- /dev/null
+++ b/saleor/warehouse/migrations/0024_rewrite_order_line_relations.py
@@ -0,0 +1,67 @@
+# Generated by Django 3.2.12 on 2022-04-13 07:33
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0143_update_orderline_pk"),
+ ("warehouse", "0023_alter_orderline_relations"),
+ ]
+
+ operations = [
+ # for Allocation model
+ migrations.AlterField(
+ model_name="allocation",
+ name="order_line_token",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE, to="order.orderline"
+ ),
+ ),
+ migrations.RemoveField(
+ model_name="allocation",
+ name="order_line",
+ ),
+ migrations.RenameField(
+ model_name="allocation",
+ old_name="order_line_token",
+ new_name="order_line",
+ ),
+ migrations.AlterField(
+ model_name="allocation",
+ name="order_line",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="allocations",
+ to="order.orderline",
+ ),
+ ),
+ # for PreorderAllocation model
+ migrations.AlterField(
+ model_name="preorderallocation",
+ name="order_line_token",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE, to="order.orderline"
+ ),
+ ),
+ migrations.RemoveField(
+ model_name="preorderallocation",
+ name="order_line",
+ ),
+ migrations.RenameField(
+ model_name="preorderallocation",
+ old_name="order_line_token",
+ new_name="order_line",
+ ),
+ migrations.AlterField(
+ model_name="preorderallocation",
+ name="order_line",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="preorder_allocations",
+ to="order.orderline",
+ ),
+ ),
+ ]