Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add externalReference support to Collection (#19870)
DamianCzajkowskiddf48d82e4a1
diff --git a/saleor/graphql/product/mutations/collection/collection_create.py b/saleor/graphql/product/mutations/collection/collection_create.pyindex 8204478bee..7e9809033c 100644--- a/saleor/graphql/product/mutations/collection/collection_create.py+++ b/saleor/graphql/product/mutations/collection/collection_create.py@@ -11,7 +11,7 @@ from .....product.error_codes import CollectionErrorCodefrom .....product.tasks import collection_product_updated_taskfrom ....core import ResolveInfofrom ....core.context import ChannelContext-from ....core.descriptions import DEPRECATED_IN_3X_INPUT, RICH_CONTENT+from ....core.descriptions import ADDED_IN_323, DEPRECATED_IN_3X_INPUT, RICH_CONTENTfrom ....core.doc_category import DOC_CATEGORY_PRODUCTSfrom ....core.fields import JSONStringfrom ....core.mutations import DeprecatedModelMutation@@ -40,6 +40,10 @@ class CollectionInput(BaseInputObjectType):)name = graphene.String(description="Name of the collection.")slug = graphene.String(description="Slug of the collection.")+ external_reference = graphene.String(+ description=f"External ID of this collection.{ADDED_IN_323}",+ required=False,+ )description = JSONString(description="Description of the collection." + RICH_CONTENT)diff --git a/saleor/graphql/product/mutations/collection/collection_delete.py b/saleor/graphql/product/mutations/collection/collection_delete.pyindex ea0a56b1ea..f3beaaba4d 100644--- a/saleor/graphql/product/mutations/collection/collection_delete.py+++ b/saleor/graphql/product/mutations/collection/collection_delete.py@@ -6,7 +6,8 @@ from .....product import modelsfrom .....product.tasks import collection_product_updated_taskfrom ....core import ResolveInfofrom ....core.context import ChannelContext-from ....core.mutations import ModelDeleteMutation+from ....core.descriptions import ADDED_IN_323+from ....core.mutations import ModelDeleteMutation, ModelWithExtRefMutationfrom ....core.types import CollectionErrorfrom ....plugins.dataloaders import get_plugin_manager_promisefrom ...types import Collection@@ -16,9 +17,13 @@ from ...types import CollectionPRODUCTS_BATCH_SIZE = 25000-class CollectionDelete(ModelDeleteMutation):+class CollectionDelete(ModelDeleteMutation, ModelWithExtRefMutation):class Arguments:- id = graphene.ID(required=True, description="ID of a collection to delete.")+ id = graphene.ID(required=False, description="ID of a collection to delete.")+ external_reference = graphene.String(+ required=False,+ description=f"External ID of a collection to delete.{ADDED_IN_323}",+ )class Meta:description = "Deletes a collection."@@ -36,12 +41,14 @@ class CollectionDelete(ModelDeleteMutation):@classmethoddef 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=Collection)+ instance = cls.get_instance(info, external_reference=external_reference, id=id)product_ids = list(instance.products.values_list("id", flat=True))- result = super().perform_mutation(_root, info, id=id)+ result = super().perform_mutation(+ _root, info, external_reference=external_reference, id=id+ )manager = get_plugin_manager_promise(info.context).get()cls.call_event(manager.collection_deleted, instance)diff --git a/saleor/graphql/product/mutations/collection/collection_update.py b/saleor/graphql/product/mutations/collection/collection_update.pyindex cb740cae0c..242b8f5083 100644--- a/saleor/graphql/product/mutations/collection/collection_update.py+++ b/saleor/graphql/product/mutations/collection/collection_update.py@@ -6,15 +6,21 @@ from .....permission.enums import ProductPermissionsfrom .....product import modelsfrom .....thumbnail import models as thumbnail_modelsfrom ....core import ResolveInfo+from ....core.descriptions import ADDED_IN_323+from ....core.mutations import ModelWithExtRefMutationfrom ....core.types import CollectionErrorfrom ....plugins.dataloaders import get_plugin_manager_promisefrom ...types import Collectionfrom .collection_create import CollectionCreate, CollectionInput-class CollectionUpdate(CollectionCreate):+class CollectionUpdate(CollectionCreate, ModelWithExtRefMutation):class Arguments:- id = graphene.ID(required=True, description="ID of a collection to update.")+ id = graphene.ID(required=False, description="ID of a collection to update.")+ external_reference = graphene.String(+ required=False,+ description=f"External ID of a collection to update.{ADDED_IN_323}",+ )input = CollectionInput(required=True, description="Fields required to update a collection.")diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.pyindex 27dfb3fdbc..a1be9ee47a 100644--- a/saleor/graphql/product/resolvers.py+++ b/saleor/graphql/product/resolvers.py@@ -64,6 +64,17 @@ def resolve_collection_by_id(info: ResolveInfo, id, channel_slug, requestor):)+def resolve_collection_by_external_reference(+ info: ResolveInfo, external_reference, channel_slug, requestor+):+ return (+ models.Collection.objects.using(get_database_connection_name(info.context))+ .visible_to_user(requestor, channel_slug=channel_slug)+ .filter(external_reference=external_reference)+ .first()+ )++def resolve_collection_by_slug(info: ResolveInfo, slug, 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.pyindex a64d91c644..2c56d7bdd4 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -105,6 +105,7 @@ from .resolvers import (resolve_categories,resolve_category_by_external_reference,resolve_category_by_translated_slug,+ resolve_collection_by_external_reference,resolve_collection_by_id,resolve_collection_by_slug,resolve_collection_by_translated_slug,@@ -182,14 +183,18 @@ class ProductQueries(graphene.ObjectType):LanguageCodeEnum,description="Language code of the collection slug, omit to use primary slug.",),+ external_reference=graphene.Argument(+ graphene.String,+ description=f"External ID of the collection.{ADDED_IN_323}",+ ),channel=graphene.String(description="Slug of a channel for which the data should be returned."),description=(- "Look up a collection by ID or slug. If slugLanguageCode is provided, "- "category will be fetched by slug translation. Requires one of the "- "following permissions to include the unpublished items: "- f"{', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}."+ "Look up a collection by ID, slug or external reference. If "+ "slugLanguageCode is provided, category will be fetched by slug "+ "translation. Requires one of the following permissions to include "+ f"the unpublished items: {', '.join([p.name for p in ALL_PRODUCTS_PERMISSIONS])}."),doc_category=DOC_CATEGORY_PRODUCTS,)@@ -385,8 +390,11 @@ class ProductQueries(graphene.ObjectType):slug=None,channel=None,slug_language_code=None,+ external_reference=None,):- 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+ )requestor = get_user_or_app_from_context(info.context)has_required_permissions = has_one_of_permissions(@@ -400,6 +408,10 @@ class ProductQueries(graphene.ObjectType):if id:_, id = from_global_id_or_error(id, Collection)collection = resolve_collection_by_id(info, id, channel, requestor)+ elif external_reference:+ collection = resolve_collection_by_external_reference(+ info, external_reference, channel, requestor+ )else:if slug_language_code is None:collection = resolve_collection_by_slug(diff --git a/saleor/graphql/product/tests/mutations/test_collection_create.py b/saleor/graphql/product/tests/mutations/test_collection_create.pyindex 9323ea7d98..ba680c995a 100644--- a/saleor/graphql/product/tests/mutations/test_collection_create.py+++ b/saleor/graphql/product/tests/mutations/test_collection_create.py@@ -9,7 +9,9 @@ from .....product.models import Collectionfrom .....product.tests.utils import create_imagefrom .....tests.utils import dummy_editorjsfrom ....tests.utils import (+ assert_no_permission,get_graphql_content,+ get_graphql_content_from_response,get_multipart_request_body,)@@ -59,6 +61,82 @@ CREATE_COLLECTION_MUTATION = """"""+CREATE_COLLECTION_WITH_EXTERNAL_REFERENCE_MUTATION = """+ mutation createCollection($name: String!, $externalReference: String) {+ collectionCreate(+ input: {name: $name, externalReference: $externalReference}+ ) {+ collection {+ name+ externalReference+ }+ errors {+ field+ message+ code+ }+ }+ }+"""+++def test_create_collection_with_external_reference(+ staff_api_client, permission_manage_products+):+ # given+ name = "test-collection"+ external_reference = "test-ext-ref"+ variables = {"name": name, "externalReference": external_reference}++ # when+ response = staff_api_client.post_graphql(+ CREATE_COLLECTION_WITH_EXTERNAL_REFERENCE_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["collectionCreate"]+ assert data["errors"] == []+ assert data["collection"]["externalReference"] == external_reference+ collection = Collection.objects.get(name=name)+ assert collection.external_reference == external_reference+++def test_create_collection_with_non_unique_external_reference(+ staff_api_client, collection, permission_manage_products+):+ # given+ external_reference = "test-ext-ref"+ collection.external_reference = external_reference+ collection.save(update_fields=["external_reference"])++ name = "new-collection"+ variables = {"name": name, "externalReference": external_reference}++ # when+ response = staff_api_client.post_graphql(+ CREATE_COLLECTION_WITH_EXTERNAL_REFERENCE_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["collectionCreate"]+ assert data["collection"] is None+ assert Collection.objects.filter(name=name).exists() is False+ errors = data["errors"]+ assert len(errors) == 1+ assert (+ errors[0]["message"]+ == "Collection with this External reference already exists."+ )+ assert errors[0]["field"] == "externalReference"+ assert errors[0]["code"] == CollectionErrorCode.UNIQUE.name++@patch("saleor.plugins.manager.PluginsManager.collection_updated")@patch("saleor.plugins.manager.PluginsManager.collection_created")def test_create_collection(@@ -243,3 +321,101 @@ def test_create_collection_file_size_exceeds_limit(assert errors[0]["code"] == CollectionErrorCode.FILE_SIZE_LIMIT_EXCEEDED.nameassert "File size exceeds the maximum allowed size" in errors[0]["message"]assert not Collection.objects.filter(name=collection_name).exists()+++ ("_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,+ collection,+ permission_manage_products,+ mocker,+):+ # given+ client = request.getfixturevalue(client_fixture)+ collection.external_reference = "existing-reference"+ collection.save(update_fields=("external_reference",))+ original_name = collection.name+ original_reference = collection.external_reference+ name = "Changed collection"+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.collection_created")+ task = mocker.patch("saleor.product.tasks.collection_product_updated_task.delay")+ variables = {"name": name, "externalReference": "new-reference"}++ # when+ response = client.post_graphql(+ CREATE_COLLECTION_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"]["collectionCreate"]+ assert data["errors"] == []+ created = Collection.objects.get(external_reference="new-reference")+ assert created.name == name+ assert data["collection"] == {+ "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"] == {"collectionCreate": None}+ assert len(content["errors"]) == 1+ assert content["errors"][0]["path"] == ["collectionCreate"]+ assert content["errors"][0]["message"] == (+ "To access this path, you need one of the following permissions: MANAGE_PRODUCTS"+ )+ collection.refresh_from_db(fields=("name", "external_reference"))+ assert collection.name == original_name+ assert collection.external_reference == original_reference+ assert Collection.objects.filter(name=name).exists() is False+ webhook.assert_not_called()+ task.assert_not_called()+++ ("_case", "reference_input"),+ [("omitted", {}), ("null", {"externalReference": None})],+)+def test_without_external_reference(+ _case,+ reference_input,+ staff_api_client,+ collection,+ permission_manage_products,+):+ # given+ assert collection.external_reference is None+ name = "Collection without reference"+ variables = {"name": name, **reference_input}++ # when+ response = staff_api_client.post_graphql(+ CREATE_COLLECTION_WITH_EXTERNAL_REFERENCE_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )++ # then+ data = get_graphql_content(response)["data"]["collectionCreate"]+ assert data["errors"] == []+ assert data["collection"] == {"name": name, "externalReference": None}+ created = Collection.objects.get(name=name)+ assert created.external_reference is Nonediff --git a/saleor/graphql/product/tests/mutations/test_collection_delete.py b/saleor/graphql/product/tests/mutations/test_collection_delete.pyindex 9b774aed20..b371db884f 100644--- a/saleor/graphql/product/tests/mutations/test_collection_delete.py+++ b/saleor/graphql/product/tests/mutations/test_collection_delete.py@@ -7,9 +7,13 @@ from django.core.files import Filefrom .....attribute.models import AttributeValuefrom .....attribute.utils import associate_attribute_values_to_instancefrom .....discount.utils.promotion import get_active_catalogue_promotion_rules+from .....product.error_codes import CollectionErrorCode+from .....product.models import Collectionfrom .....thumbnail.models import Thumbnailfrom ....tests.utils import (+ assert_no_permission,get_graphql_content,+ get_graphql_content_from_response,)DELETE_COLLECTION_MUTATION = """@@ -28,6 +32,48 @@ DELETE_COLLECTION_MUTATION = """"""+DELETE_COLLECTION_BY_EXTERNAL_REFERENCE_MUTATION = """+ mutation deleteCollection($id: ID, $externalReference: String) {+ collectionDelete(id: $id, externalReference: $externalReference) {+ collection {+ name+ externalReference+ }+ errors {+ field+ message+ code+ }+ }+ }+"""+++def test_delete_collection_by_external_reference(+ staff_api_client, collection, permission_manage_products+):+ # given+ external_reference = "test-ext-ref"+ collection.external_reference = external_reference+ collection.save(update_fields=["external_reference"])+ variables = {"externalReference": external_reference}++ # when+ response = staff_api_client.post_graphql(+ DELETE_COLLECTION_BY_EXTERNAL_REFERENCE_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["collectionDelete"]+ assert data["errors"] == []+ assert data["collection"]["name"] == collection.name+ assert data["collection"]["externalReference"] == external_reference+ assert Collection.objects.filter(pk=collection.pk).exists() is False++@patch("saleor.plugins.manager.PluginsManager.collection_deleted")def test_delete_collection(deleted_webhook_mock,@@ -242,3 +288,153 @@ def test_collection_delete_removes_reference_to_page(collection.refresh_from_db()assert not data["errors"]+++ ("_case", "identifiers", "error_field", "error_code", "message"),+ [+ (+ "omitted",+ {},+ None,+ CollectionErrorCode.GRAPHQL_ERROR,+ "At least one of arguments is required: 'id', 'external_reference'.",+ ),+ (+ "null",+ {"id": None, "externalReference": None},+ None,+ CollectionErrorCode.GRAPHQL_ERROR,+ "At least one of arguments is required: 'id', 'external_reference'.",+ ),+ (+ "empty",+ {"externalReference": ""},+ None,+ CollectionErrorCode.GRAPHQL_ERROR,+ "At least one of arguments is required: 'id', 'external_reference'.",+ ),+ (+ "both",+ {"externalReference": "existing-reference"},+ None,+ CollectionErrorCode.GRAPHQL_ERROR,+ "Argument 'id' cannot be combined with 'external_reference'",+ ),+ (+ "not_found",+ {"externalReference": "missing-reference"},+ "externalReference",+ CollectionErrorCode.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,+ collection,+ permission_manage_products,+ mocker,+):+ # given+ collection.external_reference = "existing-reference"+ collection.save(update_fields=("external_reference",))+ original_name = collection.name+ original_reference = collection.external_reference+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.collection_deleted")+ task = mocker.patch("saleor.product.tasks.collection_product_updated_task.delay")+ variables = dict(identifiers)+ if _case == "both":+ variables["id"] = graphene.Node.to_global_id("Collection", collection.pk)++ # when+ response = staff_api_client.post_graphql(+ DELETE_COLLECTION_BY_EXTERNAL_REFERENCE_MUTATION,+ variables,+ permissions=[permission_manage_products],+ check_no_permissions=False,+ )++ # then+ data = get_graphql_content(response)["data"]["collectionDelete"]+ assert data["collection"] is None+ assert len(data["errors"]) == 1+ assert data["errors"][0] == {+ "field": error_field,+ "code": error_code.name,+ "message": message,+ }+ collection.refresh_from_db(fields=("name", "external_reference"))+ assert collection.name == original_name+ assert collection.external_reference == original_reference+ webhook.assert_not_called()+ task.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,+ collection,+ permission_manage_products,+ mocker,+):+ # given+ client = request.getfixturevalue(client_fixture)+ collection.external_reference = "existing-reference"+ collection.save(update_fields=("external_reference",))+ original_name = collection.name+ original_reference = collection.external_reference+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.collection_deleted")+ task = mocker.patch("saleor.product.tasks.collection_product_updated_task.delay")+ variables = {"externalReference": original_reference}++ # when+ response = client.post_graphql(+ DELETE_COLLECTION_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"]["collectionDelete"]+ assert data["errors"] == []+ assert Collection.objects.filter(pk=collection.pk).exists() is False+ assert data["collection"] == {+ "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"] == {"collectionDelete": None}+ assert len(content["errors"]) == 1+ assert content["errors"][0]["path"] == ["collectionDelete"]+ assert content["errors"][0]["message"] == (+ "To access this path, you need one of the following permissions: MANAGE_PRODUCTS"+ )+ collection.refresh_from_db(fields=("name", "external_reference"))+ assert collection.name == original_name+ assert collection.external_reference == original_reference+ webhook.assert_not_called()+ task.assert_not_called()diff --git a/saleor/graphql/product/tests/mutations/test_collection_update.py b/saleor/graphql/product/tests/mutations/test_collection_update.pyindex bbd83dc0b7..fd0ba90222 100644--- a/saleor/graphql/product/tests/mutations/test_collection_update.py+++ b/saleor/graphql/product/tests/mutations/test_collection_update.py@@ -4,16 +4,105 @@ import grapheneimport pytestfrom django.core.files import File-from .....product.error_codes import ProductErrorCode+from .....product.error_codes import CollectionErrorCode, ProductErrorCodefrom .....product.models import Collectionfrom .....product.tests.utils import create_image, create_zip_file_with_image_extfrom .....tests.utils import dummy_editorjsfrom .....thumbnail.models import Thumbnailfrom ....tests.utils import (+ assert_no_permission,get_graphql_content,+ get_graphql_content_from_response,get_multipart_request_body,)+MUTATION_UPDATE_COLLECTION_BY_EXTERNAL_REFERENCE = """+ mutation updateCollection(+ $id: ID, $externalReference: String, $input: CollectionInput!+ ) {+ collectionUpdate(+ id: $id, externalReference: $externalReference, input: $input+ ) {+ errors {+ message+ field+ code+ }+ collection {+ name+ externalReference+ }+ }+ }+"""+++def test_update_collection_by_external_reference(+ staff_api_client, collection, permission_manage_products+):+ # given+ external_reference = "test-ext-ref"+ collection.external_reference = external_reference+ collection.save(update_fields=["external_reference"])+ name = "New name"+ variables = {+ "externalReference": external_reference,+ "input": {"name": name},+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_COLLECTION_BY_EXTERNAL_REFERENCE,+ variables=variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["collectionUpdate"]+ assert data["errors"] == []+ collection.refresh_from_db(fields=("name", "external_reference"))+ assert data["collection"]["name"] == name+ assert collection.name == name+ assert collection.external_reference == external_reference+++def test_update_collection_with_non_unique_external_reference(+ staff_api_client, collection, collection_list, permission_manage_products+):+ # given+ external_reference = "test-ext-ref"+ other_collection = collection_list[0]+ other_collection.external_reference = external_reference+ other_collection.save(update_fields=["external_reference"])++ variables = {+ "id": graphene.Node.to_global_id("Collection", collection.pk),+ "input": {"externalReference": external_reference},+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_COLLECTION_BY_EXTERNAL_REFERENCE,+ variables=variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["collectionUpdate"]+ collection.refresh_from_db(fields=("external_reference",))+ assert collection.external_reference is None+ assert data["collection"] is None+ errors = data["errors"]+ assert len(errors) == 1+ assert (+ errors[0]["message"]+ == "Collection with this External reference already exists."+ )+ assert errors[0]["field"] == "externalReference"+ assert errors[0]["code"] == CollectionErrorCode.UNIQUE.name+@patch("saleor.plugins.manager.PluginsManager.collection_updated")@patch("saleor.plugins.manager.PluginsManager.collection_created")@@ -521,3 +610,199 @@ def test_update_collection_mutation_remove_background_image(assert not data["backgroundImage"]collection_with_image.refresh_from_db()assert not collection_with_image.background_image+++ ("_case", "identifiers", "error_field", "error_code", "message"),+ [+ (+ "omitted",+ {},+ None,+ CollectionErrorCode.GRAPHQL_ERROR,+ "At least one of arguments is required: 'id', 'external_reference'.",+ ),+ (+ "null",+ {"id": None, "externalReference": None},+ None,+ CollectionErrorCode.GRAPHQL_ERROR,+ "At least one of arguments is required: 'id', 'external_reference'.",+ ),+ (+ "empty",+ {"externalReference": ""},+ None,+ CollectionErrorCode.GRAPHQL_ERROR,+ "At least one of arguments is required: 'id', 'external_reference'.",+ ),+ (+ "both",+ {"externalReference": "existing-reference"},+ None,+ CollectionErrorCode.GRAPHQL_ERROR,+ "Argument 'id' cannot be combined with 'external_reference'",+ ),+ (+ "not_found",+ {"externalReference": "missing-reference"},+ "externalReference",+ CollectionErrorCode.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,+ collection,+ permission_manage_products,+ mocker,+):+ # given+ collection.external_reference = "existing-reference"+ collection.save(update_fields=("external_reference",))+ original_name = collection.name+ original_reference = collection.external_reference+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.collection_updated")+ task = mocker.patch("saleor.product.tasks.collection_product_updated_task.delay")+ variables = dict(identifiers)+ if _case == "both":+ variables["id"] = graphene.Node.to_global_id("Collection", collection.pk)+ variables["input"] = {"name": "Changed name"}++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_COLLECTION_BY_EXTERNAL_REFERENCE,+ variables,+ permissions=[permission_manage_products],+ check_no_permissions=False,+ )++ # then+ data = get_graphql_content(response)["data"]["collectionUpdate"]+ assert data["collection"] is None+ assert len(data["errors"]) == 1+ assert data["errors"][0] == {+ "field": error_field,+ "code": error_code.name,+ "message": message,+ }+ collection.refresh_from_db(fields=("name", "external_reference"))+ assert collection.name == original_name+ assert collection.external_reference == original_reference+ webhook.assert_not_called()+ task.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,+ collection,+ permission_manage_products,+ mocker,+):+ # given+ client = request.getfixturevalue(client_fixture)+ collection.external_reference = "existing-reference"+ collection.save(update_fields=("external_reference",))+ original_name = collection.name+ original_reference = collection.external_reference+ name = "Changed collection"+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.collection_updated")+ task = mocker.patch("saleor.product.tasks.collection_product_updated_task.delay")+ variables = {"externalReference": original_reference, "input": {"name": name}}++ # when+ response = client.post_graphql(+ MUTATION_UPDATE_COLLECTION_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"]["collectionUpdate"]+ assert data["errors"] == []+ collection.refresh_from_db(fields=("name", "external_reference"))+ assert collection.name == name+ assert collection.external_reference == original_reference+ assert data["collection"] == {+ "name": name,+ "externalReference": original_reference,+ }+ webhook.assert_called_once()+ else:+ assert_no_permission(response)+ content = get_graphql_content_from_response(response)+ assert content["data"] == {"collectionUpdate": None}+ assert len(content["errors"]) == 1+ assert content["errors"][0]["path"] == ["collectionUpdate"]+ assert content["errors"][0]["message"] == (+ "To access this path, you need one of the following permissions: MANAGE_PRODUCTS"+ )+ collection.refresh_from_db(fields=("name", "external_reference"))+ assert collection.name == original_name+ assert collection.external_reference == original_reference+ assert Collection.objects.filter(name=name).exists() is False+ webhook.assert_not_called()+ task.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,+ collection,+ permission_manage_products,+):+ # given+ collection.external_reference = "original-reference"+ collection.save(update_fields=("external_reference",))+ name = "Updated collection"+ variables = {+ "externalReference": collection.external_reference,+ "input": {"name": name, **reference_input},+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_COLLECTION_BY_EXTERNAL_REFERENCE,+ variables,+ permissions=[permission_manage_products],+ )++ # then+ data = get_graphql_content(response)["data"]["collectionUpdate"]+ assert data["errors"] == []+ assert data["collection"] == {"name": name, "externalReference": expected_reference}+ collection.refresh_from_db(fields=("name", "external_reference"))+ assert collection.name == name+ assert collection.external_reference == expected_referencediff --git a/saleor/graphql/product/tests/queries/test_collection_query.py b/saleor/graphql/product/tests/queries/test_collection_query.pyindex e14ec235a0..ba138c3185 100644--- a/saleor/graphql/product/tests/queries/test_collection_query.py+++ b/saleor/graphql/product/tests/queries/test_collection_query.py@@ -2,6 +2,7 @@ import loggingfrom unittest.mock import MagicMockimport graphene+import pytestfrom django.core.files import Filefrom .....product.tests.utils import create_image@@ -24,6 +25,149 @@ QUERY_COLLECTION = """"""+QUERY_COLLECTION_BY_EXTERNAL_REFERENCE = """+ query ($id: ID, $externalReference: String, $slug: String, $channel: String){+ collection(+ id: $id,+ slug: $slug,+ externalReference: $externalReference,+ channel: $channel,+ ) {+ id+ name+ externalReference+ }+ }+ """+++ ("_case", "client_fixture", "has_permission"),+ [+ ("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),+ ],+)+ ("_visibility_case", "is_published", "use_other_channel"),+ [+ ("published", True, False),+ ("unpublished", False, False),+ ("not_assigned_to_channel", True, True),+ ],+)+def test_external_reference_visibility(+ _case,+ client_fixture,+ has_permission,+ _visibility_case,+ is_published,+ use_other_channel,+ request,+ published_collection,+ channel_USD,+ channel_PLN,+ permission_manage_products,+):+ # given+ client = request.getfixturevalue(client_fixture)+ collection = published_collection+ assert collection.channel_listings.get(channel=channel_USD).is_published is True+ assert collection.channel_listings.filter(channel=channel_PLN).exists() is False+ collection.external_reference = "collection-reference"+ collection.save(update_fields=("external_reference",))+ if not is_published:+ collection.channel_listings.filter(channel=channel_USD).update(+ is_published=False+ )+ variables = {+ "externalReference": collection.external_reference,+ "channel": channel_PLN.slug if use_other_channel else channel_USD.slug,+ }++ # when+ response = client.post_graphql(+ QUERY_COLLECTION_BY_EXTERNAL_REFERENCE,+ variables,+ permissions=[permission_manage_products] if has_permission else [],+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ if not use_other_channel and (is_published or has_permission):+ assert content["data"] == {+ "collection": {+ "id": graphene.Node.to_global_id("Collection", collection.pk),+ "name": collection.name,+ "externalReference": collection.external_reference,+ }+ }+ else:+ assert content["data"] == {"collection": None}+++def test_collection_query_by_external_reference_not_found(+ staff_api_client, permission_manage_products, channel_USD+):+ # given+ variables = {+ "externalReference": "non-existing-ext-ref",+ "channel": channel_USD.slug,+ }++ # when+ response = staff_api_client.post_graphql(+ QUERY_COLLECTION_BY_EXTERNAL_REFERENCE,+ variables=variables,+ permissions=(permission_manage_products,),+ check_no_permissions=False,+ )+ content = get_graphql_content(response)++ # then+ assert content["data"]["collection"] is None+++ ("_case", "identifier"),+ [("id", "id"), ("slug", "slug")],+)+def test_external_reference_conflicting_identifiers(+ _case,+ identifier,+ user_api_client,+ published_collection,+):+ # given+ variables = {+ identifier: (+ graphene.Node.to_global_id("Collection", published_collection.pk)+ if identifier == "id"+ else published_collection.slug+ ),+ "externalReference": "collection-reference",+ }++ # when+ response = user_api_client.post_graphql(+ QUERY_COLLECTION_BY_EXTERNAL_REFERENCE, variables=variables+ )++ # then+ content = get_graphql_content(response, ignore_errors=True)+ assert content["data"] == {"collection": 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"] == ["collection"]++def test_collection_query_by_id(user_api_client, published_collection, channel_USD):variables = {"id": graphene.Node.to_global_id("Collection", published_collection.pk),diff --git a/saleor/graphql/product/types/collections.py b/saleor/graphql/product/types/collections.pyindex 373c07f8d2..f2d291c370 100644--- a/saleor/graphql/product/types/collections.py+++ b/saleor/graphql/product/types/collections.py@@ -24,7 +24,7 @@ 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_CONTENTfrom ...core.doc_category import DOC_CATEGORY_PRODUCTSfrom ...core.federation import federated_entityfrom ...core.fields import FilterConnectionField, JSONString, PermissionsField@@ -58,6 +58,9 @@ class Collection(ChannelContextType[models.Collection]):description="Description of the collection." + RICH_CONTENT)slug = graphene.String(required=True, description="Slug of the collection.")+ external_reference = graphene.String(+ description=f"External ID of this collection.{ADDED_IN_323}"+ )channel = graphene.String(description=("Channel given to retrieve this collection. Also used by federation "diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 8adac8a1b9..4a82da517d 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -359,7 +359,7 @@ type Query {): Category @doc(category: "Products")"""- Look up a collection by ID or slug. If slugLanguageCode is provided, category will be fetched by slug translation. Requires one of the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.+ Look up a collection by ID, slug or external reference. If slugLanguageCode is provided, category will be fetched by slug translation. Requires one of the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS."""collection("""ID of the collection."""@@ -371,6 +371,13 @@ type Query {"""Language code of the collection slug, omit to use primary slug."""slugLanguageCode: LanguageCodeEnum+ """+ External ID of the collection.++ Added in Saleor 3.23.+ """+ externalReference: String+"""Slug of a channel for which the data should be returned."""channel: String): Collection @doc(category: "Products")@@ -10169,6 +10176,13 @@ type Collection implements Node & ObjectWithMetadata @doc(category: "Products")"""Slug of the collection."""slug: String!+ """+ External ID of this collection.++ Added in Saleor 3.23.+ """+ externalReference: String+"""Channel given to retrieve this collection. Also used by federation gateway to resolve this object in a federated query."""@@ -18586,8 +18600,15 @@ type Mutation {Requires one of the following permissions: MANAGE_PRODUCTS."""collectionDelete(+ """+ External ID of a collection to delete.++ Added in Saleor 3.23.+ """+ externalReference: String+"""ID of a collection to delete."""- id: ID!+ id: ID): CollectionDelete @doc(category: "Products")"""@@ -18634,8 +18655,15 @@ type Mutation {Requires one of the following permissions: MANAGE_PRODUCTS."""collectionUpdate(+ """+ External ID of a collection to update.++ Added in Saleor 3.23.+ """+ externalReference: String+"""ID of a collection to update."""- id: ID!+ id: ID"""Fields required to update a collection."""input: CollectionInput!@@ -24699,6 +24727,13 @@ input CollectionCreateInput @doc(category: "Products") {"""Slug of the collection."""slug: String+ """+ External ID of this collection.++ Added in Saleor 3.23.+ """+ externalReference: String+"""Description of the collection.@@ -24814,6 +24849,13 @@ input CollectionInput @doc(category: "Products") {"""Slug of the collection."""slug: String+ """+ External ID of this collection.++ Added in Saleor 3.23.+ """+ externalReference: String+"""Description of the collection.diff --git a/saleor/product/migrations/0209_collection_external_reference.py b/saleor/product/migrations/0209_collection_external_reference.pynew file mode 100644index 0000000000..2d97db9aa2--- /dev/null+++ b/saleor/product/migrations/0209_collection_external_reference.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.17 on 2026-09-14 12:21++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("product", "0208_category_external_reference_unique_constraint"),+ ]++ operations = [+ migrations.AddField(+ model_name="collection",+ name="external_reference",+ field=models.CharField(blank=True, max_length=250, null=True),+ ),+ ]diff --git a/saleor/product/migrations/0210_collection_external_reference_unique_constraint.py b/saleor/product/migrations/0210_collection_external_reference_unique_constraint.pynew file mode 100644index 0000000000..237d904267--- /dev/null+++ b/saleor/product/migrations/0210_collection_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_collection while it is created. CONCURRENTLY+ # cannot run inside a transaction, hence atomic = False and its own+ # migration, separate from the fast, atomic AddField in 0209.+ atomic = False++ dependencies = [+ ("product", "0209_collection_external_reference"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ database_operations=[+ migrations.RunSQL(+ sql="""+ CREATE UNIQUE INDEX CONCURRENTLY collection_external_reference_key+ ON product_collection ("external_reference");+ """,+ reverse_sql="""+ DROP INDEX CONCURRENTLY IF EXISTS collection_external_reference_key;+ """,+ ),+ migrations.RunSQL(+ sql="""+ ALTER TABLE product_collection+ ADD CONSTRAINT collection_external_reference_key+ UNIQUE USING INDEX collection_external_reference_key;+ """,+ reverse_sql="""+ ALTER TABLE product_collection DROP CONSTRAINT+ IF EXISTS collection_external_reference_key;+ """,+ ),+ ],+ state_operations=[+ migrations.AlterField(+ model_name="collection",+ name="external_reference",+ field=models.CharField(+ blank=True,+ max_length=250,+ null=True,+ unique=True,+ db_index=True,+ ),+ ),+ ],+ ),+ ]diff --git a/saleor/product/migrations/0211_merge_20261005_0745.py b/saleor/product/migrations/0211_merge_20261005_0745.pynew file mode 100644index 0000000000..d6fd0373ae--- /dev/null+++ b/saleor/product/migrations/0211_merge_20261005_0745.py@@ -0,0 +1,12 @@+# Generated by Django 5.2.17 on 2026-10-05 07:45++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("product", "0209_merge_20261005_0735"),+ ("product", "0210_collection_external_reference_unique_constraint"),+ ]++ operations = []diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 95ff2a1123..ef4a9a7375 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -668,7 +668,7 @@ class CollectionProduct(SortableModel):return self.product.collectionproduct.all()-class Collection(SeoModel, ModelWithMetadata):+class Collection(SeoModel, ModelWithMetadata, ModelWithExternalReference):name = models.CharField(max_length=250)slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)products = models.ManyToManyField(