Skip to content

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

Add externalReference support to Voucher (#19893)

DamianCzajkowskie5e4625a231d
diff --git a/saleor/discount/migrations/0090_voucher_external_reference.py b/saleor/discount/migrations/0090_voucher_external_reference.py
new file mode 100644
index 0000000000..cf8ac8fe05
--- /dev/null
+++ b/saleor/discount/migrations/0090_voucher_external_reference.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("discount", "0089_promotion_external_reference_unique_constraint"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="voucher",
+ name="external_reference",
+ field=models.CharField(blank=True, max_length=250, null=True),
+ ),
+ ]
diff --git a/saleor/discount/migrations/0091_voucher_external_reference_unique_constraint.py b/saleor/discount/migrations/0091_voucher_external_reference_unique_constraint.py
new file mode 100644
index 0000000000..d0e2f46ad7
--- /dev/null
+++ b/saleor/discount/migrations/0091_voucher_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_voucher while it is created. CONCURRENTLY
+ # cannot run inside a transaction, hence atomic = False and its own
+ # migration, separate from the fast, atomic AddField in 0090.
+ atomic = False
+
+ dependencies = [
+ ("discount", "0090_voucher_external_reference"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ database_operations=[
+ migrations.RunSQL(
+ sql="""
+ CREATE UNIQUE INDEX CONCURRENTLY voucher_external_reference_key
+ ON discount_voucher ("external_reference");
+ """,
+ reverse_sql="""
+ DROP INDEX CONCURRENTLY IF EXISTS voucher_external_reference_key;
+ """,
+ ),
+ migrations.RunSQL(
+ sql="""
+ ALTER TABLE discount_voucher
+ ADD CONSTRAINT voucher_external_reference_key
+ UNIQUE USING INDEX voucher_external_reference_key;
+ """,
+ reverse_sql="""
+ ALTER TABLE discount_voucher DROP CONSTRAINT
+ IF EXISTS voucher_external_reference_key;
+ """,
+ ),
+ ],
+ state_operations=[
+ migrations.AlterField(
+ model_name="voucher",
+ 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.py
index 1df4d54132..b17a9d8b18 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -119,7 +119,7 @@ class VoucherQueryset(models.QuerySet["Voucher"]):
VoucherManager = models.Manager.from_queryset(VoucherQueryset)
-class Voucher(ModelWithMetadata):
+class Voucher(ModelWithMetadata, ModelWithExternalReference):
type = models.CharField(
max_length=20, choices=VoucherType.CHOICES, default=VoucherType.ENTIRE_ORDER
)
diff --git a/saleor/graphql/discount/mutations/voucher/voucher_create.py b/saleor/graphql/discount/mutations/voucher/voucher_create.py
index 73d4abbefd..16d16d9ea6 100644
--- a/saleor/graphql/discount/mutations/voucher/voucher_create.py
+++ b/saleor/graphql/discount/mutations/voucher/voucher_create.py
@@ -10,6 +10,7 @@ from .....webhook.event_types import WebhookEventAsyncType
from ....core import ResolveInfo
from ....core.context import ChannelContext
from ....core.descriptions import (
+ ADDED_IN_323,
DEPRECATED_IN_3X_INPUT,
PREVIEW_FEATURE,
)
@@ -33,6 +34,10 @@ class VoucherInput(BaseInputObjectType):
description="Voucher type: PRODUCT, CATEGORY SHIPPING or ENTIRE_ORDER."
)
name = graphene.String(description="Voucher name.")
+ external_reference = graphene.String(
+ description=f"External ID of this voucher.{ADDED_IN_323}",
+ required=False,
+ )
code = graphene.String(
required=False,
description="Code to use the voucher. "
diff --git a/saleor/graphql/discount/mutations/voucher/voucher_delete.py b/saleor/graphql/discount/mutations/voucher/voucher_delete.py
index 343b681485..3287ecb28a 100644
--- a/saleor/graphql/discount/mutations/voucher/voucher_delete.py
+++ b/saleor/graphql/discount/mutations/voucher/voucher_delete.py
@@ -6,16 +6,21 @@ from .....permission.enums import DiscountPermissions
from .....webhook.event_types import WebhookEventAsyncType
from ....core import ResolveInfo
from ....core.context import ChannelContext
-from ....core.mutations import ModelDeleteMutation
+from ....core.descriptions import ADDED_IN_323
+from ....core.mutations import ModelDeleteMutation, ModelWithExtRefMutation
from ....core.types import DiscountError
from ....core.utils import WebhookEventInfo
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import Voucher
-class VoucherDelete(ModelDeleteMutation):
+class VoucherDelete(ModelDeleteMutation, ModelWithExtRefMutation):
class Arguments:
- id = graphene.ID(required=True, description="ID of a voucher to delete.")
+ id = graphene.ID(required=False, description="ID of a voucher to delete.")
+ external_reference = graphene.String(
+ required=False,
+ description=f"External ID of a voucher to delete.{ADDED_IN_323}",
+ )
class Meta:
description = "Deletes a voucher."
diff --git a/saleor/graphql/discount/mutations/voucher/voucher_update.py b/saleor/graphql/discount/mutations/voucher/voucher_update.py
index 82a2a6e125..4376095916 100644
--- a/saleor/graphql/discount/mutations/voucher/voucher_update.py
+++ b/saleor/graphql/discount/mutations/voucher/voucher_update.py
@@ -10,6 +10,8 @@ from .....order import models as order_models
from .....permission.enums import DiscountPermissions
from .....webhook.event_types import WebhookEventAsyncType
from ....core import ResolveInfo
+from ....core.descriptions import ADDED_IN_323
+from ....core.mutations import ModelWithExtRefMutation
from ....core.types import DiscountError
from ....core.utils import WebhookEventInfo
from ....plugins.dataloaders import get_plugin_manager_promise
@@ -17,9 +19,13 @@ from ...types import Voucher
from .voucher_create import VoucherCreate, VoucherInput
-class VoucherUpdate(VoucherCreate):
+class VoucherUpdate(VoucherCreate, ModelWithExtRefMutation):
class Arguments:
- id = graphene.ID(required=True, description="ID of a voucher to update.")
+ id = graphene.ID(required=False, description="ID of a voucher to update.")
+ external_reference = graphene.String(
+ required=False,
+ description=f"External ID of a voucher to update.{ADDED_IN_323}",
+ )
input = VoucherInput(
required=True, description="Fields required to update a voucher."
)
diff --git a/saleor/graphql/discount/resolvers.py b/saleor/graphql/discount/resolvers.py
index efeed2385d..b1b803f2de 100644
--- a/saleor/graphql/discount/resolvers.py
+++ b/saleor/graphql/discount/resolvers.py
@@ -19,6 +19,15 @@ def resolve_voucher(info, id, channel):
return ChannelContext(node=sale, channel_slug=channel) if sale else None
+def resolve_voucher_by_external_reference(info, external_reference, channel):
+ voucher = (
+ models.Voucher.objects.using(get_database_connection_name(info.context))
+ .filter(external_reference=external_reference)
+ .first()
+ )
+ return ChannelContext(node=voucher, channel_slug=channel) if voucher else None
+
+
def resolve_vouchers(info, channel_slug, **kwargs) -> ChannelQsContext:
qs = models.Voucher.objects.using(get_database_connection_name(info.context)).all()
if channel_slug:
diff --git a/saleor/graphql/discount/schema.py b/saleor/graphql/discount/schema.py
index bcb10000f1..7710fc08e7 100644
--- a/saleor/graphql/discount/schema.py
+++ b/saleor/graphql/discount/schema.py
@@ -49,6 +49,7 @@ from .resolvers import (
resolve_sale,
resolve_sales,
resolve_voucher,
+ resolve_voucher_by_external_reference,
resolve_vouchers,
)
from .sorters import PromotionSortingInput, SaleSortingInput, VoucherSortingInput
@@ -111,12 +112,16 @@ class DiscountQueries(graphene.ObjectType):
voucher = PermissionsField(
Voucher,
id=graphene.Argument(
- graphene.ID, description="ID of the voucher.", required=True
+ graphene.ID, description="ID of the voucher.", required=False
+ ),
+ external_reference=graphene.Argument(
+ graphene.String,
+ description=f"External ID of the voucher.{ADDED_IN_323}",
),
channel=graphene.String(
description="Slug of a channel for which the data should be returned."
),
- description="Look up a voucher by ID.",
+ description="Look up a voucher by ID or external reference.",
permissions=[
DiscountPermissions.MANAGE_DISCOUNTS,
],
@@ -182,9 +187,21 @@ class DiscountQueries(graphene.ObjectType):
return create_connection_slice(qs, info, kwargs, SaleCountableConnection)
@staticmethod
- def resolve_voucher(_root, info: ResolveInfo, *, id, channel=None):
- _, id = from_global_id_or_error(id, Voucher)
- return resolve_voucher(info, id, channel)
+ def resolve_voucher(
+ _root,
+ info: ResolveInfo,
+ *,
+ 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, Voucher)
+ return resolve_voucher(info, id, channel)
+ return resolve_voucher_by_external_reference(info, external_reference, channel)
@staticmethod
def resolve_vouchers(_root, info: ResolveInfo, *, channel=None, **kwargs):
diff --git a/saleor/graphql/discount/tests/mutations/test_voucher_create.py b/saleor/graphql/discount/tests/mutations/test_voucher_create.py
index ec75eb9fef..c30cb6bbf0 100644
--- a/saleor/graphql/discount/tests/mutations/test_voucher_create.py
+++ b/saleor/graphql/discount/tests/mutations/test_voucher_create.py
@@ -3,6 +3,7 @@ import json
from unittest.mock import call, patch
import graphene
+import pytest
from django.utils import timezone
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
@@ -13,9 +14,190 @@ from .....discount.error_codes import DiscountErrorCode
from .....discount.models import Voucher
from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.payloads import generate_meta, generate_requestor
-from ....tests.utils import get_graphql_content
+from ....tests.utils import (
+ assert_no_permission,
+ get_graphql_content,
+ get_graphql_content_from_response,
+)
from ...enums import DiscountValueTypeEnum, VoucherTypeEnum
+CREATE_VOUCHER_WITH_EXTERNAL_REFERENCE_MUTATION = """
+ mutation createVoucher($name: String, $externalReference: String) {
+ voucherCreate(
+ input: {
+ name: $name
+ addCodes: [""]
+ externalReference: $externalReference
+ }
+ ) {
+ voucher {
+ 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-voucher"
+ variables = {"name": name, "externalReference": external_reference}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_VOUCHER_WITH_EXTERNAL_REFERENCE_MUTATION,
+ variables,
+ permissions=[permission_manage_discounts],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["voucherCreate"]
+ assert data["errors"] == []
+ assert data["voucher"]["externalReference"] == external_reference
+ voucher = Voucher.objects.get(name=name)
+ assert voucher.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, voucher, permission_manage_discounts
+):
+ # given
+ voucher.external_reference = external_reference
+ voucher.save(update_fields=["external_reference"])
+
+ name = "new-voucher"
+ variables = {"name": name, "externalReference": external_reference}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_VOUCHER_WITH_EXTERNAL_REFERENCE_MUTATION,
+ variables,
+ permissions=[permission_manage_discounts],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["voucherCreate"]
+ assert data["voucher"] is None
+ assert Voucher.objects.filter(name=name).exists() is False
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert (
+ errors[0]["message"] == "Voucher with this External reference already exists."
+ )
+ assert errors[0]["field"] == "externalReference"
+ assert errors[0]["code"] == DiscountErrorCode.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 voucher"
+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.voucher_created")
+ variables = {"name": name, "externalReference": "new-reference"}
+
+ # when
+ response = client.post_graphql(
+ CREATE_VOUCHER_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"]["voucherCreate"]
+ assert data["errors"] == []
+ created = Voucher.objects.get(external_reference="new-reference")
+ assert created.name == name
+ assert data["voucher"] == {
+ "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"] == {"voucherCreate": None}
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["path"] == ["voucherCreate"]
+ assert content["errors"][0]["message"] == (
+ "To access this path, you need one of the following permissions: MANAGE_DISCOUNTS"
+ )
+ assert Voucher.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 = "Voucher without reference"
+ variables = {"name": name, **reference_input}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_VOUCHER_WITH_EXTERNAL_REFERENCE_MUTATION,
+ variables,
+ permissions=[permission_manage_discounts],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["voucherCreate"]
+ assert data["errors"] == []
+ assert data["voucher"] == {"name": name, "externalReference": None}
+ created = Voucher.objects.get(name=name)
+ assert created.external_reference is None
+
+
CREATE_VOUCHER_MUTATION = """
mutation voucherCreate($input: VoucherInput!) {
voucherCreate(input: $input) {
diff --git a/saleor/graphql/discount/tests/mutations/test_voucher_delete.py b/saleor/graphql/discount/tests/mutations/test_voucher_delete.py
index f123fe9f40..ace94e8d2a 100644
--- a/saleor/graphql/discount/tests/mutations/test_voucher_delete.py
+++ b/saleor/graphql/discount/tests/mutations/test_voucher_delete.py
@@ -7,9 +7,15 @@ from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
from .....core.utils.json_serializer import CustomJsonEncoder
+from .....discount.error_codes import DiscountErrorCode
+from .....discount.models import Voucher
from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.payloads import generate_meta, generate_requestor
-from ....tests.utils import get_graphql_content
+from ....tests.utils import (
+ assert_no_permission,
+ get_graphql_content,
+ get_graphql_content_from_response,
+)
VOUCHER_DELETE_MUTATION = """
mutation DeleteVoucher($id: ID!) {
@@ -27,6 +33,191 @@ VOUCHER_DELETE_MUTATION = """
}
"""
+DELETE_VOUCHER_BY_EXTERNAL_REFERENCE_MUTATION = """
+ mutation deleteVoucher($id: ID, $externalReference: String) {
+ voucherDelete(id: $id, externalReference: $externalReference) {
+ voucher {
+ name
+ externalReference
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
+def test_by_external_reference(staff_api_client, voucher, permission_manage_discounts):
+ # given
+ external_reference = "test-ext-ref"
+ voucher.external_reference = external_reference
+ voucher.save(update_fields=["external_reference"])
+ variables = {"externalReference": external_reference}
+
+ # when
+ response = staff_api_client.post_graphql(
+ DELETE_VOUCHER_BY_EXTERNAL_REFERENCE_MUTATION,
+ variables,
+ permissions=[permission_manage_discounts],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["voucherDelete"]
+ assert data["errors"] == []
+ assert data["voucher"]["name"] == voucher.name
+ assert data["voucher"]["externalReference"] == external_reference
+ assert Voucher.objects.filter(pk=voucher.pk).exists() is False
+
+
+ ("_case", "identifiers", "error_field", "error_code", "message"),
+ [
+ (
+ "omitted",
+ {},
+ None,
+ DiscountErrorCode.GRAPHQL_ERROR,
+ "At least one of arguments is required: 'id', 'external_reference'.",
+ ),
+ (
+ "null",
+ {"id": None, "externalReference": None},
+ None,
+ DiscountErrorCode.GRAPHQL_ERROR,
+ "At least one of arguments is required: 'id', 'external_reference'.",
+ ),
+ (
+ "empty",
+ {"externalReference": ""},
+ None,
+ DiscountErrorCode.GRAPHQL_ERROR,
+ "At least one of arguments is required: 'id', 'external_reference'.",
+ ),
+ (
+ "both",
+ {"externalReference": "existing-reference"},
+ None,
+ DiscountErrorCode.GRAPHQL_ERROR,
+ "Argument 'id' cannot be combined with 'external_reference'",
+ ),
+ (
+ "not_found",
+ {"externalReference": "missing-reference"},
+ "externalReference",
+ DiscountErrorCode.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,
+ voucher,
+ permission_manage_discounts,
+ mocker,
+):
+ # given
+ voucher.external_reference = "existing-reference"
+ voucher.save(update_fields=("external_reference",))
+ original_name = voucher.name
+ original_reference = voucher.external_reference
+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.voucher_deleted")
+ variables = dict(identifiers)
+ if _case == "both":
+ variables["id"] = graphene.Node.to_global_id("Voucher", voucher.pk)
+
+ # when
+ response = staff_api_client.post_graphql(
+ DELETE_VOUCHER_BY_EXTERNAL_REFERENCE_MUTATION,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["voucherDelete"]
+ assert data["voucher"] is None
+ assert len(data["errors"]) == 1
+ assert data["errors"][0] == {
+ "field": error_field,
+ "code": error_code.name,
+ "message": message,
+ }
+ voucher.refresh_from_db(fields=("name", "external_reference"))
+ assert voucher.name == original_name
+ assert voucher.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,
+ voucher,
+ permission_manage_discounts,
+ mocker,
+):
+ # given
+ client = request.getfixturevalue(client_fixture)
+ voucher.external_reference = "existing-reference"
+ voucher.save(update_fields=("external_reference",))
+ original_name = voucher.name
+ original_reference = voucher.external_reference
+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.voucher_deleted")
+ variables = {"externalReference": original_reference}
+
+ # when
+ response = client.post_graphql(
+ DELETE_VOUCHER_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"]["voucherDelete"]
+ assert data["errors"] == []
+ assert Voucher.objects.filter(pk=voucher.pk).exists() is False
+ assert data["voucher"] == {
+ "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"] == {"voucherDelete": None}
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["path"] == ["voucherDelete"]
+ assert content["errors"][0]["message"] == (
+ "To access this path, you need one of the following permissions: MANAGE_DISCOUNTS"
+ )
+ voucher.refresh_from_db(fields=("name", "external_reference"))
+ assert voucher.name == original_name
+ assert voucher.external_reference == original_reference
+ webhook.assert_not_called()
+
def test_voucher_delete_mutation(
staff_api_client, voucher, permission_manage_discounts
diff --git a/saleor/graphql/discount/tests/mutations/test_voucher_update.py b/saleor/graphql/discount/tests/mutations/test_voucher_update.py
index 1ea110b69f..f8c7f60283 100644
--- a/saleor/graphql/discount/tests/mutations/test_voucher_update.py
+++ b/saleor/graphql/discount/tests/mutations/test_voucher_update.py
@@ -2,6 +2,7 @@ import json
from unittest.mock import call, patch
import graphene
+import pytest
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
@@ -10,9 +11,289 @@ from .....discount import DiscountValueType
from .....discount.error_codes import DiscountErrorCode
from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.payloads import generate_meta, generate_requestor
-from ....tests.utils import get_graphql_content
+from ....tests.utils import (
+ assert_no_permission,
+ get_graphql_content,
+ get_graphql_content_from_response,
+)
from ...enums import DiscountValueTypeEnum
+MUTATION_UPDATE_VOUCHER_BY_EXTERNAL_REFERENCE = """
+ mutation updateVoucher(
+ $id: ID, $externalReference: String, $input: VoucherInput!
+ ) {
+ voucherUpdate(
+ id: $id, externalReference: $externalReference, input: $input
+ ) {
+ errors {
+ message
+ field
+ code
+ }
+ voucher {
+ name
+ externalReference
+ }
+ }
+ }
+"""
+
+
+def test_by_external_reference(staff_api_client, voucher, permission_manage_discounts):
+ # given
+ external_reference = "test-ext-ref"
+ voucher.external_reference = external_reference
+ voucher.save(update_fields=["external_reference"])
+ name = "New name"
+ variables = {
+ "externalReference": external_reference,
+ "input": {"name": name},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_VOUCHER_BY_EXTERNAL_REFERENCE,
+ variables=variables,
+ permissions=[permission_manage_discounts],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["voucherUpdate"]
+ assert data["errors"] == []
+ voucher.refresh_from_db(fields=("name", "external_reference"))
+ assert data["voucher"]["name"] == name
+ assert voucher.name == name
+ assert voucher.external_reference == external_reference
+
+
+def test_with_non_unique_external_reference(
+ staff_api_client, voucher, voucher_list, permission_manage_discounts
+):
+ # given
+ external_reference = "test-ext-ref"
+ other_voucher = voucher_list[0]
+ other_voucher.external_reference = external_reference
+ other_voucher.save(update_fields=["external_reference"])
+
+ variables = {
+ "id": graphene.Node.to_global_id("Voucher", voucher.pk),
+ "input": {"externalReference": external_reference},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_VOUCHER_BY_EXTERNAL_REFERENCE,
+ variables=variables,
+ permissions=[permission_manage_discounts],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["voucherUpdate"]
+ voucher.refresh_from_db(fields=("external_reference",))
+ assert voucher.external_reference is None
+ assert data["voucher"] is None
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert (
+ errors[0]["message"] == "Voucher with this External reference already exists."
+ )
+ assert errors[0]["field"] == "externalReference"
+ assert errors[0]["code"] == DiscountErrorCode.UNIQUE.name
+
+
+ ("_case", "identifiers", "error_field", "error_code", "message"),
+ [
+ (
+ "omitted",
+ {},
+ None,
+ DiscountErrorCode.GRAPHQL_ERROR,
+ "At least one of arguments is required: 'id', 'external_reference'.",
+ ),
+ (
+ "null",
+ {"id": None, "externalReference": None},
+ None,
+ DiscountErrorCode.GRAPHQL_ERROR,
+ "At least one of arguments is required: 'id', 'external_reference'.",
+ ),
+ (
+ "empty",
+ {"externalReference": ""},
+ None,
+ DiscountErrorCode.GRAPHQL_ERROR,
+ "At least one of arguments is required: 'id', 'external_reference'.",
+ ),
+ (
+ "both",
+ {"externalReference": "existing-reference"},
+ None,
+ DiscountErrorCode.GRAPHQL_ERROR,
+ "Argument 'id' cannot be combined with 'external_reference'",
+ ),
+ (
+ "not_found",
+ {"externalReference": "missing-reference"},
+ "externalReference",
+ DiscountErrorCode.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,
+ voucher,
+ permission_manage_discounts,
+ mocker,
+):
+ # given
+ voucher.external_reference = "existing-reference"
+ voucher.save(update_fields=("external_reference",))
+ original_name = voucher.name
+ original_reference = voucher.external_reference
+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.voucher_updated")
+ variables = dict(identifiers)
+ if _case == "both":
+ variables["id"] = graphene.Node.to_global_id("Voucher", voucher.pk)
+ variables["input"] = {"name": "Changed name"}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_VOUCHER_BY_EXTERNAL_REFERENCE,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["voucherUpdate"]
+ assert data["voucher"] is None
+ assert len(data["errors"]) == 1
+ assert data["errors"][0] == {
+ "field": error_field,
+ "code": error_code.name,
+ "message": message,
+ }
+ voucher.refresh_from_db(fields=("name", "external_reference"))
+ assert voucher.name == original_name
+ assert voucher.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,
+ voucher,
+ permission_manage_discounts,
+ mocker,
+):
+ # given
+ client = request.getfixturevalue(client_fixture)
+ voucher.external_reference = "existing-reference"
+ voucher.save(update_fields=("external_reference",))
+ original_name = voucher.name
+ original_reference = voucher.external_reference
+ name = "Changed voucher"
+ webhook = mocker.patch("saleor.plugins.manager.PluginsManager.voucher_updated")
+ variables = {"externalReference": original_reference, "input": {"name": name}}
+
+ # when
+ response = client.post_graphql(
+ MUTATION_UPDATE_VOUCHER_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"]["voucherUpdate"]
+ assert data["errors"] == []
+ voucher.refresh_from_db(fields=("name", "external_reference"))
+ assert voucher.name == name
+ assert voucher.external_reference == original_reference
+ assert data["voucher"] == {
+ "name": name,
+ "externalReference": original_reference,
+ }
+ webhook.assert_called_once()
+ else:
+ assert_no_permission(response)
+ content = get_graphql_content_from_response(response)
+ assert content["data"] == {"voucherUpdate": None}
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["path"] == ["voucherUpdate"]
+ assert content["errors"][0]["message"] == (
+ "To access this path, you need one of the following permissions: MANAGE_DISCOUNTS"
+ )
+ voucher.refresh_from_db(fields=("name", "external_reference"))
+ assert voucher.name == original_name
+ assert voucher.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,
+ voucher,
+ permission_manage_discounts,
+):
+ # given
+ voucher.external_reference = "original-reference"
+ voucher.save(update_fields=("external_reference",))
+ name = "Updated voucher"
+ variables = {
+ "externalReference": voucher.external_reference,
+ "input": {"name": name, **reference_input},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_VOUCHER_BY_EXTERNAL_REFERENCE,
+ variables,
+ permissions=[permission_manage_discounts],
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["voucherUpdate"]
+ assert data["errors"] == []
+ assert data["voucher"] == {"name": name, "externalReference": expected_reference}
+ voucher.refresh_from_db(fields=("name", "external_reference"))
+ assert voucher.name == name
+ assert voucher.external_reference == expected_reference
+
+
UPDATE_VOUCHER_MUTATION = """
mutation voucherUpdate($id: ID!, $input: VoucherInput!) {
voucherUpdate(id: $id, input: $input) {
diff --git a/saleor/graphql/discount/tests/queries/test_voucher.py b/saleor/graphql/discount/tests/queries/test_voucher.py
index 4be5fdaf20..510d946e14 100644
--- a/saleor/graphql/discount/tests/queries/test_voucher.py
+++ b/saleor/graphql/discount/tests/queries/test_voucher.py
@@ -6,6 +6,129 @@ from ....tests.utils import (
get_graphql_content_from_response,
)
+QUERY_VOUCHER_BY_EXTERNAL_REFERENCE = """
+ query ($id: ID, $externalReference: String) {
+ voucher(
+ id: $id,
+ externalReference: $externalReference,
+ ) {
+ id
+ name
+ externalReference
+ }
+ }
+ """
+
+
+def test_voucher_query_by_external_reference(
+ staff_api_client, voucher, permission_manage_discounts
+):
+ # given
+ external_reference = "test-ext-ref"
+ voucher.external_reference = external_reference
+ voucher.save(update_fields=("external_reference",))
+ variables = {"externalReference": external_reference}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_VOUCHER_BY_EXTERNAL_REFERENCE,
+ variables,
+ permissions=[permission_manage_discounts],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"] == {
+ "voucher": {
+ "id": graphene.Node.to_global_id("Voucher", voucher.pk),
+ "name": voucher.name,
+ "externalReference": external_reference,
+ }
+ }
+
+
+def test_voucher_query_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_VOUCHER_BY_EXTERNAL_REFERENCE,
+ variables,
+ permissions=[permission_manage_discounts],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"] == {"voucher": None}
+
+
+def test_voucher_query_by_empty_string_external_reference(
+ staff_api_client, voucher, permission_manage_discounts
+):
+ """An empty string is treated as a missing argument, so it can't be looked up."""
+ # given
+ external_reference = ""
+ voucher.external_reference = external_reference
+ voucher.save(update_fields=("external_reference",))
+ variables = {"externalReference": external_reference}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_VOUCHER_BY_EXTERNAL_REFERENCE,
+ variables,
+ permissions=[permission_manage_discounts],
+ )
+
+ # then
+ content = get_graphql_content_from_response(response)
+ assert content["data"] == {"voucher": 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"] == ["voucher"]
+
+
+def test_voucher_query_by_external_reference_no_permission(api_client, voucher):
+ # given
+ variables = {"externalReference": "non-existing-ext-ref"}
+
+ # when
+ response = api_client.post_graphql(QUERY_VOUCHER_BY_EXTERNAL_REFERENCE, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_external_reference_conflicting_identifiers(
+ staff_api_client, voucher, permission_manage_discounts
+):
+ # given
+ variables = {
+ "id": graphene.Node.to_global_id("Voucher", voucher.pk),
+ "externalReference": "voucher-reference",
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_VOUCHER_BY_EXTERNAL_REFERENCE,
+ variables,
+ permissions=[permission_manage_discounts],
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ assert content["data"] == {"voucher": None}
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["message"] == (
+ "Argument 'id' cannot be combined with 'external_reference'"
+ )
+ assert content["errors"][0]["path"] == ["voucher"]
+
+
QUERY_VOUCHER_BY_ID = """
query Voucher($id: ID!) {
voucher(id: $id) {
diff --git a/saleor/graphql/discount/types/vouchers.py b/saleor/graphql/discount/types/vouchers.py
index 9f8e3fced3..8654c6ba02 100644
--- a/saleor/graphql/discount/types/vouchers.py
+++ b/saleor/graphql/discount/types/vouchers.py
@@ -12,7 +12,11 @@ from ...core.context import (
ChannelQsContext,
get_database_connection_name,
)
-from ...core.descriptions import DEPRECATED_IN_3X_INPUT, PREVIEW_FEATURE
+from ...core.descriptions import (
+ ADDED_IN_323,
+ DEPRECATED_IN_3X_INPUT,
+ PREVIEW_FEATURE,
+)
from ...core.doc_category import DOC_CATEGORY_DISCOUNTS
from ...core.fields import ConnectionField, PermissionsField
from ...core.scalars import DateTime
@@ -84,6 +88,9 @@ class VoucherCodeCountableConnection(CountableConnection):
class Voucher(ChannelContextType[models.Voucher]):
id = graphene.GlobalID(required=True, description="The ID of the voucher.")
name = graphene.String(description="The name of the voucher.")
+ external_reference = graphene.String(
+ description=f"External ID of this voucher.{ADDED_IN_323}"
+ )
codes = ConnectionField(
VoucherCodeCountableConnection,
description="List of codes available for this voucher.",
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 4a82da517d..5efdb36ab8 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1168,13 +1168,20 @@ type Query {
): SaleCountableConnection @doc(category: "Discounts") @deprecated(reason: "Use the `promotions` query instead.")
"""
- Look up a voucher by ID.
+ Look up a voucher by ID or external reference.
Requires one of the following permissions: MANAGE_DISCOUNTS.
"""
voucher(
"""ID of the voucher."""
- id: ID!
+ id: ID
+
+ """
+ External ID of the voucher.
+
+ Added in Saleor 3.23.
+ """
+ externalReference: String
"""Slug of a channel for which the data should be returned."""
channel: String
@@ -11014,6 +11021,13 @@ type Voucher implements Node & ObjectWithMetadata @doc(category: "Discounts") {
"""The name of the voucher."""
name: String
+ """
+ External ID of this voucher.
+
+ Added in Saleor 3.23.
+ """
+ externalReference: String
+
"""List of codes available for this voucher."""
codes(
"""Return the elements in the list that come before the specified cursor."""
@@ -21056,8 +21070,15 @@ type Mutation {
- VOUCHER_DELETED (async): A voucher was deleted.
"""
voucherDelete(
+ """
+ External ID of a voucher to delete.
+
+ Added in Saleor 3.23.
+ """
+ externalReference: String
+
"""ID of a voucher to delete."""
- id: ID!
+ id: ID
): VoucherDelete @doc(category: "Discounts") @webhookEventsInfo(asyncEvents: [VOUCHER_DELETED], syncEvents: [])
"""
@@ -21085,8 +21106,15 @@ type Mutation {
- VOUCHER_CODES_CREATED (async): A voucher code was created.
"""
voucherUpdate(
+ """
+ External ID of a voucher to update.
+
+ Added in Saleor 3.23.
+ """
+ externalReference: String
+
"""ID of a voucher to update."""
- id: ID!
+ id: ID
"""Fields required to update a voucher."""
input: VoucherInput!
@@ -30817,6 +30845,13 @@ input VoucherInput @doc(category: "Discounts") {
"""Voucher name."""
name: String
+ """
+ External ID of this voucher.
+
+ Added in Saleor 3.23.
+ """
+ externalReference: String
+
"""Code to use the voucher."""
code: String @deprecated(reason: "Use `addCodes` instead.")