Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add externalReference support to Promotion (#19868)
DamianCzajkowskicfd5519bbca3
diff --git a/saleor/discount/error_codes.py b/saleor/discount/error_codes.pyindex b05b10e987..e3a4184b42 100644--- a/saleor/discount/error_codes.py+++ b/saleor/discount/error_codes.py@@ -18,6 +18,7 @@ class PromotionCreateErrorCode(Enum):NOT_FOUND = "not_found"REQUIRED = "required"INVALID = "invalid"+ UNIQUE = "unique"MULTIPLE_CURRENCIES_NOT_ALLOWED = "multiple_currencies_not_allowed"INVALID_PRECISION = "invalid_precision"MISSING_CHANNELS = "missing_channels"@@ -31,6 +32,7 @@ class PromotionUpdateErrorCode(Enum):NOT_FOUND = "not_found"REQUIRED = "required"INVALID = "invalid"+ UNIQUE = "unique"class PromotionDeleteErrorCode(Enum):diff --git a/saleor/discount/migrations/0088_promotion_external_reference.py b/saleor/discount/migrations/0088_promotion_external_reference.pynew file mode 100644index 0000000000..514e1429ba--- /dev/null+++ b/saleor/discount/migrations/0088_promotion_external_reference.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("discount", "0087_merge_20250630_1332"),+ ]++ operations = [+ migrations.AddField(+ model_name="promotion",+ name="external_reference",+ field=models.CharField(blank=True, max_length=250, null=True),+ ),+ ]diff --git a/saleor/discount/migrations/0089_promotion_external_reference_unique_constraint.py b/saleor/discount/migrations/0089_promotion_external_reference_unique_constraint.pynew file mode 100644index 0000000000..44ce06f4c8--- /dev/null+++ b/saleor/discount/migrations/0089_promotion_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 discount_promotion while it is created. CONCURRENTLY+ # cannot run inside a transaction, hence atomic = False and its own+ # migration, separate from the fast, atomic AddField in 0088.+ atomic = False++ dependencies = [+ ("discount", "0088_promotion_external_reference"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ database_operations=[+ migrations.RunSQL(+ sql="""+ CREATE UNIQUE INDEX CONCURRENTLY promotion_external_reference_key+ ON discount_promotion ("external_reference");+ """,+ reverse_sql="""+ DROP INDEX CONCURRENTLY IF EXISTS promotion_external_reference_key;+ """,+ ),+ migrations.RunSQL(+ sql="""+ ALTER TABLE discount_promotion+ ADD CONSTRAINT promotion_external_reference_key+ UNIQUE USING INDEX promotion_external_reference_key;+ """,+ reverse_sql="""+ ALTER TABLE discount_promotion DROP CONSTRAINT+ IF EXISTS promotion_external_reference_key;+ """,+ ),+ ],+ state_operations=[+ migrations.AlterField(+ model_name="promotion",+ name="external_reference",+ field=models.CharField(+ blank=True,+ max_length=250,+ null=True,+ unique=True,+ db_index=True,+ ),+ ),+ ],+ ),+ ]diff --git a/saleor/discount/models.py b/saleor/discount/models.pyindex 1bae13b42e..640e1a2048 100644--- a/saleor/discount/models.py+++ b/saleor/discount/models.py@@ -16,7 +16,7 @@ from ..app.models import Appfrom ..channel.models import Channelfrom ..core.db.fields import MoneyField, SanitizedJSONFieldfrom ..core.editorjs import clean_editorjs-from ..core.models import ModelWithMetadata+from ..core.models import ModelWithExternalReference, ModelWithMetadatafrom ..core.utils.json_serializer import CustomJsonEncoderfrom ..core.utils.translations import Translationfrom ..permission.enums import DiscountPermissions@@ -318,7 +318,7 @@ class PromotionQueryset(models.QuerySet["Promotion"]):PromotionManager = models.Manager.from_queryset(PromotionQueryset)-class Promotion(ModelWithMetadata):+class Promotion(ModelWithMetadata, ModelWithExternalReference):id = models.UUIDField(primary_key=True, editable=False, unique=True, default=uuid4)name = models.CharField(max_length=255)type = models.CharField(diff --git a/saleor/graphql/discount/mutations/promotion/promotion_create.py b/saleor/graphql/discount/mutations/promotion/promotion_create.pyindex 236351da54..86f032b5d2 100644--- a/saleor/graphql/discount/mutations/promotion/promotion_create.py+++ b/saleor/graphql/discount/mutations/promotion/promotion_create.py@@ -16,7 +16,7 @@ from .....webhook.event_types import WebhookEventAsyncTypefrom ....app.dataloaders import get_app_promisefrom ....channel.types import Channelfrom ....core import ResolveInfo-from ....core.descriptions import PREVIEW_FEATURE+from ....core.descriptions import ADDED_IN_323, PREVIEW_FEATUREfrom ....core.doc_category import DOC_CATEGORY_DISCOUNTSfrom ....core.mutations import DeprecatedModelMutationfrom ....core.scalars import JSON, DateTime@@ -72,6 +72,10 @@ class PromotionInput(BaseInputObjectType):description="The start date of the promotion in ISO 8601 format.")end_date = DateTime(description="The end date of the promotion in ISO 8601 format.")+ external_reference = graphene.String(+ description=f"External ID of this promotion.{ADDED_IN_323}",+ required=False,+ )class PromotionCreateInput(PromotionInput):diff --git a/saleor/graphql/discount/mutations/promotion/promotion_delete.py b/saleor/graphql/discount/mutations/promotion/promotion_delete.pyindex 723ecab1e2..fb1d0e0ffb 100644--- a/saleor/graphql/discount/mutations/promotion/promotion_delete.py+++ b/saleor/graphql/discount/mutations/promotion/promotion_delete.py@@ -2,7 +2,7 @@ import graphenefrom django.db import transactionfrom .....discount import models-from .....graphql.core.mutations import ModelDeleteMutation+from .....graphql.core.mutations import ModelDeleteMutation, ModelWithExtRefMutationfrom .....permission.enums import DiscountPermissionsfrom .....product.utils.product import (get_channel_to_products_map_from_rules,@@ -10,6 +10,7 @@ from .....product.utils.product import ()from .....webhook.event_types import WebhookEventAsyncTypefrom ....core import ResolveInfo+from ....core.descriptions import ADDED_IN_323from ....core.doc_category import DOC_CATEGORY_DISCOUNTSfrom ....core.types import Errorfrom ....core.utils import WebhookEventInfo@@ -22,10 +23,14 @@ class PromotionDeleteError(Error):code = PromotionDeleteErrorCode(description="The error code.", required=True)-class PromotionDelete(ModelDeleteMutation):+class PromotionDelete(ModelDeleteMutation, ModelWithExtRefMutation):class Arguments:id = graphene.ID(- required=True, description="The ID of the promotion to remove."+ required=False, description="The ID of the promotion to remove."+ )+ external_reference = graphene.String(+ required=False,+ description=f"External ID of the promotion to remove.{ADDED_IN_323}",)class Meta:@@ -44,9 +49,9 @@ class PromotionDelete(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=Promotion)+ instance = cls.get_instance(info, external_reference=external_reference, id=id)manager = get_plugin_manager_promise(info.context).get()rules = instance.rules.all()channel_to_products_map = get_channel_to_products_map_from_rules(rules)@@ -54,7 +59,9 @@ class PromotionDelete(ModelDeleteMutation):promotion_id = instance.idwith transaction.atomic():- response = super().perform_mutation(root, info, id=id)+ response = super().perform_mutation(+ root, info, id=id, external_reference=external_reference+ )instance.id = promotion_idcls.call_event(manager.promotion_deleted, instance)if channel_to_products_map:diff --git a/saleor/graphql/discount/mutations/promotion/promotion_update.py b/saleor/graphql/discount/mutations/promotion/promotion_update.pyindex 405d19cab8..9c8c5a34a5 100644--- a/saleor/graphql/discount/mutations/promotion/promotion_update.py+++ b/saleor/graphql/discount/mutations/promotion/promotion_update.py@@ -11,8 +11,9 @@ from .....plugins.manager import PluginsManagerfrom .....webhook.event_types import WebhookEventAsyncTypefrom ....app.dataloaders import get_app_promisefrom ....core import ResolveInfo+from ....core.descriptions import ADDED_IN_323from ....core.doc_category import DOC_CATEGORY_DISCOUNTS-from ....core.mutations import DeprecatedModelMutation+from ....core.mutations import ModelWithExtRefMutationfrom ....core.types import Errorfrom ....core.utils import WebhookEventInfofrom ....core.validators import validate_end_is_after_start@@ -36,9 +37,13 @@ class PromotionUpdateInput(PromotionInput):name = graphene.String(description="Promotion name.")-class PromotionUpdate(DeprecatedModelMutation):+class PromotionUpdate(ModelWithExtRefMutation):class Arguments:- id = graphene.ID(required=True, description="ID of the promotion to update.")+ id = graphene.ID(required=False, description="ID of the promotion to update.")+ external_reference = graphene.String(+ required=False,+ description=f"External ID of a promotion to update.{ADDED_IN_323}",+ )input = PromotionUpdateInput(description="Fields required to update a promotion.", required=True)diff --git a/saleor/graphql/discount/resolvers.py b/saleor/graphql/discount/resolvers.pyindex 8a1fd1329a..efeed2385d 100644--- a/saleor/graphql/discount/resolvers.py+++ b/saleor/graphql/discount/resolvers.py@@ -70,6 +70,14 @@ def resolve_promotion(info, id):)+def resolve_promotion_by_external_reference(info, external_reference):+ return (+ models.Promotion.objects.using(get_database_connection_name(info.context))+ .filter(external_reference=external_reference)+ .first()+ )++def resolve_promotions(info) -> QuerySet:return models.Promotion.objects.using(get_database_connection_name(info.context)diff --git a/saleor/graphql/discount/schema.py b/saleor/graphql/discount/schema.pyindex a224f4c704..bcb10000f1 100644--- a/saleor/graphql/discount/schema.py+++ b/saleor/graphql/discount/schema.py@@ -4,12 +4,14 @@ from ...permission.enums import DiscountPermissionsfrom ..core import ResolveInfofrom ..core.connection import create_connection_slice, filter_connection_querysetfrom ..core.descriptions import (+ ADDED_IN_323,DEPRECATED_IN_3X_INPUT,)from ..core.doc_category import DOC_CATEGORY_DISCOUNTSfrom ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.filters import FilterInputObjectTypefrom ..core.utils import from_global_id_or_error+from ..core.validators import validate_one_of_args_is_in_queryfrom ..translations.mutations import (PromotionRuleTranslate,PromotionTranslate,@@ -42,6 +44,7 @@ from .mutations import (from .mutations.bulk_mutations import SaleBulkDelete, VoucherBulkDeletefrom .resolvers import (resolve_promotion,+ resolve_promotion_by_external_reference,resolve_promotions,resolve_sale,resolve_sales,@@ -141,9 +144,13 @@ class DiscountQueries(graphene.ObjectType):promotion = PermissionsField(Promotion,id=graphene.Argument(- graphene.ID, description="ID of the promotion.", required=True+ graphene.ID, description="ID of the promotion.", required=False),- description="Look up a promotion by ID.",+ external_reference=graphene.Argument(+ graphene.String,+ description=f"External ID of the promotion.{ADDED_IN_323}",+ ),+ description="Look up a promotion by ID or external reference.",permissions=[DiscountPermissions.MANAGE_DISCOUNTS,],@@ -189,9 +196,16 @@ class DiscountQueries(graphene.ObjectType):return create_connection_slice(qs, info, kwargs, VoucherCountableConnection)@staticmethod- def resolve_promotion(_root, info, *, id, channel=None):- _, id = from_global_id_or_error(id, Promotion)- return resolve_promotion(info, id)+ def resolve_promotion(+ _root, info, *, id=None, external_reference=None, channel=None+ ):+ validate_one_of_args_is_in_query(+ "id", id, "external_reference", external_reference+ )+ if id:+ _, id = from_global_id_or_error(id, Promotion)+ return resolve_promotion(info, id)+ return resolve_promotion_by_external_reference(info, external_reference)@staticmethoddef resolve_promotions(_root, info: ResolveInfo, **kwargs):diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_create.py b/saleor/graphql/discount/tests/mutations/test_promotion_create.pyindex dae04d1d02..d909675ca7 100644--- a/saleor/graphql/discount/tests/mutations/test_promotion_create.py+++ b/saleor/graphql/discount/tests/mutations/test_promotion_create.py@@ -3,6 +3,7 @@ from decimal import Decimalfrom unittest.mock import ANY, patchimport graphene+import pytestfrom django.test import override_settingsfrom django.utils import timezonefrom freezegun import freeze_time@@ -10,7 +11,11 @@ from freezegun import freeze_timefrom .....discount import PromotionEventsfrom .....discount.error_codes import PromotionCreateErrorCodefrom .....discount.models import Promotion, PromotionEvent-from ....tests.utils import assert_no_permission, get_graphql_content+from ....tests.utils import (+ assert_no_permission,+ get_graphql_content,+ get_graphql_content_from_response,+)from ...enums import PromotionTypeEnum, RewardTypeEnum, RewardValueTypeEnumPROMOTION_CREATE_MUTATION = """@@ -58,6 +63,187 @@ PROMOTION_CREATE_MUTATION = """"""+CREATE_PROMOTION_WITH_EXTERNAL_REFERENCE_MUTATION = """+ mutation createPromotion($name: String!, $externalReference: String) {+ promotionCreate(+ input: {+ name: $name+ type: CATALOGUE+ externalReference: $externalReference+ }+ ) {+ promotion {+ name+ externalReference+ }+ errors {+ field+ message+ code+ }+ }+ }+"""+++ ("_case", "external_reference"),+ [+ ("non_empty", "test-ext-ref"),+ ("empty_string", ""),+ ],+)+def test_with_external_reference(+ _case, external_reference, staff_api_client, permission_manage_discounts+):+ # given+ name = "test-promotion"+ variables = {"name": name, "externalReference": external_reference}++ # when+ response = staff_api_client.post_graphql(+ CREATE_PROMOTION_WITH_EXTERNAL_REFERENCE_MUTATION,+ variables,+ permissions=[permission_manage_discounts],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["promotionCreate"]+ assert data["errors"] == []+ assert data["promotion"]["externalReference"] == external_reference+ promotion = Promotion.objects.get(name=name)+ assert promotion.external_reference == external_reference+++ ("_case", "external_reference"),+ [+ ("non_empty", "test-ext-ref"),+ ("empty_string", ""),+ ],+)+def test_with_non_unique_external_reference(+ _case,+ external_reference,+ staff_api_client,+ catalogue_promotion,+ permission_manage_discounts,+):+ # given+ catalogue_promotion.external_reference = external_reference+ catalogue_promotion.save(update_fields=["external_reference"])++ name = "new-promotion"+ variables = {"name": name, "externalReference": external_reference}++ # when+ response = staff_api_client.post_graphql(+ CREATE_PROMOTION_WITH_EXTERNAL_REFERENCE_MUTATION,+ variables,+ permissions=[permission_manage_discounts],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["promotionCreate"]+ assert data["promotion"] is None+ assert Promotion.objects.filter(name=name).exists() is False+ errors = data["errors"]+ assert len(errors) == 1+ assert (+ errors[0]["message"] == "Promotion with this External reference already exists."+ )+ assert errors[0]["field"] == "externalReference"+ assert errors[0]["code"] == PromotionCreateErrorCode.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,+ permission_manage_discounts,+ mocker,+):+ # given+ client = request.getfixturevalue(client_fixture)+ name = "Changed promotion"+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.promotion_created")+ variables = {"name": name, "externalReference": "new-reference"}++ # when+ response = client.post_graphql(+ CREATE_PROMOTION_WITH_EXTERNAL_REFERENCE_MUTATION,+ variables,+ permissions=[permission_manage_discounts] if is_allowed else [],+ check_no_permissions=False,+ )++ # then+ if is_allowed:+ data = get_graphql_content(response)["data"]["promotionCreate"]+ assert data["errors"] == []+ created = Promotion.objects.get(external_reference="new-reference")+ assert created.name == name+ assert data["promotion"] == {+ "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"] == {"promotionCreate": None}+ assert len(content["errors"]) == 1+ assert content["errors"][0]["path"] == ["promotionCreate"]+ assert content["errors"][0]["message"] == (+ "To access this path, you need one of the following permissions: MANAGE_DISCOUNTS"+ )+ assert Promotion.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,+ permission_manage_discounts,+):+ # given+ name = "Promotion without reference"+ variables = {"name": name, **reference_input}++ # when+ response = staff_api_client.post_graphql(+ CREATE_PROMOTION_WITH_EXTERNAL_REFERENCE_MUTATION,+ variables,+ permissions=[permission_manage_discounts],+ )++ # then+ data = get_graphql_content(response)["data"]["promotionCreate"]+ assert data["errors"] == []+ assert data["promotion"] == {"name": name, "externalReference": None}+ created = Promotion.objects.get(name=name)+ assert created.external_reference is None++@freeze_time("2020-03-18 12:00:00")@patch("saleor.plugins.manager.PluginsManager.promotion_started")@patch("saleor.plugins.manager.PluginsManager.promotion_created")diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_delete.py b/saleor/graphql/discount/tests/mutations/test_promotion_delete.pyindex 3c7b512476..73c3a2fb33 100644--- a/saleor/graphql/discount/tests/mutations/test_promotion_delete.py+++ b/saleor/graphql/discount/tests/mutations/test_promotion_delete.py@@ -3,9 +3,14 @@ from unittest.mock import patchimport grapheneimport pytest-from .....discount.models import PromotionRule+from .....discount.error_codes import PromotionDeleteErrorCode+from .....discount.models import Promotion, PromotionRulefrom .....product.models import ProductChannelListing-from ....tests.utils import assert_no_permission, get_graphql_content+from ....tests.utils import (+ assert_no_permission,+ get_graphql_content,+ get_graphql_content_from_response,+)from ...utils import get_products_for_promotionPROMOTION_DELETE_MUTATION = """@@ -25,6 +30,202 @@ PROMOTION_DELETE_MUTATION = """"""+DELETE_PROMOTION_BY_EXTERNAL_REFERENCE_MUTATION = """+ mutation deletePromotion($id: ID, $externalReference: String) {+ promotionDelete(id: $id, externalReference: $externalReference) {+ promotion {+ name+ externalReference+ }+ errors {+ field+ message+ code+ }+ }+ }+"""+++def test_by_external_reference(+ staff_api_client, catalogue_promotion, permission_manage_discounts+):+ # given+ external_reference = "test-ext-ref"+ catalogue_promotion.external_reference = external_reference+ catalogue_promotion.save(update_fields=["external_reference"])+ variables = {"externalReference": external_reference}++ # when+ response = staff_api_client.post_graphql(+ DELETE_PROMOTION_BY_EXTERNAL_REFERENCE_MUTATION,+ variables,+ permissions=[permission_manage_discounts],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["promotionDelete"]+ assert data["errors"] == []+ assert data["promotion"]["name"] == catalogue_promotion.name+ assert data["promotion"]["externalReference"] == external_reference+ assert Promotion.objects.filter(pk=catalogue_promotion.pk).exists() is False+++ ("_case", "with_id", "identifiers", "error_field", "error_code", "message"),+ [+ (+ "omitted",+ False,+ {},+ None,+ PromotionDeleteErrorCode.GRAPHQL_ERROR,+ "At least one of arguments is required: 'id', 'external_reference'.",+ ),+ (+ "null",+ False,+ {"id": None, "externalReference": None},+ None,+ PromotionDeleteErrorCode.GRAPHQL_ERROR,+ "At least one of arguments is required: 'id', 'external_reference'.",+ ),+ (+ "empty",+ False,+ {"externalReference": ""},+ None,+ PromotionDeleteErrorCode.GRAPHQL_ERROR,+ "At least one of arguments is required: 'id', 'external_reference'.",+ ),+ (+ "both",+ True,+ {"externalReference": "existing-reference"},+ None,+ PromotionDeleteErrorCode.GRAPHQL_ERROR,+ "Argument 'id' cannot be combined with 'external_reference'",+ ),+ (+ "not_found",+ False,+ {"externalReference": "missing-reference"},+ "externalReference",+ PromotionDeleteErrorCode.NOT_FOUND,+ "Couldn't resolve to a node: missing-reference",+ ),+ ],+)+def test_external_reference_invalid_identifiers(+ _case,+ with_id,+ identifiers,+ error_field,+ error_code,+ message,+ staff_api_client,+ catalogue_promotion,+ permission_manage_discounts,+ mocker,+):+ # given+ catalogue_promotion.external_reference = "existing-reference"+ catalogue_promotion.save(update_fields=("external_reference",))+ original_name = catalogue_promotion.name+ original_reference = catalogue_promotion.external_reference+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.promotion_deleted")+ variables = dict(identifiers)+ if with_id:+ variables["id"] = graphene.Node.to_global_id(+ "Promotion", catalogue_promotion.pk+ )++ # when+ response = staff_api_client.post_graphql(+ DELETE_PROMOTION_BY_EXTERNAL_REFERENCE_MUTATION,+ variables,+ permissions=[permission_manage_discounts],+ check_no_permissions=False,+ )++ # then+ data = get_graphql_content(response)["data"]["promotionDelete"]+ assert data["promotion"] is None+ assert len(data["errors"]) == 1+ assert data["errors"][0] == {+ "field": error_field,+ "code": error_code.name,+ "message": message,+ }+ catalogue_promotion.refresh_from_db(fields=("name", "external_reference"))+ assert catalogue_promotion.name == original_name+ assert catalogue_promotion.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,+ catalogue_promotion,+ permission_manage_discounts,+ mocker,+):+ # given+ client = request.getfixturevalue(client_fixture)+ catalogue_promotion.external_reference = "existing-reference"+ catalogue_promotion.save(update_fields=("external_reference",))+ original_name = catalogue_promotion.name+ original_reference = catalogue_promotion.external_reference+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.promotion_deleted")+ variables = {"externalReference": original_reference}++ # when+ response = client.post_graphql(+ DELETE_PROMOTION_BY_EXTERNAL_REFERENCE_MUTATION,+ variables,+ permissions=[permission_manage_discounts] if is_allowed else [],+ check_no_permissions=False,+ )++ # then+ if is_allowed:+ data = get_graphql_content(response)["data"]["promotionDelete"]+ assert data["errors"] == []+ assert Promotion.objects.filter(pk=catalogue_promotion.pk).exists() is False+ assert data["promotion"] == {+ "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"] == {"promotionDelete": None}+ assert len(content["errors"]) == 1+ assert content["errors"][0]["path"] == ["promotionDelete"]+ assert content["errors"][0]["message"] == (+ "To access this path, you need one of the following permissions: MANAGE_DISCOUNTS"+ )+ catalogue_promotion.refresh_from_db(fields=("name", "external_reference"))+ assert catalogue_promotion.name == original_name+ assert catalogue_promotion.external_reference == original_reference+ webhook.assert_not_called()++@patch("saleor.plugins.manager.PluginsManager.promotion_deleted")def test_promotion_delete_by_staff_user(promotion_deleted_mock,diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_update.py b/saleor/graphql/discount/tests/mutations/test_promotion_update.pyindex 51a6275037..98bc0491dc 100644--- a/saleor/graphql/discount/tests/mutations/test_promotion_update.py+++ b/saleor/graphql/discount/tests/mutations/test_promotion_update.py@@ -2,13 +2,18 @@ import datetimefrom unittest.mock import patchimport graphene+import pytestfrom django.utils import timezonefrom freezegun import freeze_timefrom .....discount import PromotionEvents-from .....discount.error_codes import PromotionCreateErrorCode+from .....discount.error_codes import PromotionCreateErrorCode, PromotionUpdateErrorCodefrom .....discount.models import PromotionEvent-from ....tests.utils import assert_no_permission, get_graphql_content+from ....tests.utils import (+ assert_no_permission,+ get_graphql_content,+ get_graphql_content_from_response,+)PROMOTION_UPDATE_MUTATION = """mutation promotionUpdate($id: ID!, $input: PromotionUpdateInput!) {@@ -37,6 +42,292 @@ PROMOTION_UPDATE_MUTATION = """"""+MUTATION_UPDATE_PROMOTION_BY_EXTERNAL_REFERENCE = """+ mutation updatePromotion(+ $id: ID, $externalReference: String, $input: PromotionUpdateInput!+ ) {+ promotionUpdate(+ id: $id, externalReference: $externalReference, input: $input+ ) {+ errors {+ message+ field+ code+ }+ promotion {+ name+ externalReference+ }+ }+ }+"""+++def test_by_external_reference(+ staff_api_client, catalogue_promotion, permission_manage_discounts+):+ # given+ external_reference = "test-ext-ref"+ catalogue_promotion.external_reference = external_reference+ catalogue_promotion.save(update_fields=["external_reference"])+ name = "New name"+ variables = {+ "externalReference": external_reference,+ "input": {"name": name},+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_PROMOTION_BY_EXTERNAL_REFERENCE,+ variables=variables,+ permissions=[permission_manage_discounts],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["promotionUpdate"]+ assert data["errors"] == []+ catalogue_promotion.refresh_from_db(fields=("name", "external_reference"))+ assert data["promotion"]["name"] == name+ assert catalogue_promotion.name == name+ assert catalogue_promotion.external_reference == external_reference+++def test_with_non_unique_external_reference(+ staff_api_client, catalogue_promotion, promotion_list, permission_manage_discounts+):+ # given+ external_reference = "test-ext-ref"+ other_promotion = promotion_list[0]+ other_promotion.external_reference = external_reference+ other_promotion.save(update_fields=["external_reference"])++ variables = {+ "id": graphene.Node.to_global_id("Promotion", catalogue_promotion.pk),+ "input": {"externalReference": external_reference},+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_PROMOTION_BY_EXTERNAL_REFERENCE,+ variables=variables,+ permissions=[permission_manage_discounts],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["promotionUpdate"]+ catalogue_promotion.refresh_from_db(fields=("external_reference",))+ assert catalogue_promotion.external_reference is None+ assert data["promotion"] is None+ errors = data["errors"]+ assert len(errors) == 1+ assert (+ errors[0]["message"] == "Promotion with this External reference already exists."+ )+ assert errors[0]["field"] == "externalReference"+ assert errors[0]["code"] == PromotionUpdateErrorCode.UNIQUE.name+++ ("_case", "with_id", "identifiers", "error_field", "error_code", "message"),+ [+ (+ "omitted",+ False,+ {},+ None,+ PromotionUpdateErrorCode.GRAPHQL_ERROR,+ "At least one of arguments is required: 'id', 'external_reference'.",+ ),+ (+ "null",+ False,+ {"id": None, "externalReference": None},+ None,+ PromotionUpdateErrorCode.GRAPHQL_ERROR,+ "At least one of arguments is required: 'id', 'external_reference'.",+ ),+ (+ "empty",+ False,+ {"externalReference": ""},+ None,+ PromotionUpdateErrorCode.GRAPHQL_ERROR,+ "At least one of arguments is required: 'id', 'external_reference'.",+ ),+ (+ "both",+ True,+ {"externalReference": "existing-reference"},+ None,+ PromotionUpdateErrorCode.GRAPHQL_ERROR,+ "Argument 'id' cannot be combined with 'external_reference'",+ ),+ (+ "not_found",+ False,+ {"externalReference": "missing-reference"},+ "externalReference",+ PromotionUpdateErrorCode.NOT_FOUND,+ "Couldn't resolve to a node: missing-reference",+ ),+ ],+)+def test_external_reference_invalid_identifiers(+ _case,+ with_id,+ identifiers,+ error_field,+ error_code,+ message,+ staff_api_client,+ catalogue_promotion,+ permission_manage_discounts,+ mocker,+):+ # given+ catalogue_promotion.external_reference = "existing-reference"+ catalogue_promotion.save(update_fields=("external_reference",))+ original_name = catalogue_promotion.name+ original_reference = catalogue_promotion.external_reference+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.promotion_updated")+ variables = dict(identifiers)+ if with_id:+ variables["id"] = graphene.Node.to_global_id(+ "Promotion", catalogue_promotion.pk+ )+ variables["input"] = {"name": "Changed name"}++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_PROMOTION_BY_EXTERNAL_REFERENCE,+ variables,+ permissions=[permission_manage_discounts],+ check_no_permissions=False,+ )++ # then+ data = get_graphql_content(response)["data"]["promotionUpdate"]+ assert data["promotion"] is None+ assert len(data["errors"]) == 1+ assert data["errors"][0] == {+ "field": error_field,+ "code": error_code.name,+ "message": message,+ }+ catalogue_promotion.refresh_from_db(fields=("name", "external_reference"))+ assert catalogue_promotion.name == original_name+ assert catalogue_promotion.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,+ catalogue_promotion,+ permission_manage_discounts,+ mocker,+):+ # given+ client = request.getfixturevalue(client_fixture)+ catalogue_promotion.external_reference = "existing-reference"+ catalogue_promotion.save(update_fields=("external_reference",))+ original_name = catalogue_promotion.name+ original_reference = catalogue_promotion.external_reference+ name = "Changed promotion"+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.promotion_updated")+ variables = {"externalReference": original_reference, "input": {"name": name}}++ # when+ response = client.post_graphql(+ MUTATION_UPDATE_PROMOTION_BY_EXTERNAL_REFERENCE,+ variables,+ permissions=[permission_manage_discounts] if is_allowed else [],+ check_no_permissions=False,+ )++ # then+ if is_allowed:+ data = get_graphql_content(response)["data"]["promotionUpdate"]+ assert data["errors"] == []+ catalogue_promotion.refresh_from_db(fields=("name", "external_reference"))+ assert catalogue_promotion.name == name+ assert catalogue_promotion.external_reference == original_reference+ assert data["promotion"] == {+ "name": name,+ "externalReference": original_reference,+ }+ webhook.assert_called_once()+ else:+ assert_no_permission(response)+ content = get_graphql_content_from_response(response)+ assert content["data"] == {"promotionUpdate": None}+ assert len(content["errors"]) == 1+ assert content["errors"][0]["path"] == ["promotionUpdate"]+ assert content["errors"][0]["message"] == (+ "To access this path, you need one of the following permissions: MANAGE_DISCOUNTS"+ )+ catalogue_promotion.refresh_from_db(fields=("name", "external_reference"))+ assert catalogue_promotion.name == original_name+ assert catalogue_promotion.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,+ catalogue_promotion,+ permission_manage_discounts,+):+ # given+ catalogue_promotion.external_reference = "original-reference"+ catalogue_promotion.save(update_fields=("external_reference",))+ name = "Updated promotion"+ variables = {+ "externalReference": catalogue_promotion.external_reference,+ "input": {"name": name, **reference_input},+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_PROMOTION_BY_EXTERNAL_REFERENCE,+ variables,+ permissions=[permission_manage_discounts],+ )++ # then+ data = get_graphql_content(response)["data"]["promotionUpdate"]+ assert data["errors"] == []+ assert data["promotion"] == {"name": name, "externalReference": expected_reference}+ catalogue_promotion.refresh_from_db(fields=("name", "external_reference"))+ assert catalogue_promotion.name == name+ assert catalogue_promotion.external_reference == expected_reference++@freeze_time("2020-03-18 12:00:00")@patch("saleor.plugins.manager.PluginsManager.promotion_started")@patch("saleor.plugins.manager.PluginsManager.promotion_updated")diff --git a/saleor/graphql/discount/tests/queries/test_promotion.py b/saleor/graphql/discount/tests/queries/test_promotion.pyindex f21e8c134c..dda60dc539 100644--- a/saleor/graphql/discount/tests/queries/test_promotion.py+++ b/saleor/graphql/discount/tests/queries/test_promotion.py@@ -6,7 +6,11 @@ import graphenefrom .....discount import PromotionEvents, RewardType, RewardValueTypefrom .....tests.utils import dummy_editorjs-from ....tests.utils import assert_no_permission, get_graphql_content+from ....tests.utils import (+ assert_no_permission,+ get_graphql_content,+ get_graphql_content_from_response,+)QUERY_PROMOTION_BY_ID = """query Promotion($id: ID!) {@@ -67,6 +71,131 @@ def _assert_promotion_data(promotion, content_data):assert rule_data in promotion_data["rules"]+QUERY_PROMOTION_BY_EXTERNAL_REFERENCE = """+ query ($id: ID, $externalReference: String) {+ promotion(+ id: $id,+ externalReference: $externalReference,+ ) {+ id+ name+ externalReference+ }+ }+ """+++def test_query_promotion_by_external_reference(+ staff_api_client, catalogue_promotion, permission_manage_discounts+):+ # given+ external_reference = "test-ext-ref"+ catalogue_promotion.external_reference = external_reference+ catalogue_promotion.save(update_fields=("external_reference",))+ variables = {"externalReference": external_reference}++ # when+ response = staff_api_client.post_graphql(+ QUERY_PROMOTION_BY_EXTERNAL_REFERENCE,+ variables,+ permissions=[permission_manage_discounts],+ )++ # then+ content = get_graphql_content(response)+ assert content["data"] == {+ "promotion": {+ "id": graphene.Node.to_global_id("Promotion", catalogue_promotion.pk),+ "name": catalogue_promotion.name,+ "externalReference": external_reference,+ }+ }+++def test_query_promotion_by_external_reference_not_found(+ staff_api_client, permission_manage_discounts+):+ # given+ variables = {"externalReference": "non-existing-ext-ref"}++ # when+ response = staff_api_client.post_graphql(+ QUERY_PROMOTION_BY_EXTERNAL_REFERENCE,+ variables,+ permissions=[permission_manage_discounts],+ )++ # then+ content = get_graphql_content(response)+ assert content["data"] == {"promotion": None}+++def test_query_promotion_by_empty_string_external_reference(+ staff_api_client, catalogue_promotion, permission_manage_discounts+):+ """An empty string is treated as a missing argument, so it can't be looked up."""+ # given+ external_reference = ""+ catalogue_promotion.external_reference = external_reference+ catalogue_promotion.save(update_fields=("external_reference",))+ variables = {"externalReference": external_reference}++ # when+ response = staff_api_client.post_graphql(+ QUERY_PROMOTION_BY_EXTERNAL_REFERENCE,+ variables,+ permissions=[permission_manage_discounts],+ )++ # then+ content = get_graphql_content_from_response(response)+ assert content["data"] == {"promotion": None}+ assert len(content["errors"]) == 1+ assert content["errors"][0]["message"] == (+ "At least one of arguments is required: 'id', 'external_reference'."+ )+ assert content["errors"][0]["path"] == ["promotion"]+++def test_query_promotion_by_external_reference_no_permission(+ api_client, catalogue_promotion+):+ # given+ variables = {"externalReference": "non-existing-ext-ref"}++ # when+ response = api_client.post_graphql(QUERY_PROMOTION_BY_EXTERNAL_REFERENCE, variables)++ # then+ assert_no_permission(response)+++def test_query_promotion_external_reference_conflicting_identifiers(+ staff_api_client, catalogue_promotion, permission_manage_discounts+):+ # given+ variables = {+ "id": graphene.Node.to_global_id("Promotion", catalogue_promotion.pk),+ "externalReference": "promotion-reference",+ }++ # when+ response = staff_api_client.post_graphql(+ QUERY_PROMOTION_BY_EXTERNAL_REFERENCE,+ variables,+ permissions=[permission_manage_discounts],+ )++ # then+ content = get_graphql_content_from_response(response)+ assert content["data"] == {"promotion": None}+ assert len(content["errors"]) == 1+ assert content["errors"][0]["message"] == (+ "Argument 'id' cannot be combined with 'external_reference'"+ )+ assert content["errors"][0]["path"] == ["promotion"]++def test_query_promotion_by_id_by_staff_user(catalogue_promotion, staff_api_client, permission_group_manage_discounts):diff --git a/saleor/graphql/discount/types/promotions.py b/saleor/graphql/discount/types/promotions.pyindex 0be09059d2..f73c10ed42 100644--- a/saleor/graphql/discount/types/promotions.py+++ b/saleor/graphql/discount/types/promotions.py@@ -6,7 +6,7 @@ from ....permission.auth_filters import AuthorizationFiltersfrom ...channel.types import Channelfrom ...core import ResolveInfofrom ...core.connection import CountableConnection-from ...core.descriptions import PREVIEW_FEATURE+from ...core.descriptions import ADDED_IN_323, PREVIEW_FEATUREfrom ...core.doc_category import DOC_CATEGORY_DISCOUNTSfrom ...core.fields import PermissionsFieldfrom ...core.scalars import JSON, DateTime, PositiveDecimal@@ -28,6 +28,9 @@ from .promotion_events import PromotionEventclass Promotion(ModelObjectType[models.Promotion]):id = graphene.GlobalID(required=True)name = graphene.String(required=True, description="Name of the promotion.")+ external_reference = graphene.String(+ description=f"External ID of this promotion.{ADDED_IN_323}"+ )type = PromotionTypeEnum(description=("The type of the promotion. Implicate if the discount is applied on "diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex da4a404e4a..953db20048 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1200,13 +1200,20 @@ type Query {): VoucherCountableConnection @doc(category: "Discounts")"""- Look up a promotion by ID.+ Look up a promotion by ID or external reference.Requires one of the following permissions: MANAGE_DISCOUNTS."""promotion("""ID of the promotion."""- id: ID!+ id: ID++ """+ External ID of the promotion.++ Added in Saleor 3.23.+ """+ externalReference: String): Promotion @doc(category: "Discounts")"""@@ -16821,6 +16828,13 @@ type Promotion implements Node & ObjectWithMetadata @doc(category: "Discounts")"""Name of the promotion."""name: String!+ """+ External ID of this promotion.++ Added in Saleor 3.23.+ """+ externalReference: String+"""The type of the promotion. Implicate if the discount is applied on catalogue or order level.@@ -20632,8 +20646,15 @@ type Mutation {- PROMOTION_ENDED (async): Optionally called if promotion was ended."""promotionUpdate(+ """+ External ID of a promotion to update.++ Added in Saleor 3.23.+ """+ externalReference: String+"""ID of the promotion to update."""- id: ID!+ id: ID"""Fields required to update a promotion."""input: PromotionUpdateInput!@@ -20648,8 +20669,15 @@ type Mutation {- PROMOTION_DELETED (async): A promotion was deleted."""promotionDelete(+ """+ External ID of the promotion to remove.++ Added in Saleor 3.23.+ """+ externalReference: String+"""The ID of the promotion to remove."""- id: ID!+ id: ID): PromotionDelete @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [PROMOTION_DELETED], syncEvents: [])"""@@ -29888,6 +29916,7 @@ enum PromotionCreateErrorCode {NOT_FOUNDREQUIREDINVALID+ UNIQUEMULTIPLE_CURRENCIES_NOT_ALLOWEDINVALID_PRECISIONMISSING_CHANNELS@@ -29906,6 +29935,13 @@ input PromotionCreateInput @doc(category: "Discounts") {"""The end date of the promotion in ISO 8601 format."""endDate: DateTime+ """+ External ID of this promotion.++ Added in Saleor 3.23.+ """+ externalReference: String+"""Promotion name."""name: String!@@ -30043,6 +30079,7 @@ enum PromotionUpdateErrorCode {NOT_FOUNDREQUIREDINVALID+ UNIQUE}input PromotionUpdateInput {@@ -30055,6 +30092,13 @@ input PromotionUpdateInput {"""The end date of the promotion in ISO 8601 format."""endDate: DateTime+ """+ External ID of this promotion.++ Added in Saleor 3.23.+ """+ externalReference: String+"""Promotion name."""name: String}