Skip to content

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

Add externalReference support to Category (#19869)

DamianCzajkowskiecb6cdc7ff1b
diff --git a/saleor/graphql/product/mutations/category/category_create.py b/saleor/graphql/product/mutations/category/category_create.py
index 407bed09f6..aaead2fe58 100644
--- a/saleor/graphql/product/mutations/category/category_create.py
+++ b/saleor/graphql/product/mutations/category/category_create.py
@@ -8,7 +8,7 @@ from .....product import models
from .....product.error_codes import ProductErrorCode
from .....product.lock_objects import acquire_category_tree_lock
from ....core import ResolveInfo
-from ....core.descriptions import RICH_CONTENT
+from ....core.descriptions import ADDED_IN_323, RICH_CONTENT
from ....core.doc_category import DOC_CATEGORY_PRODUCTS
from ....core.fields import JSONString
from ....core.mutations import DeprecatedModelMutation
@@ -30,6 +30,10 @@ class CategoryInput(BaseInputObjectType):
description = JSONString(description="Category description." + RICH_CONTENT)
name = graphene.String(description="Category name.")
slug = graphene.String(description="Category slug.")
+ external_reference = graphene.String(
+ description=f"External ID of this category.{ADDED_IN_323}",
+ required=False,
+ )
seo = SeoInput(description="Search engine optimization fields.")
background_image = Upload(description="Background image file.")
background_image_alt = graphene.String(description="Alt text for a product media.")
diff --git a/saleor/graphql/product/mutations/category/category_delete.py b/saleor/graphql/product/mutations/category/category_delete.py
index 01e3ad70ea..171f9d6e37 100644
--- a/saleor/graphql/product/mutations/category/category_delete.py
+++ b/saleor/graphql/product/mutations/category/category_delete.py
@@ -4,15 +4,20 @@ from .....permission.enums import ProductPermissions
from .....product import models
from .....product.utils import delete_categories
from ....core import ResolveInfo
-from ....core.mutations import ModelDeleteMutation
+from ....core.descriptions import ADDED_IN_323
+from ....core.mutations import ModelDeleteMutation, ModelWithExtRefMutation
from ....core.types import ProductError
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import Category
-class CategoryDelete(ModelDeleteMutation):
+class CategoryDelete(ModelDeleteMutation, ModelWithExtRefMutation):
class Arguments:
- id = graphene.ID(required=True, description="ID of a category to delete.")
+ id = graphene.ID(required=False, description="ID of a category to delete.")
+ external_reference = graphene.String(
+ required=False,
+ description=f"External ID of a category to delete.{ADDED_IN_323}",
+ )
class Meta:
description = "Deletes a category."
@@ -24,9 +29,9 @@ class CategoryDelete(ModelDeleteMutation):
@classmethod
def perform_mutation( # type: ignore[override]
- cls, _root, info: ResolveInfo, /, *, id: str
+ cls, _root, info: ResolveInfo, /, *, external_reference=None, id=None
):
- instance = cls.get_node_or_error(info, id, only_type=Category)
+ instance = cls.get_instance(info, external_reference=external_reference, id=id)
db_id = instance.id
manager = get_plugin_manager_promise(info.context).get()
diff --git a/saleor/graphql/product/mutations/category/category_update.py b/saleor/graphql/product/mutations/category/category_update.py
index 0deab54372..25644de646 100644
--- a/saleor/graphql/product/mutations/category/category_update.py
+++ b/saleor/graphql/product/mutations/category/category_update.py
@@ -6,15 +6,21 @@ from .....permission.enums import ProductPermissions
from .....product import models
from .....thumbnail import models as thumbnail_models
from ....core import ResolveInfo
+from ....core.descriptions import ADDED_IN_323
+from ....core.mutations import ModelWithExtRefMutation
from ....core.types import ProductError
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import Category
from .category_create import CategoryCreate, CategoryInput
-class CategoryUpdate(CategoryCreate):
+class CategoryUpdate(CategoryCreate, ModelWithExtRefMutation):
class Arguments:
- id = graphene.ID(required=True, description="ID of a category to update.")
+ id = graphene.ID(required=False, description="ID of a category to update.")
+ external_reference = graphene.String(
+ required=False,
+ description=f"External ID of a category to update.{ADDED_IN_323}",
+ )
input = CategoryInput(
required=True, description="Fields required to update a category."
)
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index d5319a995a..27dfb3fdbc 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -47,6 +47,14 @@ def resolve_category_by_translated_slug(info: ResolveInfo, slug, slug_language_c
)
+def resolve_category_by_external_reference(info: ResolveInfo, external_reference):
+ return (
+ models.Category.objects.using(get_database_connection_name(info.context))
+ .filter(external_reference=external_reference)
+ .first()
+ )
+
+
def resolve_collection_by_id(info: ResolveInfo, id, channel_slug, requestor):
return (
models.Collection.objects.using(get_database_connection_name(info.context))
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 0861345b9a..a64d91c644 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -14,6 +14,7 @@ from ..core.connection import create_connection_slice, filter_connection_queryse
from ..core.context import ChannelContext, ChannelQsContext
from ..core.descriptions import (
ADDED_IN_322,
+ ADDED_IN_323,
DEFAULT_DEPRECATION_REASON,
DEPRECATED_IN_3X_INPUT,
)
@@ -102,6 +103,7 @@ from .mutations.channels import (
)
from .resolvers import (
resolve_categories,
+ resolve_category_by_external_reference,
resolve_category_by_translated_slug,
resolve_collection_by_id,
resolve_collection_by_slug,
@@ -158,7 +160,15 @@ class ProductQueries(graphene.ObjectType):
LanguageCodeEnum,
description="Language code of the category slug, omit to use primary slug.",
),
- description="Look up a category by ID or slug.",
+ external_reference=graphene.Argument(
+ graphene.String,
+ description=f"External ID of the category.{ADDED_IN_323}",
+ ),
+ description=(
+ "Look up a category by ID, slug or external reference. If "
+ "slugLanguageCode is provided, category will be fetched by slug "
+ "translation."
+ ),
doc_category=DOC_CATEGORY_PRODUCTS,
)
collection = BaseField(
@@ -343,15 +353,20 @@ class ProductQueries(graphene.ObjectType):
id=None,
slug=None,
slug_language_code=None,
+ external_reference=None,
**kwargs,
) -> Promise[Category] | None | Category:
- validate_one_of_args_is_in_query("id", id, "slug", slug)
+ validate_one_of_args_is_in_query(
+ "id", id, "slug", slug, "external_reference", external_reference
+ )
if id:
_, id = from_global_id_or_error(id, Category)
# FIXME: we should raise an error above
if id is not None:
return CategoryByIdLoader(info.context).load(int(id))
return None
+ if external_reference:
+ return resolve_category_by_external_reference(info, external_reference)
if slug:
if slug_language_code:
return resolve_category_by_translated_slug(
diff --git a/saleor/graphql/product/tests/mutations/test_category_create.py b/saleor/graphql/product/tests/mutations/test_category_create.py
index aa90753644..ef5f3d33ec 100644
--- a/saleor/graphql/product/tests/mutations/test_category_create.py
+++ b/saleor/graphql/product/tests/mutations/test_category_create.py
@@ -17,7 +17,9 @@ from .....tests.utils import dummy_editorjs
from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.payloads import generate_meta, generate_requestor
from ....tests.utils import (
+ assert_no_permission,
get_graphql_content,
+ get_graphql_content_from_response,
get_multipart_request_body,
)
@@ -70,6 +72,177 @@ CATEGORY_CREATE_MUTATION = """
"""
+CREATE_CATEGORY_WITH_EXTERNAL_REFERENCE_MUTATION = """
+ mutation createCategory($name: String!, $externalReference: String) {
+ categoryCreate(
+ input: {name: $name, externalReference: $externalReference}
+ ) {
+ category {
+ name
+ externalReference
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
+def test_create_category_with_external_reference(
+ staff_api_client, permission_manage_products
+):
+ # given
+ name = "test-category"
+ external_reference = "test-ext-ref"
+ variables = {"name": name, "externalReference": external_reference}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_CATEGORY_WITH_EXTERNAL_REFERENCE_MUTATION,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["categoryCreate"]
+ assert data["errors"] == []
+ assert data["category"]["externalReference"] == external_reference
+ category = Category.objects.get(name=name)
+ assert category.external_reference == external_reference
+
+
+def test_create_category_with_non_unique_external_reference(
+ staff_api_client, category, permission_manage_products
+):
+ # given
+ external_reference = "test-ext-ref"
+ category.external_reference = external_reference
+ category.save(update_fields=["external_reference"])
+
+ name = "new-category"
+ variables = {"name": name, "externalReference": external_reference}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_CATEGORY_WITH_EXTERNAL_REFERENCE_MUTATION,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["categoryCreate"]
+ assert data["category"] is None
+ assert Category.objects.filter(name=name).exists() is False
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert (
+ errors[0]["message"] == "Category with this External reference already exists."
+ )
+ assert errors[0]["field"] == "externalReference"
+ assert errors[0]["code"] == ProductErrorCode.UNIQUE.name
+
+
+ ("_case", "client_fixture", "is_allowed"),
+ [
+ ("anonymous", "api_client", False),
+ ("customer", "user_api_client", False),
+ ("staff_without_permission", "staff_api_client", False),
+ ("staff_with_permission", "staff_api_client", True),
+ ("app_without_permission", "app_api_client", False),
+ ("app_with_permission", "app_api_client", True),
+ ],
+)
+def test_external_reference_authorization(
+ _case,
+ client_fixture,
+ is_allowed,
+ request,
+ category,
+ permission_manage_products,
+ mocker,
+):
+ # given
+ client = request.getfixturevalue(client_fixture)
+ category.external_reference = "existing-reference"
+ category.save(update_fields=("external_reference",))
+ original_name = category.name
+ original_reference = category.external_reference
+ name = "Changed category"
+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.category_created")
+ variables = {"name": name, "externalReference": "new-reference"}
+
+ # when
+ response = client.post_graphql(
+ CREATE_CATEGORY_WITH_EXTERNAL_REFERENCE_MUTATION,
+ variables,
+ permissions=[permission_manage_products] if is_allowed else [],
+ check_no_permissions=False,
+ )
+
+ # then
+ if is_allowed:
+ data = get_graphql_content(response)["data"]["categoryCreate"]
+ assert data["errors"] == []
+ created = Category.objects.get(external_reference="new-reference")
+ assert created.name == name
+ assert data["category"] == {
+ "name": name,
+ "externalReference": created.external_reference,
+ }
+ webhook.assert_called_once()
+ else:
+ assert_no_permission(response)
+ content = get_graphql_content_from_response(response)
+ assert content["data"] == {"categoryCreate": None}
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["path"] == ["categoryCreate"]
+ assert content["errors"][0]["message"] == (
+ "To access this path, you need one of the following permissions: MANAGE_PRODUCTS"
+ )
+ category.refresh_from_db(fields=("name", "external_reference"))
+ assert category.name == original_name
+ assert category.external_reference == original_reference
+ assert Category.objects.filter(name=name).exists() is False
+ webhook.assert_not_called()
+
+
+ ("_case", "reference_input"),
+ [("omitted", {}), ("null", {"externalReference": None})],
+)
+def test_without_external_reference(
+ _case,
+ reference_input,
+ staff_api_client,
+ category,
+ permission_manage_products,
+):
+ # given
+ assert category.external_reference is None
+ name = "Category without reference"
+ variables = {"name": name, **reference_input}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_CATEGORY_WITH_EXTERNAL_REFERENCE_MUTATION,
+ variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["categoryCreate"]
+ assert data["errors"] == []
+ assert data["category"] == {"name": name, "externalReference": None}
+ created = Category.objects.get(name=name)
+ assert created.external_reference is None
+
+
def test_category_create_mutation(
monkeypatch, staff_api_client, permission_manage_products, media_root
):
diff --git a/saleor/graphql/product/tests/mutations/test_category_delete.py b/saleor/graphql/product/tests/mutations/test_category_delete.py
index 77a707a623..709da271de 100644
--- a/saleor/graphql/product/tests/mutations/test_category_delete.py
+++ b/saleor/graphql/product/tests/mutations/test_category_delete.py
@@ -12,12 +12,15 @@ from .....attribute.utils import associate_attribute_values_to_instance
from .....core.db.locks import AdvisoryLock
from .....core.utils.json_serializer import CustomJsonEncoder
from .....discount.utils.promotion import get_active_catalogue_promotion_rules
+from .....product.error_codes import ProductErrorCode
from .....product.models import Category, ProductChannelListing
from .....thumbnail.models import Thumbnail
from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.payloads import generate_meta, generate_requestor
from ....tests.utils import (
+ assert_no_permission,
get_graphql_content,
+ get_graphql_content_from_response,
)
MUTATION_CATEGORY_DELETE = """
@@ -34,6 +37,193 @@ MUTATION_CATEGORY_DELETE = """
}
"""
+DELETE_CATEGORY_BY_EXTERNAL_REFERENCE_MUTATION = """
+ mutation deleteCategory($id: ID, $externalReference: String) {
+ categoryDelete(id: $id, externalReference: $externalReference) {
+ category {
+ name
+ externalReference
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
+def test_delete_category_by_external_reference(
+ staff_api_client, category, permission_manage_products
+):
+ # given
+ external_reference = "test-ext-ref"
+ category.external_reference = external_reference
+ category.save(update_fields=["external_reference"])
+ variables = {"externalReference": external_reference}
+
+ # when
+ response = staff_api_client.post_graphql(
+ DELETE_CATEGORY_BY_EXTERNAL_REFERENCE_MUTATION,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["categoryDelete"]
+ assert data["errors"] == []
+ assert data["category"]["name"] == category.name
+ assert data["category"]["externalReference"] == external_reference
+ assert Category.objects.filter(pk=category.pk).exists() is False
+
+
+ ("_case", "identifiers", "error_field", "error_code", "message"),
+ [
+ (
+ "omitted",
+ {},
+ None,
+ ProductErrorCode.GRAPHQL_ERROR,
+ "At least one of arguments is required: 'id', 'external_reference'.",
+ ),
+ (
+ "null",
+ {"id": None, "externalReference": None},
+ None,
+ ProductErrorCode.GRAPHQL_ERROR,
+ "At least one of arguments is required: 'id', 'external_reference'.",
+ ),
+ (
+ "empty",
+ {"externalReference": ""},
+ None,
+ ProductErrorCode.GRAPHQL_ERROR,
+ "At least one of arguments is required: 'id', 'external_reference'.",
+ ),
+ (
+ "both",
+ {"externalReference": "existing-reference"},
+ None,
+ ProductErrorCode.GRAPHQL_ERROR,
+ "Argument 'id' cannot be combined with 'external_reference'",
+ ),
+ (
+ "not_found",
+ {"externalReference": "missing-reference"},
+ "externalReference",
+ ProductErrorCode.NOT_FOUND,
+ "Couldn't resolve to a node: missing-reference",
+ ),
+ ],
+)
+def test_external_reference_invalid_identifiers(
+ _case,
+ identifiers,
+ error_field,
+ error_code,
+ message,
+ staff_api_client,
+ category,
+ permission_manage_products,
+ mocker,
+):
+ # given
+ category.external_reference = "existing-reference"
+ category.save(update_fields=("external_reference",))
+ original_name = category.name
+ original_reference = category.external_reference
+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.category_deleted")
+ variables = dict(identifiers)
+ if _case == "both":
+ variables["id"] = graphene.Node.to_global_id("Category", category.pk)
+
+ # when
+ response = staff_api_client.post_graphql(
+ DELETE_CATEGORY_BY_EXTERNAL_REFERENCE_MUTATION,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["categoryDelete"]
+ assert data["category"] is None
+ assert len(data["errors"]) == 1
+ assert data["errors"][0] == {
+ "field": error_field,
+ "code": error_code.name,
+ "message": message,
+ }
+ category.refresh_from_db(fields=("name", "external_reference"))
+ assert category.name == original_name
+ assert category.external_reference == original_reference
+ webhook.assert_not_called()
+
+
+ ("_case", "client_fixture", "is_allowed"),
+ [
+ ("anonymous", "api_client", False),
+ ("customer", "user_api_client", False),
+ ("staff_without_permission", "staff_api_client", False),
+ ("staff_with_permission", "staff_api_client", True),
+ ("app_without_permission", "app_api_client", False),
+ ("app_with_permission", "app_api_client", True),
+ ],
+)
+def test_external_reference_authorization(
+ _case,
+ client_fixture,
+ is_allowed,
+ request,
+ category,
+ permission_manage_products,
+ mocker,
+):
+ # given
+ client = request.getfixturevalue(client_fixture)
+ category.external_reference = "existing-reference"
+ category.save(update_fields=("external_reference",))
+ original_name = category.name
+ original_reference = category.external_reference
+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.category_deleted")
+ variables = {"externalReference": original_reference}
+
+ # when
+ response = client.post_graphql(
+ DELETE_CATEGORY_BY_EXTERNAL_REFERENCE_MUTATION,
+ variables,
+ permissions=[permission_manage_products] if is_allowed else [],
+ check_no_permissions=False,
+ )
+
+ # then
+ if is_allowed:
+ data = get_graphql_content(response)["data"]["categoryDelete"]
+ assert data["errors"] == []
+ assert Category.objects.filter(pk=category.pk).exists() is False
+ assert data["category"] == {
+ "name": original_name,
+ "externalReference": original_reference,
+ }
+ webhook.assert_called_once()
+ else:
+ assert_no_permission(response)
+ content = get_graphql_content_from_response(response)
+ assert content["data"] == {"categoryDelete": None}
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["path"] == ["categoryDelete"]
+ assert content["errors"][0]["message"] == (
+ "To access this path, you need one of the following permissions: MANAGE_PRODUCTS"
+ )
+ category.refresh_from_db(fields=("name", "external_reference"))
+ assert category.name == original_name
+ assert category.external_reference == original_reference
+ webhook.assert_not_called()
+
@patch("saleor.core.tasks.delete_from_storage_task.delay")
def test_category_delete_mutation(
diff --git a/saleor/graphql/product/tests/mutations/test_category_update.py b/saleor/graphql/product/tests/mutations/test_category_update.py
index f5bebe5d98..26d4d3210e 100644
--- a/saleor/graphql/product/tests/mutations/test_category_update.py
+++ b/saleor/graphql/product/tests/mutations/test_category_update.py
@@ -18,10 +18,290 @@ from .....thumbnail.models import Thumbnail
from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.payloads import generate_meta, generate_requestor
from ....tests.utils import (
+ assert_no_permission,
get_graphql_content,
+ get_graphql_content_from_response,
get_multipart_request_body,
)
+MUTATION_UPDATE_CATEGORY_BY_EXTERNAL_REFERENCE = """
+ mutation updateCategory(
+ $id: ID, $externalReference: String, $input: CategoryInput!
+ ) {
+ categoryUpdate(
+ id: $id, externalReference: $externalReference, input: $input
+ ) {
+ errors {
+ message
+ field
+ code
+ }
+ category {
+ name
+ externalReference
+ }
+ }
+ }
+"""
+
+
+def test_update_category_by_external_reference(
+ staff_api_client, category, permission_manage_products
+):
+ # given
+ external_reference = "test-ext-ref"
+ category.external_reference = external_reference
+ category.save(update_fields=["external_reference"])
+ name = "New name"
+ variables = {
+ "externalReference": external_reference,
+ "input": {"name": name},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_CATEGORY_BY_EXTERNAL_REFERENCE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["categoryUpdate"]
+ assert data["errors"] == []
+ category.refresh_from_db(fields=("name", "external_reference"))
+ assert data["category"]["name"] == name
+ assert category.name == name
+ assert category.external_reference == external_reference
+
+
+def test_update_category_with_non_unique_external_reference(
+ staff_api_client, category, category_list, permission_manage_products
+):
+ # given
+ external_reference = "test-ext-ref"
+ other_category = category_list[0]
+ other_category.external_reference = external_reference
+ other_category.save(update_fields=["external_reference"])
+
+ variables = {
+ "id": graphene.Node.to_global_id("Category", category.pk),
+ "input": {"externalReference": external_reference},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_CATEGORY_BY_EXTERNAL_REFERENCE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["categoryUpdate"]
+ category.refresh_from_db(fields=("external_reference",))
+ assert category.external_reference is None
+ assert data["category"] is None
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert (
+ errors[0]["message"] == "Category with this External reference already exists."
+ )
+ assert errors[0]["field"] == "externalReference"
+ assert errors[0]["code"] == ProductErrorCode.UNIQUE.name
+
+
+ ("_case", "identifiers", "error_field", "error_code", "message"),
+ [
+ (
+ "omitted",
+ {},
+ None,
+ ProductErrorCode.GRAPHQL_ERROR,
+ "At least one of arguments is required: 'id', 'external_reference'.",
+ ),
+ (
+ "null",
+ {"id": None, "externalReference": None},
+ None,
+ ProductErrorCode.GRAPHQL_ERROR,
+ "At least one of arguments is required: 'id', 'external_reference'.",
+ ),
+ (
+ "empty",
+ {"externalReference": ""},
+ None,
+ ProductErrorCode.GRAPHQL_ERROR,
+ "At least one of arguments is required: 'id', 'external_reference'.",
+ ),
+ (
+ "both",
+ {"externalReference": "existing-reference"},
+ None,
+ ProductErrorCode.GRAPHQL_ERROR,
+ "Argument 'id' cannot be combined with 'external_reference'",
+ ),
+ (
+ "not_found",
+ {"externalReference": "missing-reference"},
+ "externalReference",
+ ProductErrorCode.NOT_FOUND,
+ "Couldn't resolve to a node: missing-reference",
+ ),
+ ],
+)
+def test_external_reference_invalid_identifiers(
+ _case,
+ identifiers,
+ error_field,
+ error_code,
+ message,
+ staff_api_client,
+ category,
+ permission_manage_products,
+ mocker,
+):
+ # given
+ category.external_reference = "existing-reference"
+ category.save(update_fields=("external_reference",))
+ original_name = category.name
+ original_reference = category.external_reference
+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.category_updated")
+ variables = dict(identifiers)
+ if _case == "both":
+ variables["id"] = graphene.Node.to_global_id("Category", category.pk)
+ variables["input"] = {"name": "Changed name"}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_CATEGORY_BY_EXTERNAL_REFERENCE,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["categoryUpdate"]
+ assert data["category"] is None
+ assert len(data["errors"]) == 1
+ assert data["errors"][0] == {
+ "field": error_field,
+ "code": error_code.name,
+ "message": message,
+ }
+ category.refresh_from_db(fields=("name", "external_reference"))
+ assert category.name == original_name
+ assert category.external_reference == original_reference
+ webhook.assert_not_called()
+
+
+ ("_case", "client_fixture", "is_allowed"),
+ [
+ ("anonymous", "api_client", False),
+ ("customer", "user_api_client", False),
+ ("staff_without_permission", "staff_api_client", False),
+ ("staff_with_permission", "staff_api_client", True),
+ ("app_without_permission", "app_api_client", False),
+ ("app_with_permission", "app_api_client", True),
+ ],
+)
+def test_external_reference_authorization(
+ _case,
+ client_fixture,
+ is_allowed,
+ request,
+ category,
+ permission_manage_products,
+ mocker,
+):
+ # given
+ client = request.getfixturevalue(client_fixture)
+ category.external_reference = "existing-reference"
+ category.save(update_fields=("external_reference",))
+ original_name = category.name
+ original_reference = category.external_reference
+ name = "Changed category"
+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.category_updated")
+ variables = {"externalReference": original_reference, "input": {"name": name}}
+
+ # when
+ response = client.post_graphql(
+ MUTATION_UPDATE_CATEGORY_BY_EXTERNAL_REFERENCE,
+ variables,
+ permissions=[permission_manage_products] if is_allowed else [],
+ check_no_permissions=False,
+ )
+
+ # then
+ if is_allowed:
+ data = get_graphql_content(response)["data"]["categoryUpdate"]
+ assert data["errors"] == []
+ category.refresh_from_db(fields=("name", "external_reference"))
+ assert category.name == name
+ assert category.external_reference == original_reference
+ assert data["category"] == {
+ "name": name,
+ "externalReference": original_reference,
+ }
+ webhook.assert_called_once()
+ else:
+ assert_no_permission(response)
+ content = get_graphql_content_from_response(response)
+ assert content["data"] == {"categoryUpdate": None}
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["path"] == ["categoryUpdate"]
+ assert content["errors"][0]["message"] == (
+ "To access this path, you need one of the following permissions: MANAGE_PRODUCTS"
+ )
+ category.refresh_from_db(fields=("name", "external_reference"))
+ assert category.name == original_name
+ assert category.external_reference == original_reference
+ webhook.assert_not_called()
+
+
+ ("_case", "reference_input", "expected_reference"),
+ [
+ ("changed", {"externalReference": "new-reference"}, "new-reference"),
+ ("cleared", {"externalReference": None}, None),
+ ("omitted", {}, "original-reference"),
+ ],
+)
+def test_external_reference_input(
+ _case,
+ reference_input,
+ expected_reference,
+ staff_api_client,
+ category,
+ permission_manage_products,
+):
+ # given
+ category.external_reference = "original-reference"
+ category.save(update_fields=("external_reference",))
+ name = "Updated category"
+ variables = {
+ "externalReference": category.external_reference,
+ "input": {"name": name, **reference_input},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_CATEGORY_BY_EXTERNAL_REFERENCE,
+ variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["categoryUpdate"]
+ assert data["errors"] == []
+ assert data["category"] == {"name": name, "externalReference": expected_reference}
+ category.refresh_from_db(fields=("name", "external_reference"))
+ assert category.name == name
+ assert category.external_reference == expected_reference
+
+
MUTATION_CATEGORY_UPDATE_MUTATION = """
mutation($id: ID!, $name: String, $slug: String,
$backgroundImage: Upload, $backgroundImageAlt: String,
diff --git a/saleor/graphql/product/tests/queries/test_category_query.py b/saleor/graphql/product/tests/queries/test_category_query.py
index 66a1f37955..9a63872313 100644
--- a/saleor/graphql/product/tests/queries/test_category_query.py
+++ b/saleor/graphql/product/tests/queries/test_category_query.py
@@ -2,6 +2,7 @@ import logging
from unittest.mock import MagicMock
import graphene
+import pytest
from django.core.files import File
from .....product.models import Category, Product
@@ -14,6 +15,90 @@ from ....tests.utils import (
get_graphql_content_from_response,
)
+QUERY_CATEGORY_BY_EXTERNAL_REFERENCE = """
+ query ($id: ID, $slug: String, $externalReference: String) {
+ category(
+ id: $id,
+ slug: $slug,
+ externalReference: $externalReference,
+ ) {
+ id
+ name
+ externalReference
+ }
+ }
+ """
+
+
+def test_category_query_by_external_reference(user_api_client, category):
+ # given
+ external_reference = "test-ext-ref"
+ category.external_reference = external_reference
+ category.save(update_fields=("external_reference",))
+ variables = {"externalReference": external_reference}
+
+ # when
+ response = user_api_client.post_graphql(
+ QUERY_CATEGORY_BY_EXTERNAL_REFERENCE, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"] == {
+ "category": {
+ "id": graphene.Node.to_global_id("Category", category.pk),
+ "name": category.name,
+ "externalReference": external_reference,
+ }
+ }
+
+
+def test_category_query_by_external_reference_not_found(user_api_client):
+ # given
+ variables = {"externalReference": "non-existing-ext-ref"}
+
+ # when
+ response = user_api_client.post_graphql(
+ QUERY_CATEGORY_BY_EXTERNAL_REFERENCE, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"] == {"category": None}
+
+
+ ("_case", "identifier"),
+ [("id", "id"), ("slug", "slug")],
+)
+def test_external_reference_conflicting_identifiers(
+ _case, identifier, user_api_client, category
+):
+ # given
+ variables = {
+ identifier: (
+ graphene.Node.to_global_id("Category", category.pk)
+ if identifier == "id"
+ else category.slug
+ ),
+ "externalReference": "category-reference",
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ QUERY_CATEGORY_BY_EXTERNAL_REFERENCE, variables
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ assert content["data"] == {"category": None}
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["message"] == (
+ f"Argument '{identifier}' cannot be combined with 'external_reference'"
+ )
+ assert content["errors"][0]["path"] == ["category"]
+
+
QUERY_CATEGORY = """
query ($id: ID, $slug: String, $channel: String, $slugLanguageCode: LanguageCodeEnum){
category(
diff --git a/saleor/graphql/product/types/categories.py b/saleor/graphql/product/types/categories.py
index 7348b79e96..2e20fcd287 100644
--- a/saleor/graphql/product/types/categories.py
+++ b/saleor/graphql/product/types/categories.py
@@ -19,7 +19,7 @@ from ...core.connection import (
filter_connection_queryset,
)
from ...core.context import ChannelQsContext, get_database_connection_name
-from ...core.descriptions import DEPRECATED_IN_3X_INPUT, RICH_CONTENT
+from ...core.descriptions import ADDED_IN_323, DEPRECATED_IN_3X_INPUT, RICH_CONTENT
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
from ...core.federation import federated_entity, resolve_federation_references
from ...core.fields import ConnectionField, FilterConnectionField, JSONString
@@ -48,6 +48,9 @@ class Category(ModelObjectType[models.Category]):
name = graphene.String(required=True, description="Name of category")
description = JSONString(description="Description of the category." + RICH_CONTENT)
slug = graphene.String(required=True, description="Slug of the category.")
+ external_reference = graphene.String(
+ description=f"External ID of this category.{ADDED_IN_323}"
+ )
parent = graphene.Field(lambda: Category, description="Parent category.")
level = graphene.Int(required=True, description="Level of the category.")
description_json = JSONString(
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 953db20048..fdb126f351 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -337,7 +337,9 @@ type Query {
last: Int
): CategoryCountableConnection @doc(category: "Products")
- """Look up a category by ID or slug."""
+ """
+ Look up a category by ID, slug or external reference. If slugLanguageCode is provided, category will be fetched by slug translation.
+ """
category(
"""ID of the category."""
id: ID
@@ -347,6 +349,13 @@ type Query {
"""Language code of the category slug, omit to use primary slug."""
slugLanguageCode: LanguageCodeEnum
+
+ """
+ External ID of the category.
+
+ Added in Saleor 3.23.
+ """
+ externalReference: String
): Category @doc(category: "Products")
"""
@@ -4312,6 +4321,13 @@ type Category implements Node & ObjectWithMetadata @doc(category: "Products") {
"""Slug of the category."""
slug: String!
+ """
+ External ID of this category.
+
+ Added in Saleor 3.23.
+ """
+ externalReference: String
+
"""Parent category."""
parent: Category
@@ -18395,8 +18411,15 @@ type Mutation {
Requires one of the following permissions: MANAGE_PRODUCTS.
"""
categoryDelete(
+ """
+ External ID of a category to delete.
+
+ Added in Saleor 3.23.
+ """
+ externalReference: String
+
"""ID of a category to delete."""
- id: ID!
+ id: ID
): CategoryDelete @doc(category: "Products")
"""
@@ -18417,8 +18440,15 @@ type Mutation {
Requires one of the following permissions: MANAGE_PRODUCTS.
"""
categoryUpdate(
+ """
+ External ID of a category to update.
+
+ Added in Saleor 3.23.
+ """
+ externalReference: String
+
"""ID of a category to update."""
- id: ID!
+ id: ID
"""Fields required to update a category."""
input: CategoryInput!
@@ -24419,6 +24449,13 @@ input CategoryInput @doc(category: "Products") {
"""Category slug."""
slug: String
+ """
+ External ID of this category.
+
+ Added in Saleor 3.23.
+ """
+ externalReference: String
+
"""Search engine optimization fields."""
seo: SeoInput
diff --git a/saleor/product/migrations/0207_category_external_reference.py b/saleor/product/migrations/0207_category_external_reference.py
new file mode 100644
index 0000000000..ddd9b0a96d
--- /dev/null
+++ b/saleor/product/migrations/0207_category_external_reference.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("product", "0206_product_media_translation"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="category",
+ name="external_reference",
+ field=models.CharField(blank=True, max_length=250, null=True),
+ ),
+ ]
diff --git a/saleor/product/migrations/0208_category_external_reference_unique_constraint.py b/saleor/product/migrations/0208_category_external_reference_unique_constraint.py
new file mode 100644
index 0000000000..37db17c586
--- /dev/null
+++ b/saleor/product/migrations/0208_category_external_reference_unique_constraint.py
@@ -0,0 +1,53 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ # The unique index is built CONCURRENTLY so it does not hold an ACCESS
+ # EXCLUSIVE lock on product_category while it is created. CONCURRENTLY
+ # cannot run inside a transaction, hence atomic = False and its own
+ # migration, separate from the fast, atomic AddField in 0207.
+ atomic = False
+
+ dependencies = [
+ ("product", "0207_category_external_reference"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ database_operations=[
+ migrations.RunSQL(
+ sql="""
+ CREATE UNIQUE INDEX CONCURRENTLY category_external_reference_key
+ ON product_category ("external_reference");
+ """,
+ reverse_sql="""
+ DROP INDEX CONCURRENTLY IF EXISTS category_external_reference_key;
+ """,
+ ),
+ migrations.RunSQL(
+ sql="""
+ ALTER TABLE product_category
+ ADD CONSTRAINT category_external_reference_key
+ UNIQUE USING INDEX category_external_reference_key;
+ """,
+ reverse_sql="""
+ ALTER TABLE product_category DROP CONSTRAINT
+ IF EXISTS category_external_reference_key;
+ """,
+ ),
+ ],
+ state_operations=[
+ migrations.AlterField(
+ model_name="category",
+ name="external_reference",
+ field=models.CharField(
+ blank=True,
+ max_length=250,
+ null=True,
+ unique=True,
+ db_index=True,
+ ),
+ ),
+ ],
+ ),
+ ]
diff --git a/saleor/product/migrations/0209_merge_20261005_0735.py b/saleor/product/migrations/0209_merge_20261005_0735.py
new file mode 100644
index 0000000000..8438d3695b
--- /dev/null
+++ b/saleor/product/migrations/0209_merge_20261005_0735.py
@@ -0,0 +1,12 @@
+# Generated by Django 5.2.17 on 2026-10-05 07:35
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("product", "0208_category_external_reference_unique_constraint"),
+ ("product", "0208_merge_20260917_1338"),
+ ]
+
+ operations = []
diff --git a/saleor/product/models.py b/saleor/product/models.py
index f045ec5185..95ff2a1123 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -54,7 +54,7 @@ ALL_PRODUCTS_PERMISSIONS = [
]
-class Category(ModelWithMetadata, MPTTModel, SeoModel):
+class Category(ModelWithMetadata, MPTTModel, SeoModel, ModelWithExternalReference):
name = models.CharField(max_length=250)
slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)
description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)