Skip to content

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

Add updatedAt and filter for categories (#13697) (#13825)

Rafał Krupiński029c415b6bae
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0e0c477aa7..97850b88a8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Fix thumbnail redirects sometimes failing with an unsafe redirect warning - #14023 by @patrys
- New environment variable `PUBLIC_URL` to define URL on which Saleor is hosted (e.g., https://api.example.com/). Takes precedence over `ENABLE_SSL` and `Shop.domain` for URL generation - #13841 by @przlada
+- Add a new `updatedAt` field and a filter for product categories. - #13825 by @rafiwts
# 3.16.0
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index 71578d4070..fa64bf6415 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -36,7 +36,7 @@ from ...product.models import (
from ...product.search import search_products
from ...warehouse.models import Allocation, Reservation, Stock, Warehouse
from ..channel.filters import get_channel_slug_from_filter_data
-from ..core.descriptions import ADDED_IN_38
+from ..core.descriptions import ADDED_IN_38, ADDED_IN_317
from ..core.doc_category import DOC_CATEGORY_PRODUCTS
from ..core.filters import (
BooleanWhereFilter,
@@ -1258,6 +1258,11 @@ class CategoryFilter(MetadataFilterBase):
search = django_filters.CharFilter(method="category_filter_search")
ids = GlobalIDMultipleChoiceFilter(field_name="id")
slugs = ListObjectTypeFilter(input_class=graphene.String, method=filter_slug_list)
+ updated_at = ObjectTypeFilter(
+ input_class=DateTimeRangeInput,
+ method=filter_updated_at_range,
+ help_text=f"Filter by when was the most recent update. {ADDED_IN_317}",
+ )
class Meta:
model = Category
diff --git a/saleor/graphql/product/tests/test_category.py b/saleor/graphql/product/tests/test_category.py
index f195eed98c..6102e9da19 100644
--- a/saleor/graphql/product/tests/test_category.py
+++ b/saleor/graphql/product/tests/test_category.py
@@ -5,6 +5,7 @@ from unittest.mock import MagicMock, Mock, patch
import graphene
import pytest
from django.core.files import File
+from django.utils import timezone
from django.utils.functional import SimpleLazyObject
from django.utils.text import slugify
from freezegun import freeze_time
@@ -610,6 +611,7 @@ MUTATION_CATEGORY_UPDATE_MUTATION = """
id
name
description
+ updatedAt
parent {
id
}
@@ -689,6 +691,45 @@ def test_category_update_mutation(
assert category.private_metadata == {metadata_key: metadata_value, **old_meta}
+@freeze_time("2023-09-01 12:00:00")
+def test_category_update_mutation_with_update_at_field(
+ monkeypatch, staff_api_client, category, permission_manage_products, media_root
+):
+ # given
+ query = MUTATION_CATEGORY_UPDATE_MUTATION
+
+ # create child category and test that the update mutation won't change
+ # it's parent
+ child_category = category.children.create(name="child")
+
+ category_name = "Updated name"
+ description = "description"
+ category_slug = slugify(category_name)
+ category_description = dummy_editorjs(description, True)
+
+ category_id = graphene.Node.to_global_id("Category", child_category.pk)
+ variables = {
+ "name": category_name,
+ "description": category_description,
+ "id": category_id,
+ "slug": category_slug,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["categoryUpdate"]
+
+ # then
+ assert data["category"]["id"] == category_id
+ assert data["category"]["name"] == category_name
+ assert data["category"]["description"] == category_description
+ assert data["category"]["updatedAt"] == timezone.now().isoformat()
+
+
@freeze_time("2022-05-12 12:00:00")
@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
diff --git a/saleor/graphql/product/tests/test_category_filtering.py b/saleor/graphql/product/tests/test_category_filtering.py
index 3a0e88cccd..ca1651fb57 100644
--- a/saleor/graphql/product/tests/test_category_filtering.py
+++ b/saleor/graphql/product/tests/test_category_filtering.py
@@ -1,5 +1,6 @@
import graphene
import pytest
+from freezegun import freeze_time
from ....product.models import (
Category,
@@ -75,6 +76,86 @@ def test_categories_with_filtering(
assert len(categories_nodes) == categories_count
+ "filter_by, categories_count",
+ [
+ ({"updatedAt": {"gte": "2012-01-14T10:59:00+00:00"}}, 3),
+ ({"updatedAt": {"lte": "2012-01-14T12:00:05+00:00"}}, 3),
+ ({"updatedAt": {"gte": "2012-01-14T11:29:00+00:00"}}, 2),
+ ({"updatedAt": {"lte": "2012-01-14T11:31:00+00:00"}}, 2),
+ ({"updatedAt": {"gte": "2012-01-14T12:01:00+00:00"}}, 0),
+ ({"updatedAt": {"lte": "2012-01-14T10:59:00+00:00"}}, 0),
+ ({"updatedAt": {}}, 3),
+ (
+ {
+ "updatedAt": {
+ "lte": "2012-01-14T12:01:00+00:00",
+ "gte": "2012-01-14T11:59:00+00:00",
+ },
+ },
+ 1,
+ ),
+ (
+ {
+ "updatedAt": {
+ "lte": "2012-01-14T12:01:00+00:00",
+ "gte": "2012-01-14T11:29:00+00:00",
+ },
+ },
+ 2,
+ ),
+ ],
+)
+def test_order_query_with_filter_updated_at(
+ filter_by,
+ categories_count,
+ staff_api_client,
+):
+ # given
+ with freeze_time("2012-01-14 11:00:00"):
+ Category.objects.create(
+ name="Category1",
+ slug="category1",
+ lft=0,
+ rght=0,
+ tree_id=2,
+ level=0,
+ )
+
+ with freeze_time("2012-01-14 11:30:00"):
+ Category.objects.create(
+ name="Category2",
+ slug="category2",
+ lft=1,
+ rght=2,
+ tree_id=1,
+ level=0,
+ )
+
+ with freeze_time("2012-01-14 12:00:00"):
+ Category.objects.create(
+ name="Category3",
+ slug="category3",
+ lft=1,
+ rght=2,
+ tree_id=2,
+ level=0,
+ )
+
+ variables = {"filter": filter_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_CATEGORIES_WITH_FILTERING,
+ variables,
+ )
+
+ content = get_graphql_content(response)
+ categories_nodes = content["data"]["categories"]["edges"]
+ # then
+ assert len(categories_nodes) == categories_count
+
+
GET_FILTERED_PRODUCTS_CATEGORY_QUERY = """
query ($id: ID!, $channel: String, $filters: ProductFilterInput) {
category(id: $id) {
diff --git a/saleor/graphql/product/types/categories.py b/saleor/graphql/product/types/categories.py
index dd4e35556c..f28a361963 100644
--- a/saleor/graphql/product/types/categories.py
+++ b/saleor/graphql/product/types/categories.py
@@ -22,6 +22,7 @@ from ...core.context import get_database_connection_name
from ...core.descriptions import (
ADDED_IN_310,
ADDED_IN_314,
+ ADDED_IN_317,
DEPRECATED_IN_3X_FIELD,
PREVIEW_FEATURE,
RICH_CONTENT,
@@ -60,6 +61,11 @@ class Category(ModelObjectType[models.Category]):
f"{DEPRECATED_IN_3X_FIELD} Use the `description` field instead."
),
)
+ updated_at = graphene.DateTime(
+ required=True,
+ description="The date and time when the category was last updated."
+ + ADDED_IN_317,
+ )
ancestors = ConnectionField(
lambda: CategoryCountableConnection,
description="List of ancestors of the category.",
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index b08ffbeebb..3bad139873 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -6670,6 +6670,13 @@ type Category implements Node & ObjectWithMetadata @doc(category: "Products") {
"""
descriptionJson: JSONString @deprecated(reason: "This field will be removed in Saleor 4.0. Use the `description` field instead.")
+ """
+ The date and time when the category was last updated.
+
+ Added in Saleor 3.17.
+ """
+ updatedAt: DateTime!
+
"""List of ancestors of the category."""
ancestors(
"""Return the elements in the list that come before the specified cursor."""
@@ -12796,6 +12803,13 @@ input CategoryFilterInput @doc(category: "Products") {
metadata: [MetadataFilter!]
ids: [ID!]
slugs: [String!]
+
+ """
+ Filter by when was the most recent update.
+
+ Added in Saleor 3.17.
+ """
+ updatedAt: DateTimeRangeInput
}
input CategoryWhereInput @doc(category: "Products") {
diff --git a/saleor/product/migrations/0187_category_updated_at.py b/saleor/product/migrations/0187_category_updated_at.py
new file mode 100644
index 0000000000..4898af7b2f
--- /dev/null
+++ b/saleor/product/migrations/0187_category_updated_at.py
@@ -0,0 +1,25 @@
+# Generated by Django 3.2.20 on 2023-09-27 06:26
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("product", "0186_remove_product_charge_taxes"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="category",
+ name="updated_at",
+ field=models.DateTimeField(auto_now=True, null=True),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE product_category
+ ALTER COLUMN updated_at
+ SET DEFAULT NOW();
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/product/migrations/0188_category_updated_at_idx.py b/saleor/product/migrations/0188_category_updated_at_idx.py
new file mode 100644
index 0000000000..8f310516ed
--- /dev/null
+++ b/saleor/product/migrations/0188_category_updated_at_idx.py
@@ -0,0 +1,22 @@
+# Generated by Django 3.2.20 on 2023-09-27 06:31
+
+import django.contrib.postgres.indexes
+from django.db import migrations
+from django.contrib.postgres.operations import AddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("product", "0187_category_updated_at"),
+ ]
+
+ operations = [
+ AddIndexConcurrently(
+ model_name="category",
+ index=django.contrib.postgres.indexes.BTreeIndex(
+ fields=["updated_at"], name="updated_at_idx"
+ ),
+ ),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 8bb389fa35..6db0e8af4f 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -62,6 +62,7 @@ class Category(ModelWithMetadata, MPTTModel, SeoModel):
slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)
description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
description_plaintext = TextField(blank=True)
+ updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
parent = models.ForeignKey(
"self", null=True, blank=True, related_name="children", on_delete=models.CASCADE
)
@@ -82,6 +83,7 @@ class Category(ModelWithMetadata, MPTTModel, SeoModel):
fields=["name", "slug", "description_plaintext"],
opclasses=["gin_trgm_ops"] * 3,
),
+ BTreeIndex(fields=["updated_at"], name="updated_at_idx"),
]
def __str__(self) -> str: