Skip to content

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

Migrate order discount id from int to UUID (#9729)

Iga Karbowiake371b0d1dac0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 864b38dcb0..1ec9a04649 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,10 @@ All notable, unreleased changes to this project will be documented in this file.
- Fix invalid `ADDED_PRODUCTS` event parameter for `OrderLinesCreate` mutation - #9653 by @IKarbowiak
- Fix sorting by publication date with pagination - #9741 by @IKarbowiak
- Fix max_length for voucher_code in Checkout model - #9791 by @SzymJ
+- Fix sorting by publication date with pagination - #9741 by IKarbowiak
+- Migrate order discount id from int to UUID - #9729 by @IKarbowiak
+ - Changed the order discount `id` from `int` to `UUID`, the old ids still can be used
+ for old order discounts.
### Other changes
- Fix for sending incorrect prices to Avatax - #9633 by @korycins
diff --git a/saleor/checkout/migrations/0048_alter_checkoutline_options.py b/saleor/checkout/migrations/0048_alter_checkoutline_options.py
new file mode 100644
index 0000000000..03e3f65b58
--- /dev/null
+++ b/saleor/checkout/migrations/0048_alter_checkoutline_options.py
@@ -0,0 +1,17 @@
+# Generated by Django 3.2.13 on 2022-05-16 07:42
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("checkout", "0047_merge_20220519_1029"),
+ ]
+
+ operations = [
+ migrations.AlterModelOptions(
+ name="checkoutline",
+ options={"ordering": ("created_at", "id")},
+ ),
+ ]
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index dd500f42de..deca353f25 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -196,7 +196,7 @@ class CheckoutLine(models.Model):
)
class Meta:
- ordering = ("created_at",)
+ ordering = ("created_at", "id")
def __str__(self):
return smart_str(self.variant)
diff --git a/saleor/discount/migrations/0040_orderdiscount_token_old_id_created_at.py b/saleor/discount/migrations/0040_orderdiscount_token_old_id_created_at.py
new file mode 100644
index 0000000000..091cd1c4cf
--- /dev/null
+++ b/saleor/discount/migrations/0040_orderdiscount_token_old_id_created_at.py
@@ -0,0 +1,28 @@
+# Generated by Django 3.2.13 on 2022-05-02 11:05
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("discount", "0039_rename_created_sale_created_at"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="orderdiscount",
+ name="created_at",
+ field=models.DateTimeField(null=True),
+ ),
+ migrations.AddField(
+ model_name="orderdiscount",
+ name="old_id",
+ field=models.PositiveIntegerField(blank=True, null=True, unique=True),
+ ),
+ migrations.AddField(
+ model_name="orderdiscount",
+ name="token",
+ field=models.UUIDField(null=True, unique=True),
+ ),
+ ]
diff --git a/saleor/discount/migrations/0041_fulfill_orderdiscount_token_created_at_old_id.py b/saleor/discount/migrations/0041_fulfill_orderdiscount_token_created_at_old_id.py
new file mode 100644
index 0000000000..ed56a00b02
--- /dev/null
+++ b/saleor/discount/migrations/0041_fulfill_orderdiscount_token_created_at_old_id.py
@@ -0,0 +1,72 @@
+# Generated by Django 3.2.13 on 2022-05-02 11:06
+
+from django.db import migrations
+from django.db.models import F
+import uuid
+import datetime
+import pytz
+
+BATCH_SIZE = 10000
+
+
+def set_order_discount_token_and_created_at(apps, _schema_editor):
+ OrderDiscount = apps.get_model("discount", "OrderDiscount")
+ Order = apps.get_model("order", "Order")
+
+ queryset = OrderDiscount.objects.filter(token__isnull=True)
+ for batch_pks in queryset_in_batches(queryset):
+ discounts = OrderDiscount.objects.filter(pk__in=batch_pks)
+ order_in_bulk = Order.objects.in_bulk(
+ discounts.values_list("order_id", flat=True)
+ )
+ for discount in discounts:
+ order = order_in_bulk.get(discount.order_id)
+ discount.created_at = (
+ order.created_at.replace(second=discount.pk)
+ if order
+ else datetime.datetime.now(pytz.UTC)
+ )
+ discount.token = uuid.uuid4()
+
+ OrderDiscount.objects.bulk_update(discounts, ["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_discount_old_id(apps, schema_editor):
+ OrderDiscount = apps.get_model("discount", "OrderDiscount")
+ OrderDiscount.objects.all().update(old_id=F("id"))
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("discount", "0040_orderdiscount_token_old_id_created_at"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ set_order_discount_token_and_created_at,
+ migrations.RunPython.noop,
+ ),
+ migrations.RunPython(
+ set_order_discount_old_id, reverse_code=migrations.RunPython.noop
+ ),
+ ]
diff --git a/saleor/discount/migrations/0042_migrate_orderdiscount_id_to_uuid.py b/saleor/discount/migrations/0042_migrate_orderdiscount_id_to_uuid.py
new file mode 100644
index 0000000000..9ac2f00003
--- /dev/null
+++ b/saleor/discount/migrations/0042_migrate_orderdiscount_id_to_uuid.py
@@ -0,0 +1,43 @@
+# Generated by Django 3.2.13 on 2022-05-02 11:13
+
+from django.db import migrations, models
+import uuid
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("discount", "0041_fulfill_orderdiscount_token_created_at_old_id"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="orderdiscount",
+ name="created_at",
+ field=models.DateTimeField(auto_now_add=True),
+ ),
+ migrations.AlterModelOptions(
+ name="orderdiscount",
+ options={"ordering": ("created_at", "id")},
+ ),
+ migrations.RemoveField(
+ model_name="orderdiscount",
+ name="id",
+ ),
+ migrations.AlterField(
+ model_name="orderdiscount",
+ name="token",
+ field=models.UUIDField(
+ default=uuid.uuid4,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ unique=True,
+ ),
+ ),
+ migrations.RenameField(
+ model_name="orderdiscount",
+ old_name="token",
+ new_name="id",
+ ),
+ ]
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 9007c98099..8c15b57f69 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -1,6 +1,7 @@
from decimal import Decimal
from functools import partial
from typing import TYPE_CHECKING, Optional
+from uuid import uuid4
from django.conf import settings
from django.contrib.postgres.indexes import GinIndex
@@ -352,6 +353,9 @@ class SaleTranslation(Translation):
class OrderDiscount(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.Order",
related_name="discounts",
@@ -392,4 +396,4 @@ class OrderDiscount(models.Model):
class Meta:
# Orders searching index
indexes = [GinIndex(fields=["name", "translated_name"])]
- ordering = ("pk",)
+ ordering = ("created_at", "id")
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 48ce1af661..fe231ba213 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -49,7 +49,7 @@ 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", "CheckoutLine"]
+TYPES_WITH_DOUBLE_ID_AVAILABLE = ["Order", "OrderLine", "OrderDiscount", "CheckoutLine"]
class NonNullList(graphene.List):
diff --git a/saleor/graphql/order/tests/deprecated/test_discount_order.py b/saleor/graphql/order/tests/deprecated/test_discount_order.py
new file mode 100644
index 0000000000..66bf801987
--- /dev/null
+++ b/saleor/graphql/order/tests/deprecated/test_discount_order.py
@@ -0,0 +1,172 @@
+from decimal import Decimal
+from functools import partial
+
+import graphene
+import pytest
+from prices import TaxedMoney, percentage_discount
+
+from .....discount import DiscountValueType
+from .....order import OrderEvents, OrderStatus
+from ....discount.enums import DiscountValueTypeEnum
+from ....tests.utils import get_graphql_content
+
+ORDER_DISCOUNT_DELETE = """
+mutation OrderDiscountDelete($discountId: ID!){
+ orderDiscountDelete(discountId: $discountId){
+ order{
+ id
+ }
+ errors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
+
[email protected]("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
+def test_delete_order_discount_from_order_with_old_id(
+ status,
+ draft_order_with_fixed_discount_order,
+ staff_api_client,
+ permission_manage_orders,
+):
+ # given
+ order = draft_order_with_fixed_discount_order
+ order.status = status
+ order.save(update_fields=["status"])
+
+ order_discount = draft_order_with_fixed_discount_order.discounts.get()
+ name = "discount translated"
+ translated_name = "discount translated name"
+ order_discount.name = name
+ order_discount.translated_name = translated_name
+ order_discount.old_id = 1
+ order_discount.save(update_fields=["name", "translated_name", "old_id"])
+
+ current_undiscounted_total = order.undiscounted_total
+
+ variables = {
+ "discountId": graphene.Node.to_global_id(
+ "OrderDiscount", order_discount.old_id
+ ),
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_DELETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderDiscountDelete"]
+
+ order.refresh_from_db()
+
+ errors = data["errors"]
+ assert len(errors) == 0
+
+ assert order.undiscounted_total == current_undiscounted_total
+ assert order.total == current_undiscounted_total
+
+ event = order.events.get()
+ assert event.type == OrderEvents.ORDER_DISCOUNT_DELETED
+
+ assert order.search_document
+ assert name not in order.search_document
+ assert translated_name not in order.search_document
+
+
+ORDER_DISCOUNT_UPDATE = """
+mutation OrderDiscountUpdate($discountId: ID!, $input: OrderDiscountCommonInput!){
+ orderDiscountUpdate(discountId:$discountId, input: $input){
+ order{
+ id
+ total{
+ gross{
+ amount
+ }
+ }
+ undiscountedTotal{
+ gross{
+ amount
+ }
+ }
+ }
+ errors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
+
[email protected]("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
+def test_update_percentage_order_discount_by_old_id(
+ status,
+ draft_order_with_fixed_discount_order,
+ staff_api_client,
+ permission_manage_orders,
+):
+ # given
+ order = draft_order_with_fixed_discount_order
+ order.status = status
+ order.save(update_fields=["status"])
+
+ order_discount = draft_order_with_fixed_discount_order.discounts.get()
+ order_discount.old_id = 1
+ order_discount.save(update_fields=["old_id"])
+
+ current_undiscounted_total = order.undiscounted_total
+
+ reason = "The reason of the discount"
+ value = Decimal("10.000")
+ variables = {
+ "discountId": graphene.Node.to_global_id("OrderDiscount", order_discount.pk),
+ "input": {
+ "valueType": DiscountValueTypeEnum.PERCENTAGE.name,
+ "value": value,
+ "reason": reason,
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_UPDATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderDiscountUpdate"]
+
+ order.refresh_from_db()
+
+ discount = partial(percentage_discount, percentage=value)
+ expected_net_total = discount(current_undiscounted_total.net)
+ expected_gross_total = discount(current_undiscounted_total.gross)
+ expected_total = TaxedMoney(expected_net_total, expected_gross_total)
+
+ errors = data["errors"]
+ assert len(errors) == 0
+
+ assert order.undiscounted_total == current_undiscounted_total
+
+ assert expected_total == order.total
+
+ assert order.discounts.count() == 1
+ order_discount = order.discounts.first()
+ assert order_discount.value == value
+ assert order_discount.value_type == DiscountValueType.PERCENTAGE
+ assert order_discount.amount == (current_undiscounted_total - expected_total).gross
+ assert order_discount.reason == reason
+
+ event = order.events.get()
+ assert event.type == OrderEvents.ORDER_DISCOUNT_UPDATED
+ parameters = event.parameters
+ discount_data = parameters.get("discount")
+
+ assert discount_data["value"] == str(value)
+ assert discount_data["value_type"] == DiscountValueTypeEnum.PERCENTAGE.value
+ assert discount_data["amount_value"] == str(order_discount.amount.amount)
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index b7d1f8ed4b..3d35c18d56 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -758,7 +758,7 @@ def test_order_discounts_query(
assert len(discounts_data) == 1
discount_data = discounts_data[0]
_, discount_id = graphene.Node.from_global_id(discount_data["id"])
- assert int(discount_id) == discount.id
+ assert discount_id == str(discount.id)
assert discount_data["valueType"] == discount.value_type.upper()
assert discount_data["value"] == discount.value
assert discount_data["amount"]["amount"] == discount.amount_value
diff --git a/saleor/order/migrations/0147_alter_orderline_options.py b/saleor/order/migrations/0147_alter_orderline_options.py
new file mode 100644
index 0000000000..92925ad0e0
--- /dev/null
+++ b/saleor/order/migrations/0147_alter_orderline_options.py
@@ -0,0 +1,17 @@
+# Generated by Django 3.2.13 on 2022-05-16 07:42
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0146_merge_20220512_1005"),
+ ]
+
+ operations = [
+ migrations.AlterModelOptions(
+ name="orderline",
+ options={"ordering": ("created_at", "id")},
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 176169c06a..6569cb1250 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -592,7 +592,7 @@ class OrderLine(models.Model):
objects = models.Manager.from_queryset(OrderLineQueryset)()
class Meta:
- ordering = ("created_at",)
+ ordering = ("created_at", "id")
def __str__(self):
return (
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 1609833b66..8199cc14df 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -1,6 +1,6 @@
import json
from dataclasses import asdict
-from datetime import datetime
+from datetime import datetime, timedelta
from decimal import Decimal
from itertools import chain
from unittest import mock
@@ -8,6 +8,7 @@ from unittest.mock import ANY
import graphene
import pytest
+import pytz
from django.core.serializers.json import DjangoJSONEncoder
from django.utils import timezone
from freezegun import freeze_time
@@ -104,6 +105,9 @@ def test_generate_order_payload(
name="Voucher",
)
+ discount_2.created_at = datetime.now(pytz.utc) + timedelta(days=1)
+ discount_2.save(update_fields=["created_at"])
+
line_without_sku = order.lines.last()
line_without_sku.product_sku = None
line_without_sku.save()