Skip to content

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

Filter Customer/Order/Sale/Product/ProductVariant by datetime of last modification (#9137)

Rafał Pitoń55a845c7b193
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3569d17f5..b45783f1cc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,8 @@ All notable, unreleased changes to this project will be documented in this file.
### Breaking changes
### Other changes
+- Filter Customer/Order/Sale/Product/ProductVariant by datetime of last modification - #9137 by @rafalp
+
# 3.1.0
diff --git a/saleor/account/migrations/0060_user_updated_at.py b/saleor/account/migrations/0060_user_updated_at.py
new file mode 100644
index 0000000000..80c869be0e
--- /dev/null
+++ b/saleor/account/migrations/0060_user_updated_at.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.2.12 on 2022-02-09 15:36
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("account", "0059_merge_20220221_1025"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="user",
+ name="updated_at",
+ field=models.DateTimeField(null=True, db_index=True),
+ ),
+ ]
diff --git a/saleor/account/migrations/0061_populate_user_updated_at.py b/saleor/account/migrations/0061_populate_user_updated_at.py
new file mode 100644
index 0000000000..c572c77fec
--- /dev/null
+++ b/saleor/account/migrations/0061_populate_user_updated_at.py
@@ -0,0 +1,23 @@
+# Generated by Django 3.2.12 on 2022-02-09 15:36
+
+from django.db import migrations
+from django.db.models import F
+
+
+def populate_user_updated_at_datetimes(apps, _schema_editor):
+ User = apps.get_model("account", "User")
+ User.objects.filter(updated_at__isnull=True).update(updated_at=F("date_joined"))
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("account", "0060_user_updated_at"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ populate_user_updated_at_datetimes,
+ migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/account/migrations/0062_alter_user_updated_at.py b/saleor/account/migrations/0062_alter_user_updated_at.py
new file mode 100644
index 0000000000..03c02409e8
--- /dev/null
+++ b/saleor/account/migrations/0062_alter_user_updated_at.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.2.12 on 2022-02-09 15:37
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("account", "0061_populate_user_updated_at"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="user",
+ name="updated_at",
+ field=models.DateTimeField(auto_now=True, db_index=True),
+ ),
+ ]
diff --git a/saleor/account/models.py b/saleor/account/models.py
index 0b2651dd87..62f10ef342 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -159,6 +159,7 @@ class User(PermissionsMixin, ModelWithMetadata, AbstractBaseUser):
is_active = models.BooleanField(default=True)
note = models.TextField(null=True, blank=True)
date_joined = models.DateTimeField(default=timezone.now, editable=False)
+ updated_at = models.DateTimeField(auto_now=True, db_index=True)
default_shipping_address = models.ForeignKey(
Address, related_name="+", null=True, blank=True, on_delete=models.SET_NULL
)
diff --git a/saleor/account/utils.py b/saleor/account/utils.py
index e6ea6aa9af..08aec64fa4 100644
--- a/saleor/account/utils.py
+++ b/saleor/account/utils.py
@@ -65,12 +65,12 @@ def remove_the_oldest_user_address(user: "User"):
def set_user_default_billing_address(user, address):
user.default_billing_address = address
- user.save(update_fields=["default_billing_address"])
+ user.save(update_fields=["default_billing_address", "updated_at"])
def set_user_default_shipping_address(user, address):
user.default_shipping_address = address
- user.save(update_fields=["default_shipping_address"])
+ user.save(update_fields=["default_shipping_address", "updated_at"])
def change_user_default_address(
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index a78434b370..52af9eab1d 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -1695,6 +1695,7 @@ def create_checkout_with_preorders():
"is_preorder",
"preorder_global_threshold",
"preorder_end_date",
+ "updated_at",
]
)
add_variant_to_checkout(checkout_info, product_variant, 2)
diff --git a/saleor/discount/migrations/0033_auto_20220209_1543.py b/saleor/discount/migrations/0033_auto_20220209_1543.py
new file mode 100644
index 0000000000..1cad9bfebb
--- /dev/null
+++ b/saleor/discount/migrations/0033_auto_20220209_1543.py
@@ -0,0 +1,23 @@
+# Generated by Django 3.2.12 on 2022-02-09 15:43
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("discount", "0032_merge_20211109_1210"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sale",
+ name="created",
+ field=models.DateTimeField(db_index=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="sale",
+ name="updated_at",
+ field=models.DateTimeField(db_index=True, null=True),
+ ),
+ ]
diff --git a/saleor/discount/migrations/0034_populate_sales_datetimes.py b/saleor/discount/migrations/0034_populate_sales_datetimes.py
new file mode 100644
index 0000000000..78ddcd9952
--- /dev/null
+++ b/saleor/discount/migrations/0034_populate_sales_datetimes.py
@@ -0,0 +1,25 @@
+# Generated by Django 3.2.12 on 2022-02-09 15:43
+
+from django.db import migrations
+from django.utils import timezone
+
+
+def populate_sales_datetimes(apps, _schema_editor):
+ timestamp = timezone.now()
+
+ Sale = apps.get_model("discount", "Sale")
+ Sale.objects.update(created=timestamp, updated_at=timestamp)
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("discount", "0033_auto_20220209_1543"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ populate_sales_datetimes,
+ migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/discount/migrations/0035_auto_20220209_1544.py b/saleor/discount/migrations/0035_auto_20220209_1544.py
new file mode 100644
index 0000000000..7274d4a846
--- /dev/null
+++ b/saleor/discount/migrations/0035_auto_20220209_1544.py
@@ -0,0 +1,23 @@
+# Generated by Django 3.2.12 on 2022-02-09 15:44
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("discount", "0034_populate_sales_datetimes"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="sale",
+ name="created",
+ field=models.DateTimeField(auto_now_add=True, db_index=True),
+ ),
+ migrations.AlterField(
+ model_name="sale",
+ name="updated_at",
+ field=models.DateTimeField(auto_now=True, db_index=True),
+ ),
+ ]
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index bf7d0893f2..d2bdf8a6b0 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -264,6 +264,8 @@ class Sale(ModelWithMetadata):
variants = models.ManyToManyField("product.ProductVariant", blank=True)
start_date = models.DateTimeField(default=timezone.now)
end_date = models.DateTimeField(null=True, blank=True)
+ created = models.DateTimeField(auto_now_add=True, db_index=True)
+ updated_at = models.DateTimeField(auto_now=True, db_index=True)
objects = models.Manager.from_queryset(SaleQueryset)()
translated = TranslationProxy()
diff --git a/saleor/graphql/account/filters.py b/saleor/graphql/account/filters.py
index 2d4c16b882..7be5264eab 100644
--- a/saleor/graphql/account/filters.py
+++ b/saleor/graphql/account/filters.py
@@ -9,7 +9,7 @@ from ..core.filters import (
MetadataFilterBase,
ObjectTypeFilter,
)
-from ..core.types.common import DateRangeInput, IntRangeInput
+from ..core.types.common import DateRangeInput, DateTimeRangeInput, IntRangeInput
from ..utils.filters import filter_by_id, filter_range_field
from . import types as account_types
from .enums import StaffMemberStatus
@@ -19,6 +19,10 @@ def filter_date_joined(qs, _, value):
return filter_range_field(qs, "date_joined__date", value)
+def filter_updated_at(qs, _, value):
+ return filter_range_field(qs, "updated_at", value)
+
+
def filter_number_of_orders(qs, _, value):
qs = qs.annotate(total_orders=Count("orders"))
return filter_range_field(qs, "total_orders", value)
@@ -50,6 +54,9 @@ class CustomerFilter(MetadataFilterBase):
date_joined = ObjectTypeFilter(
input_class=DateRangeInput, method=filter_date_joined
)
+ updated_at = ObjectTypeFilter(
+ input_class=DateTimeRangeInput, method=filter_updated_at
+ )
number_of_orders = ObjectTypeFilter(
input_class=IntRangeInput, method=filter_number_of_orders
)
diff --git a/saleor/graphql/account/mutations/account.py b/saleor/graphql/account/mutations/account.py
index 18020248cf..874714eaa0 100644
--- a/saleor/graphql/account/mutations/account.py
+++ b/saleor/graphql/account/mutations/account.py
@@ -341,7 +341,7 @@ class AccountAddressCreate(ModelMutation, I18nMixin):
instance.user_addresses.add(user)
info.context.plugins.customer_updated(user)
user.search_document = search.prepare_user_search_document_value(user)
- user.save(update_fields=["search_document"])
+ user.save(update_fields=["search_document", "updated_at"])
class AccountAddressUpdate(BaseAddressUpdate):
@@ -546,7 +546,7 @@ class ConfirmEmailChange(BaseMutation):
user.email = new_email
user.search_document = search.prepare_user_search_document_value(user)
- user.save(update_fields=["email", "search_document"])
+ user.save(update_fields=["email", "search_document", "updated_at"])
channel_slug = clean_channel(
data.get("channel"), error_class=AccountErrorCode
diff --git a/saleor/graphql/account/mutations/authentication.py b/saleor/graphql/account/mutations/authentication.py
index 6924afd3f4..693a5f4787 100644
--- a/saleor/graphql/account/mutations/authentication.py
+++ b/saleor/graphql/account/mutations/authentication.py
@@ -129,7 +129,7 @@ class CreateToken(BaseMutation):
info.context.refresh_token = refresh_token
info.context._cached_user = user
user.last_login = timezone.now()
- user.save(update_fields=["last_login"])
+ user.save(update_fields=["last_login", "updated_at"])
return cls(
errors=[],
user=user,
@@ -306,7 +306,7 @@ class DeactivateAllUserTokens(BaseMutation):
def perform_mutation(cls, root, info, **data):
user = info.context.user
user.jwt_token_key = get_random_string()
- user.save(update_fields=["jwt_token_key"])
+ user.save(update_fields=["jwt_token_key", "updated_at"])
return cls()
@@ -386,7 +386,7 @@ class ExternalObtainAccessTokens(BaseMutation):
if access_tokens_response.user and access_tokens_response.user.id:
info.context._cached_user = access_tokens_response.user
access_tokens_response.user.last_login = timezone.now()
- access_tokens_response.user.save(update_fields=["last_login"])
+ access_tokens_response.user.save(update_fields=["last_login", "updated_at"])
return cls(
token=access_tokens_response.token,
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index 31a4322aee..f0da140e2d 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -110,7 +110,7 @@ class SetPassword(CreateToken):
except ValidationError as error:
raise ValidationError({"password": error})
user.set_password(password)
- user.save(update_fields=["password"])
+ user.save(update_fields=["password", "updated_at"])
account_events.customer_password_reset_event(user=user)
@@ -237,7 +237,7 @@ class ConfirmAccount(BaseMutation):
)
user.is_active = True
- user.save(update_fields=["is_active"])
+ user.save(update_fields=["is_active", "updated_at"])
match_orders_with_new_user(user)
assign_user_gift_cards(user)
@@ -284,7 +284,7 @@ class PasswordChange(BaseMutation):
raise ValidationError({"new_password": error})
user.set_password(new_password)
- user.save(update_fields=["password"])
+ user.save(update_fields=["password", "updated_at"])
account_events.customer_password_changed_event(user=user)
return PasswordChange(user=user)
@@ -326,7 +326,7 @@ class BaseAddressUpdate(ModelMutation, I18nMixin):
user = address.user_addresses.first()
user.search_document = prepare_user_search_document_value(user)
- user.save(update_fields=["search_document"])
+ user.save(update_fields=["search_document", "updated_at"])
info.context.plugins.customer_updated(user)
address = info.context.plugins.change_user_address(address, None, user)
@@ -385,7 +385,7 @@ class BaseAddressDelete(ModelDeleteMutation):
user.refresh_from_db()
user.search_document = prepare_user_search_document_value(user)
- user.save(update_fields=["search_document"])
+ user.save(update_fields=["search_document", "updated_at"])
response = cls.success_response(instance)
@@ -503,7 +503,7 @@ class BaseCustomerCreate(ModelMutation, I18nMixin):
instance.addresses.add(default_shipping_address)
instance.search_document = prepare_user_search_document_value(instance)
- instance.save(update_fields=["search_document"])
+ instance.save(update_fields=["search_document", "updated_at"])
# The instance is a new object in db, create an event
if is_creation:
diff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.py
index 64ebe54bd8..6b7ac801a9 100644
--- a/saleor/graphql/account/mutations/staff.py
+++ b/saleor/graphql/account/mutations/staff.py
@@ -478,7 +478,7 @@ class AddressCreate(ModelMutation):
user.addresses.add(address)
response.user = user
user.search_document = prepare_user_search_document_value(user)
- user.save(update_fields=["search_document"])
+ user.save(update_fields=["search_document", "updated_at"])
return response
diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.py
index a054d9a7ab..f816df34ce 100644
--- a/saleor/graphql/account/tests/test_account.py
+++ b/saleor/graphql/account/tests/test_account.py
@@ -4634,9 +4634,23 @@ def test_query_customers_with_filter_placed_orders(
({"dateJoined": {"lte": "2012-01-14"}}, 1),
({"dateJoined": {"lte": "2012-01-14", "gte": "2012-01-13"}}, 1),
({"dateJoined": {"gte": "2012-01-14"}}, 2),
+ ({"updatedAt": {"gte": "2012-01-14T10:59:00+00:00"}}, 2),
+ ({"updatedAt": {"gte": "2012-01-14T11:01:00+00:00"}}, 1),
+ ({"updatedAt": {"lte": "2012-01-14T12:00:00+00:00"}}, 1),
+ ({"updatedAt": {"lte": "2011-01-14T10:59:00+00:00"}}, 0),
+ (
+ {
+ "updatedAt": {
+ "lte": "2012-01-14T12:00:00+00:00",
+ "gte": "2012-01-14T10:00:00+00:00",
+ }
+ },
+ 1,
+ ),
+ ({"updatedAt": {"gte": "2012-01-14T10:00:00+00:00"}}, 2),
],
)
-def test_query_customers_with_filter_date_joined(
+def test_query_customers_with_filter_date_joined_and_updated_at(
customer_filter,
count,
query_customer_with_filter,
@@ -4652,7 +4666,6 @@ def test_query_customers_with_filter_date_joined(
)
content = get_graphql_content(response)
users = content["data"]["customers"]["edges"]
-
assert len(users) == count
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index 0227ead7a4..0d416b287d 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -279,6 +279,7 @@ class User(ModelObjectType):
last_login = graphene.DateTime()
date_joined = graphene.DateTime(required=True)
+ updated_at = graphene.DateTime(required=True)
class Meta:
description = "Represents user data."
diff --git a/saleor/graphql/discount/filters.py b/saleor/graphql/discount/filters.py
index 5b6071d22e..c4b167d65e 100644
--- a/saleor/graphql/discount/filters.py
+++ b/saleor/graphql/discount/filters.py
@@ -75,6 +75,10 @@ def filter_voucher_search(qs, _, value):
return qs
+def filter_updated_at_range(qs, _, value):
+ return filter_range_field(qs, "updated_at", value)
+
+
class VoucherFilter(MetadataFilterBase):
status = ListObjectTypeFilter(input_class=DiscountStatusEnum, method=filter_status)
times_used = ObjectTypeFilter(input_class=IntRangeInput, method=filter_times_used)
@@ -96,6 +100,9 @@ class SaleFilter(MetadataFilterBase):
input_class=DiscountValueTypeEnum, method=filter_sale_type
)
started = ObjectTypeFilter(input_class=DateTimeRangeInput, method=filter_started)
+ updated_at = ObjectTypeFilter(
+ input_class=DateTimeRangeInput, method=filter_updated_at_range
+ )
search = django_filters.CharFilter(method=filter_sale_search)
class Meta:
diff --git a/saleor/graphql/discount/tests/test_discount.py b/saleor/graphql/discount/tests/test_discount.py
index 0d678b97fd..9cdc0f3b99 100644
--- a/saleor/graphql/discount/tests/test_discount.py
+++ b/saleor/graphql/discount/tests/test_discount.py
@@ -5,6 +5,7 @@ import graphene
import pytest
from django.utils import timezone
from django_countries import countries
+from freezegun import freeze_time
from ....discount import DiscountValueType, VoucherType
from ....discount.error_codes import DiscountErrorCode
@@ -1788,6 +1789,61 @@ def test_query_sales_with_filter_started(
assert len(data) == count
+ "sale_filter, count",
+ [
+ ({"updatedAt": {"gte": "2012-01-14T10:59:00+00:00"}}, 2),
+ ({"updatedAt": {"lte": "2012-01-14T12:00:05+00:00"}}, 2),
+ ({"updatedAt": {"gte": "2012-01-14T11:59:00+00:00"}}, 1),
+ ({"updatedAt": {"lte": "2012-01-14T11:05:00+00:00"}}, 1),
+ ({"updatedAt": {"gte": "2012-01-14T12:01:00+00:00"}}, 0),
+ ({"updatedAt": {"lte": "2012-01-14T10:59:00+00:00"}}, 0),
+ (
+ {
+ "updatedAt": {
+ "lte": "2012-01-14T12:01:00+00:00",
+ "gte": "2012-01-14T11:59:00+00:00",
+ },
+ },
+ 1,
+ ),
+ ],
+)
+def test_query_sales_with_filter_updated_at(
+ sale_filter,
+ count,
+ staff_api_client,
+ query_sales_with_filter,
+ permission_manage_discounts,
+ channel_USD,
+):
+ with freeze_time("2012-01-14 11:00:00"):
+ sale_1 = Sale.objects.create(name="Sale1")
+
+ with freeze_time("2012-01-14 12:00:00"):
+ sale_2 = Sale.objects.create(name="Sale2")
+
+ SaleChannelListing.objects.bulk_create(
+ [
+ SaleChannelListing(
+ sale=sale,
+ discount_value=123,
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ )
+ for sale in [sale_1, sale_2]
+ ]
+ )
+
+ variables = {"filter": sale_filter}
+ response = staff_api_client.post_graphql(
+ query_sales_with_filter, variables, permissions=[permission_manage_discounts]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["sales"]["edges"]
+ assert len(data) == count
+
+
@pytest.mark.parametrize(
"sale_filter, count",
[({"search": "Big"}, 1), ({"search": "69"}, 1), ({"search": "FIX"}, 2)],
diff --git a/saleor/graphql/discount/types.py b/saleor/graphql/discount/types.py
index abd2359209..8c79e89101 100644
--- a/saleor/graphql/discount/types.py
+++ b/saleor/graphql/discount/types.py
@@ -63,6 +63,8 @@ class Sale(ChannelContextTypeWithMetadata, ModelObjectType):
type = SaleType(required=True)
start_date = graphene.DateTime(required=True)
end_date = graphene.DateTime()
+ created = graphene.DateTime(required=True)
+ updated_at = graphene.DateTime(required=True)
categories = ConnectionField(
CategoryCountableConnection,
description="List of categories this sale applies to.",
diff --git a/saleor/graphql/meta/mutations.py b/saleor/graphql/meta/mutations.py
index c0a357809a..587cb0ef67 100644
--- a/saleor/graphql/meta/mutations.py
+++ b/saleor/graphql/meta/mutations.py
@@ -1,7 +1,7 @@
from typing import List
import graphene
-from django.core.exceptions import ValidationError
+from django.core.exceptions import FieldDoesNotExist, ValidationError
from graphql.error.base import GraphQLError
from ...checkout import models as checkout_models
@@ -23,6 +23,18 @@ from .permissions import PRIVATE_META_PERMISSION_MAP, PUBLIC_META_PERMISSION_MAP
from .types import ObjectWithMetadata
+def _save_instance(instance, metadata_field: str):
+ fields = [metadata_field]
+
+ try:
+ if bool(instance._meta.get_field("updated_at")):
+ fields.append("updated_at")
+ except FieldDoesNotExist:
+ pass
+
+ instance.save(update_fields=fields)
+
+
class MetadataPermissionOptions(graphene.types.mutation.MutationOptions):
permission_map = {}
@@ -247,7 +259,7 @@ class UpdateMetadata(BaseMetadataMutation):
cls.validate_metadata_keys(metadata_list)
items = {data.key: data.value for data in metadata_list}
instance.store_value_in_metadata(items=items)
- instance.save(update_fields=["metadata"])
+ _save_instance(instance, "metadata")
return cls.success_response(instance)
@@ -276,7 +288,7 @@ class DeleteMetadata(BaseMetadataMutation):
metadata_keys = data.pop("keys")
for key in metadata_keys:
instance.delete_value_from_metadata(key)
- instance.save(update_fields=["metadata"])
+ _save_instance(instance, "metadata")
return cls.success_response(instance)
@@ -306,7 +318,7 @@ class UpdatePrivateMetadata(BaseMetadataMutation):
cls.validate_metadata_keys(metadata_list)
items = {data.key: data.value for data in metadata_list}
instance.store_value_in_private_metadata(items=items)
- instance.save(update_fields=["private_metadata"])
+ _save_instance(instance, "private_metadata")
return cls.success_response(instance)
@@ -335,5 +347,5 @@ class DeletePrivateMetadata(BaseMetadataMutation):
metadata_keys = data.pop("keys")
for key in metadata_keys:
instance.delete_value_from_private_metadata(key)
- instance.save(update_fields=["private_metadata"])
+ _save_instance(instance, "private_metadata")
return cls.success_response(instance)
diff --git a/saleor/graphql/order/filters.py b/saleor/graphql/order/filters.py
index 35b9a754f9..8b7067d2b3 100644
--- a/saleor/graphql/order/filters.py
+++ b/saleor/graphql/order/filters.py
@@ -14,7 +14,7 @@ from ..core.filters import (
MetadataFilterBase,
ObjectTypeFilter,
)
-from ..core.types.common import DateRangeInput
+from ..core.types.common import DateRangeInput, DateTimeRangeInput
from ..core.utils import from_global_id_or_error
from ..payment.enums import PaymentChargeStatusEnum
from ..utils import resolve_global_ids_to_primary_keys
@@ -70,6 +70,10 @@ def filter_created_range(qs, _, value):
return filter_range_field(qs, "created__date", value)
+def filter_updated_at_range(qs, _, value):
+ return filter_range_field(qs, "updated_at", value)
+
+
def filter_order_search(qs, _, value):
return search_orders(qs, value)
@@ -141,6 +145,9 @@ class OrderFilter(DraftOrderFilter):
status = ListObjectTypeFilter(input_class=OrderStatusFilter, method=filter_status)
customer = django_filters.CharFilter(method=filter_customer)
created = ObjectTypeFilter(input_class=DateRangeInput, method=filter_created_range)
+ updated_at = ObjectTypeFilter(
+ input_class=DateTimeRangeInput, method=filter_updated_at_range
+ )
search = django_filters.CharFilter(method=filter_order_search)
channels = GlobalIDMultipleChoiceFilter(method=filter_channels)
is_click_and_collect = django_filters.BooleanFilter(
diff --git a/saleor/graphql/order/mutations/discount_order.py b/saleor/graphql/order/mutations/discount_order.py
index 767cd30a9a..dcd17ba2fb 100644
--- a/saleor/graphql/order/mutations/discount_order.py
+++ b/saleor/graphql/order/mutations/discount_order.py
@@ -89,6 +89,7 @@ class OrderDiscountCommon(BaseMutation):
"total_gross_amount",
"undiscounted_total_net_amount",
"undiscounted_total_gross_amount",
+ "updated_at",
]
)
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index 771affe78f..c96b043c46 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -279,7 +279,9 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
order=instance, user=info.context.user, app=info.context.app
)
- instance.save(update_fields=["billing_address", "shipping_address"])
+ instance.save(
+ update_fields=["billing_address", "shipping_address", "updated_at"]
+ )
@classmethod
def _refresh_lines_unit_price(cls, info, instance, cleaned_input, new_instance):
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index ab5bf02af4..de14824d77 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -347,6 +347,7 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
"shipping_price_net_amount",
"shipping_price_gross_amount",
"shipping_method_name",
+ "updated_at",
]
)
recalculate_order(order)
@@ -397,6 +398,7 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
"shipping_price_net_amount",
"shipping_price_gross_amount",
"shipping_tax_rate",
+ "updated_at",
]
)
update_order_prices(
@@ -740,7 +742,7 @@ class OrderConfirm(ModelMutation):
def perform_mutation(cls, root, info, **data):
order = cls.get_instance(info, **data)
order.status = OrderStatus.UNFULFILLED
- order.save(update_fields=["status"])
+ order.save(update_fields=["status", "updated_at"])
order_info = fetch_order_info(order)
payment = order_info.payment
manager = info.context.plugins
@@ -939,6 +941,7 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):
"shipping_price_net_amount",
"shipping_price_gross_amount",
"shipping_method_name",
+ "updated_at",
]
)
# Create the removal event
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index d00301706a..6e02e35c6b 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -7002,6 +7002,49 @@ def test_order_query_with_filter_created(
assert len(orders) == count
+ "orders_filter, count",
+ [
+ ({"updatedAt": {"gte": "2012-01-14T10:59:00+00:00"}}, 2),
+ ({"updatedAt": {"lte": "2012-01-14T12:00:05+00:00"}}, 2),
+ ({"updatedAt": {"gte": "2012-01-14T11:59:00+00:00"}}, 1),
+ ({"updatedAt": {"lte": "2012-01-14T11:05:00+00:00"}}, 1),
+ ({"updatedAt": {"gte": "2012-01-14T12:01:00+00:00"}}, 0),
+ ({"updatedAt": {"lte": "2012-01-14T10:59:00+00:00"}}, 0),
+ (
+ {
+ "updatedAt": {
+ "lte": "2012-01-14T12:01:00+00:00",
+ "gte": "2012-01-14T11:59:00+00:00",
+ },
+ },
+ 1,
+ ),
+ ],
+)
+def test_order_query_with_filter_updated_at(
+ orders_filter,
+ count,
+ orders_query_with_filter,
+ staff_api_client,
+ permission_manage_orders,
+ channel_USD,
+):
+ with freeze_time("2012-01-14 11:00:00"):
+ Order.objects.create(channel=channel_USD)
+
+ with freeze_time("2012-01-14 12:00:00"):
+ Order.objects.create(channel=channel_USD)
+
+ variables = {"filter": orders_filter}
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
+ content = get_graphql_content(response)
+ orders = content["data"]["orders"]["edges"]
+
+ assert len(orders) == count
+
+
@pytest.mark.parametrize(
"orders_filter, count, payment_status",
[
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index a75a3d1959..c3a21966b7 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -623,6 +623,7 @@ class OrderLine(ModelObjectType):
class Order(ModelObjectType):
id = graphene.GlobalID(required=True)
created = graphene.DateTime(required=True)
+ updated_at = graphene.DateTime(required=True)
status = OrderStatusEnum(required=True)
user = graphene.Field(User)
tracking_client_id = graphene.String(required=True)
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index b3d2f0fc63..f7b3601a1c 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -637,7 +637,9 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
for product in products:
product.search_document = prepare_product_search_document_value(product)
product.default_variant = product.variants.first()
- product.save(update_fields=["default_variant", "search_document"])
+ product.save(
+ update_fields=["default_variant", "search_document", "updated_at"]
+ )
return response
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index e443ad600d..a043e1d28f 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -42,7 +42,7 @@ from ..core.filters import (
ObjectTypeFilter,
)
from ..core.types import ChannelFilterInputObjectType, FilterInputObjectType
-from ..core.types.common import IntRangeInput, PriceRangeInput
+from ..core.types.common import DateTimeRangeInput, IntRangeInput, PriceRangeInput
from ..utils import resolve_global_ids_to_primary_keys
from ..utils.filters import filter_by_id, filter_range_field
from ..warehouse import types as warehouse_types
@@ -560,6 +560,10 @@ def filter_quantity(qs, quantity_value, warehouse_ids=None):
return qs.filter(pk__in=variants)
+def filter_updated_at_range(qs, _, value):
+ return filter_range_field(qs, "updated_at", value)
+
+
class ProductStockFilterInput(graphene.InputObjectType):
warehouse_ids = graphene.List(graphene.NonNull(graphene.ID), required=False)
quantity = graphene.Field(IntRangeInput, required=False)
@@ -583,6 +587,9 @@ class ProductFilter(MetadataFilterBase):
stock_availability = EnumFilter(
input_class=StockAvailability, method="filter_stock_availability"
)
+ updated_at = ObjectTypeFilter(
+ input_class=DateTimeRangeInput, method=filter_updated_at_range
+ )
product_types = GlobalIDMultipleChoiceFilter(method=filter_product_types)
stocks = ObjectTypeFilter(input_class=ProductStockFilterInput, method=filter_stocks)
search = django_filters.CharFilter(method=filter_search)
@@ -634,6 +641,9 @@ class ProductVariantFilter(MetadataFilterBase):
search = django_filters.CharFilter(method="product_variant_filter_search")
sku = ListObjectTypeFilter(input_class=graphene.String, method=filter_sku_list)
is_preorder = django_filters.BooleanFilter(method=filter_is_preorder)
+ updated_at = ObjectTypeFilter(
+ input_class=DateTimeRangeInput, method=filter_updated_at_range
+ )
class Meta:
model = ProductVariant
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index deffad9903..99f81cdd22 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -1125,7 +1125,7 @@ class ProductVariantDelete(ModelDeleteMutation):
# if the product default variant has been removed set the new one
if not product.default_variant:
product.default_variant = product.variants.first()
- product.save(update_fields=["default_variant"])
+ product.save(update_fields=["default_variant", "updated_at"])
instance = ChannelContext(node=instance, channel_slug=None)
return super().success_response(instance)
@@ -1693,7 +1693,7 @@ class ProductVariantReorder(BaseMutation):
with traced_atomic_transaction():
perform_reordering(variants_m2m, operations)
- product.save(update_fields=["updated_at"])
+ product.save(update_fields=["updated_at", "updated_at"])
info.context.plugins.product_updated(product)
product = ChannelContext(node=product, channel_slug=None)
return ProductVariantReorder(product=product)
diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.py
index e329e11056..d52c728d93 100644
--- a/saleor/graphql/product/sorters.py
+++ b/saleor/graphql/product/sorters.py
@@ -126,6 +126,7 @@ class ProductOrderField(graphene.Enum):
RANK = ["name", "slug"]
PRICE = ["min_variants_price_amount", "name", "slug"]
MINIMAL_PRICE = ["discounted_price_amount", "name", "slug"]
+ LAST_MODIFIED = ["updated_at", "name", "slug"]
DATE = ["updated_at", "name", "slug"]
TYPE = ["product_type__name", "name", "slug"]
PUBLISHED = ["is_published", "name", "slug"]
diff --git a/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py b/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py
index d8f1337cf3..634f28bdc1 100644
--- a/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py
+++ b/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py
@@ -3,6 +3,7 @@ import uuid
from decimal import Decimal
import pytest
+from freezegun import freeze_time
from ....product import ProductTypeKind
from ....product.models import (
@@ -578,3 +579,59 @@ def test_published_products_without_sku_as_staff(
content = get_graphql_content(response)
products_nodes = content["data"]["products"]["edges"]
assert len(products_nodes) == 3
+
+
+ "products_filter, count",
+ [
+ ({"updatedAt": {"gte": "2012-01-14T10:59:00+00:00"}}, 2),
+ ({"updatedAt": {"lte": "2012-01-14T12:00:05+00:00"}}, 2),
+ ({"updatedAt": {"gte": "2012-01-14T11:59:00+00:00"}}, 1),
+ ({"updatedAt": {"lte": "2012-01-14T11:05:00+00:00"}}, 1),
+ ({"updatedAt": {"gte": "2012-01-14T12:01:00+00:00"}}, 0),
+ ({"updatedAt": {"lte": "2012-01-14T10:59:00+00:00"}}, 0),
+ (
+ {
+ "updatedAt": {
+ "lte": "2012-01-14T12:01:00+00:00",
+ "gte": "2012-01-14T11:59:00+00:00",
+ },
+ },
+ 1,
+ ),
+ ],
+)
+def test_product_query_with_filter_updated_at(
+ products_filter,
+ count,
+ product_type,
+ category,
+ staff_api_client,
+ permission_manage_products,
+):
+ with freeze_time("2012-01-14 11:00:00"):
+ Product.objects.create(
+ name="Product1",
+ slug="prod1",
+ category=category,
+ product_type=product_type,
+ )
+
+ with freeze_time("2012-01-14 12:00:00"):
+ Product.objects.create(
+ name="Product2",
+ slug="prod2",
+ category=category,
+ product_type=product_type,
+ )
+
+ variables = {"filter": products_filter}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCTS_WITH_SORTING_AND_FILTERING, variables
+ )
+ content = get_graphql_content(response)
+ variants = content["data"]["products"]["edges"]
+
+ assert len(variants) == count
diff --git a/saleor/graphql/product/tests/test_variant_with_filtering.py b/saleor/graphql/product/tests/test_variant_with_filtering.py
index dc988cc543..8bc9d30dea 100644
--- a/saleor/graphql/product/tests/test_variant_with_filtering.py
+++ b/saleor/graphql/product/tests/test_variant_with_filtering.py
@@ -2,6 +2,7 @@ from datetime import timedelta
import pytest
from django.utils import timezone
+from freezegun import freeze_time
from ....product.models import Product, ProductVariant
from ...tests.utils import get_graphql_content
@@ -185,3 +186,54 @@ def test_products_pagination_with_filtering(
if product_node["node"]["sku"] is None
]
)
+
+
+ "variants_filter, count",
+ [
+ ({"updatedAt": {"gte": "2012-01-14T10:59:00+00:00"}}, 2),
+ ({"updatedAt": {"lte": "2012-01-14T12:00:05+00:00"}}, 2),
+ ({"updatedAt": {"gte": "2012-01-14T11:59:00+00:00"}}, 1),
+ ({"updatedAt": {"lte": "2012-01-14T11:05:00+00:00"}}, 1),
+ ({"updatedAt": {"gte": "2012-01-14T12:01:00+00:00"}}, 0),
+ ({"updatedAt": {"lte": "2012-01-14T10:59:00+00:00"}}, 0),
+ (
+ {
+ "updatedAt": {
+ "lte": "2012-01-14T12:01:00+00:00",
+ "gte": "2012-01-14T11:59:00+00:00",
+ },
+ },
+ 1,
+ ),
+ ],
+)
+def test_product_variant_query_with_filter_updated_at(
+ variants_filter,
+ count,
+ product_type,
+ category,
+ staff_api_client,
+ permission_manage_products,
+):
+ product = Product.objects.create(
+ name="Product1",
+ slug="prod1",
+ category=category,
+ product_type=product_type,
+ )
+
+ with freeze_time("2012-01-14 11:00:00"):
+ ProductVariant.objects.create(product=product, sku="P1-V1")
+
+ with freeze_time("2012-01-14 12:00:00"):
+ ProductVariant.objects.create(product=product, sku="P1-V2")
+
+ variables = {"filter": variants_filter}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ response = staff_api_client.post_graphql(QUERY_VARIANTS_FILTER, variables)
+ content = get_graphql_content(response)
+ variants = content["data"]["productVariants"]["edges"]
+
+ assert len(variants) == count
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 68479c376b..c13cad9f85 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -321,6 +321,8 @@ class ProductVariant(ChannelContextTypeWithMetadata, ModelObjectType):
f"{ADDED_IN_31} Preorder data for product variant. {PREVIEW_FEATURE}"
),
)
+ created = graphene.DateTime(required=True)
+ updated_at = graphene.DateTime(required=True)
class Meta:
default_resolver = ChannelContextType.resolver_with_context
@@ -731,7 +733,8 @@ class Product(ChannelContextTypeWithMetadata, ModelObjectType):
product_type = graphene.Field(lambda: ProductType, required=True)
slug = graphene.String(required=True)
category = graphene.Field(lambda: Category)
- updated_at = graphene.DateTime()
+ created = graphene.DateTime(required=True)
+ updated_at = graphene.DateTime(required=True)
charge_taxes = graphene.Boolean(required=True)
weight = graphene.Field(Weight)
default_variant = graphene.Field(ProductVariant)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 30816781a6..d65de036a4 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1808,6 +1808,7 @@ input CustomerFilterInput {
placedOrders: DateRangeInput
search: String
metadata: [MetadataFilter]
+ updatedAt: DateTimeRangeInput
}
input CustomerInput {
@@ -4197,6 +4198,7 @@ type Order implements Node & ObjectWithMetadata {
privateMetadata: [MetadataItem]!
metadata: [MetadataItem]!
created: DateTime!
+ updatedAt: DateTime!
status: OrderStatus!
user: User
trackingClientId: String!
@@ -4519,6 +4521,7 @@ input OrderFilterInput {
search: String
metadata: [MetadataFilter]
channels: [ID]
+ updatedAt: DateTimeRangeInput
isClickAndCollect: Boolean
isPreorder: Boolean
ids: [ID]
@@ -5380,7 +5383,8 @@ type Product implements Node & ObjectWithMetadata {
productType: ProductType!
slug: String!
category: Category
- updatedAt: DateTime
+ created: DateTime!
+ updatedAt: DateTime!
chargeTaxes: Boolean!
weight: Weight
defaultVariant: ProductVariant
@@ -5584,6 +5588,7 @@ input ProductFilterInput {
metadata: [MetadataFilter]
price: PriceRangeInput
minimalPrice: PriceRangeInput
+ updatedAt: DateTimeRangeInput
productTypes: [ID]
giftCard: Boolean
ids: [ID]
@@ -5683,6 +5688,7 @@ enum ProductOrderField {
RANK
PRICE
MINIMAL_PRICE
+ LAST_MODIFIED
DATE
TYPE
PUBLISHED
@@ -5877,6 +5883,8 @@ type ProductVariant implements Node & ObjectWithMetadata {
stocks(address: AddressInput, countryCode: CountryCode): [Stock]
quantityAvailable(address: AddressInput, countryCode: CountryCode): Int
preorder: PreorderData
+ created: DateTime!
+ updatedAt: DateTime!
}
type ProductVariantBulkCreate {
@@ -5964,6 +5972,7 @@ input ProductVariantFilterInput {
sku: [String]
metadata: [MetadataFilter]
isPreorder: Boolean
+ updatedAt: DateTimeRangeInput
}
input ProductVariantInput {
@@ -6170,6 +6179,8 @@ type Sale implements Node & ObjectWithMetadata {
type: SaleType!
startDate: DateTime!
endDate: DateTime
+ created: DateTime!
+ updatedAt: DateTime!
categories(before: String, after: String, first: Int, last: Int): CategoryCountableConnection
collections(before: String, after: String, first: Int, last: Int): CollectionCountableConnection
products(before: String, after: String, first: Int, last: Int): ProductCountableConnection
@@ -6244,6 +6255,7 @@ input SaleFilterInput {
started: DateTimeRangeInput
search: String
metadata: [MetadataFilter]
+ updatedAt: DateTimeRangeInput
}
input SaleInput {
@@ -7020,6 +7032,7 @@ type User implements Node & ObjectWithMetadata {
defaultBillingAddress: Address
lastLogin: DateTime
dateJoined: DateTime!
+ updatedAt: DateTime!
}
type UserAvatarDelete {
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index b343d88252..7ba0384e74 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -165,7 +165,7 @@ def cancel_order(
events.order_canceled_event(order=order, user=user, app=app)
deallocate_stock_for_order(order, manager)
order.status = OrderStatus.CANCELED
- order.save(update_fields=["status"])
+ order.save(update_fields=["status", "updated_at"])
transaction.on_commit(lambda: manager.order_cancelled(order))
transaction.on_commit(lambda: manager.order_updated(order))
diff --git a/saleor/order/migrations/0124_order_updated_at.py b/saleor/order/migrations/0124_order_updated_at.py
new file mode 100644
index 0000000000..931361c9ce
--- /dev/null
+++ b/saleor/order/migrations/0124_order_updated_at.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.2.12 on 2022-02-09 13:57
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0123_update_order_search_document"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="order",
+ name="updated_at",
+ field=models.DateTimeField(db_index=True, null=True),
+ ),
+ ]
diff --git a/saleor/order/migrations/0125_populate_order_updated_at.py b/saleor/order/migrations/0125_populate_order_updated_at.py
new file mode 100644
index 0000000000..7e6e6eca4d
--- /dev/null
+++ b/saleor/order/migrations/0125_populate_order_updated_at.py
@@ -0,0 +1,34 @@
+# Generated by Django 3.2.12 on 2022-02-09 13:58
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("order", "0124_order_updated_at"),
+ ]
+
+ operations = [
+ migrations.RunSQL(
+ """
+ UPDATE order_order
+ SET updated_at = (
+ SELECT MAX (order_orderevent.date)
+ FROM order_orderevent
+ WHERE order_orderevent.order_id = order_order.id
+ )
+ WHERE updated_at IS NULL;
+ """,
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ migrations.RunSQL(
+ """
+ UPDATE order_order
+ SET updated_at = created
+ WHERE updated_at IS NULL;
+ """,
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/order/migrations/0126_alter_order_updated_at.py b/saleor/order/migrations/0126_alter_order_updated_at.py
new file mode 100644
index 0000000000..f4d1c0faa2
--- /dev/null
+++ b/saleor/order/migrations/0126_alter_order_updated_at.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.2.12 on 2022-02-09 14:02
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0125_populate_order_updated_at"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="order",
+ name="updated_at",
+ field=models.DateTimeField(auto_now=True, db_index=True),
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 7e779bdee7..4382695b07 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -84,6 +84,7 @@ class OrderQueryset(models.QuerySet):
class Order(ModelWithMetadata):
created = models.DateTimeField(default=now, editable=False)
+ updated_at = models.DateTimeField(auto_now=True, editable=False, db_index=True)
status = models.CharField(
max_length=32, default=OrderStatus.UNFULFILLED, choices=OrderStatus.CHOICES
)
@@ -287,7 +288,7 @@ class Order(ModelWithMetadata):
self.total_paid_amount = (
sum(self.payments.values_list("captured_amount", flat=True)) or 0
)
- self.save(update_fields=["total_paid_amount"])
+ self.save(update_fields=["total_paid_amount", "updated_at"])
def _index_billing_phone(self):
return self.billing_address.phone
diff --git a/saleor/order/search.py b/saleor/order/search.py
index 546fd01d50..6d2a4ea599 100644
--- a/saleor/order/search.py
+++ b/saleor/order/search.py
@@ -14,7 +14,7 @@ if TYPE_CHECKING:
def update_order_search_document(order: "Order"):
order.search_document = prepare_order_search_document_value(order)
- order.save(update_fields=["search_document"])
+ order.save(update_fields=["search_document", "updated_at"])
def prepare_order_search_document_value(order: "Order", *, already_prefetched=False):
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index b6a35263c3..75b81d2696 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -183,6 +183,7 @@ def recalculate_order(order: Order, **kwargs):
"undiscounted_total_net_amount",
"undiscounted_total_gross_amount",
"currency",
+ "updated_at",
]
)
recalculate_order_weight(order)
@@ -195,7 +196,7 @@ def recalculate_order_weight(order):
if line.variant:
weight += line.variant.get_weight() * line.quantity
order.weight = weight
- order.save(update_fields=["weight"])
+ order.save(update_fields=["weight", "updated_at"])
def update_taxes_for_order_line(
@@ -259,6 +260,7 @@ def update_order_prices(order: Order, manager: "PluginsManager", tax_included: b
"shipping_price_gross_amount",
"shipping_tax_rate",
"currency",
+ "updated_at",
]
)
@@ -319,7 +321,7 @@ def update_order_status(order):
if status != order.status:
order.status = status
- order.save(update_fields=["status"])
+ order.save(update_fields=["status", "updated_at"])
@traced_atomic_transaction()
@@ -850,7 +852,7 @@ def create_order_discount_for_order(
amount=new_amount, # type: ignore
)
order.total = TaxedMoney(net_total, gross_total)
- order.save(update_fields=["total_net_amount", "total_gross_amount"])
+ order.save(update_fields=["total_net_amount", "total_gross_amount", "updated_at"])
return order_discount
@@ -897,7 +899,7 @@ def remove_order_discount_from_order(order: Order, order_discount: OrderDiscount
order_discount.delete()
order.total += discount_amount
- order.save(update_fields=["total_net_amount", "total_gross_amount"])
+ order.save(update_fields=["total_net_amount", "total_gross_amount", "updated_at"])
def update_discount_for_order_line(
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 1bdaf6c0e7..2a9e5ada9f 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -486,7 +486,7 @@ def store_customer_id(user: User, gateway: str, customer_id: str):
"""Store customer_id in users private meta for desired gateway."""
meta_key = prepare_key_for_gateway_customer_id(gateway)
user.store_value_in_private_metadata(items={meta_key: customer_id})
- user.save(update_fields=["private_metadata"])
+ user.save(update_fields=["private_metadata", "updated_at"])
def prepare_key_for_gateway_customer_id(gateway_name: str) -> str:
diff --git a/saleor/product/migrations/0159_auto_20220209_1501.py b/saleor/product/migrations/0159_auto_20220209_1501.py
new file mode 100644
index 0000000000..6dbeff2571
--- /dev/null
+++ b/saleor/product/migrations/0159_auto_20220209_1501.py
@@ -0,0 +1,33 @@
+# Generated by Django 3.2.12 on 2022-02-09 15:01
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0158_auto_20220120_1633"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="product",
+ name="created",
+ field=models.DateTimeField(db_index=True, null=True),
+ ),
+ migrations.AlterField(
+ model_name="product",
+ name="updated_at",
+ field=models.DateTimeField(db_index=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="productvariant",
+ name="created",
+ field=models.DateTimeField(db_index=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="productvariant",
+ name="updated_at",
+ field=models.DateTimeField(db_index=True, null=True),
+ ),
+ ]
diff --git a/saleor/product/migrations/0160_populate_product_datetimes.py b/saleor/product/migrations/0160_populate_product_datetimes.py
new file mode 100644
index 0000000000..1606ebb56a
--- /dev/null
+++ b/saleor/product/migrations/0160_populate_product_datetimes.py
@@ -0,0 +1,31 @@
+# Generated by Django 3.2.12 on 2022-02-09 15:03
+
+from django.db import migrations
+from django.db.models import F
+from django.utils import timezone
+
+
+def populate_products_datetimes(apps, _schema_editor):
+ Product = apps.get_model("product", "Product")
+
+ Product.objects.filter(updated_at__isnull=False).update(created=F("updated_at"))
+ Product.objects.filter(created__isnull=True).update(created=timezone.now())
+ Product.objects.filter(updated_at__isnull=True).update(updated_at=timezone.now())
+
+ ProductVariant = apps.get_model("product", "ProductVariant")
+ ProductVariant.objects.update(created=timezone.now(), updated_at=timezone.now())
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("product", "0159_auto_20220209_1501"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ populate_products_datetimes,
+ migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/product/migrations/0161_auto_20220209_1511.py b/saleor/product/migrations/0161_auto_20220209_1511.py
new file mode 100644
index 0000000000..e556663594
--- /dev/null
+++ b/saleor/product/migrations/0161_auto_20220209_1511.py
@@ -0,0 +1,33 @@
+# Generated by Django 3.2.12 on 2022-02-09 15:11
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0160_populate_product_datetimes"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="product",
+ name="created",
+ field=models.DateTimeField(auto_now_add=True, db_index=True),
+ ),
+ migrations.AlterField(
+ model_name="product",
+ name="updated_at",
+ field=models.DateTimeField(auto_now=True, db_index=True),
+ ),
+ migrations.AlterField(
+ model_name="productvariant",
+ name="created",
+ field=models.DateTimeField(auto_now_add=True, db_index=True),
+ ),
+ migrations.AlterField(
+ model_name="productvariant",
+ name="updated_at",
+ field=models.DateTimeField(auto_now=True, db_index=True),
+ ),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 660668f3bf..12f5133404 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -402,7 +402,8 @@ class Product(SeoModel, ModelWithMetadata):
null=True,
blank=True,
)
- updated_at = models.DateTimeField(auto_now=True, null=True)
+ created = models.DateTimeField(auto_now_add=True, db_index=True)
+ updated_at = models.DateTimeField(auto_now=True, db_index=True)
charge_taxes = models.BooleanField(default=True)
weight = MeasurementField(
measurement=Weight,
@@ -581,6 +582,8 @@ class ProductVariant(SortableModel, ModelWithMetadata):
quantity_limit_per_customer = models.IntegerField(
blank=True, null=True, validators=[MinValueValidator(1)]
)
+ created = models.DateTimeField(auto_now_add=True, db_index=True)
+ updated_at = models.DateTimeField(auto_now=True, db_index=True)
weight = MeasurementField(
measurement=Weight,
diff --git a/saleor/product/search.py b/saleor/product/search.py
index 569ac7040f..f41a39d9d9 100644
--- a/saleor/product/search.py
+++ b/saleor/product/search.py
@@ -29,12 +29,12 @@ def update_products_search_document(products: "QuerySet"):
product, already_prefetched=True
)
- Product.objects.bulk_update(products, ["search_document"])
+ Product.objects.bulk_update(products, ["search_document", "updated_at"])
def update_product_search_document(product: "Product"):
product.search_document = prepare_product_search_document_value(product)
- product.save(update_fields=["search_document"])
+ product.save(update_fields=["search_document", "updated_at"])
def prepare_product_search_document_value(
diff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.py
index 36cc1b11d2..aeba20a898 100644
--- a/saleor/product/utils/variants.py
+++ b/saleor/product/utils/variants.py
@@ -27,7 +27,7 @@ def generate_and_set_variant_name(variant: "ProductVariant", sku: Optional[str])
name = sku or variant.get_global_id()
variant.name = name
- variant.save(update_fields=["name"])
+ variant.save(update_fields=["name", "updated_at"])
def get_variant_selection_attributes(
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index c537d0887f..ccb179e30d 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -723,7 +723,12 @@ def deactivate_preorder_for_variant(product_variant: ProductVariant):
product_variant.preorder_end_date = None
product_variant.is_preorder = False
product_variant.save(
- update_fields=["preorder_global_threshold", "preorder_end_date", "is_preorder"]
+ update_fields=[
+ "preorder_global_threshold",
+ "preorder_end_date",
+ "is_preorder",
+ "updated_at",
+ ]
)
ProductVariantChannelListing.objects.filter(variant_id=product_variant.pk).update(