Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Allow external references to be used instead of Saleor-assigned IDs (#11410)
Piotr Zabieglikdb7e91a3e124
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 533efed931..e38bfdebf6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,14 @@ All notable, unreleased changes to this project will be documented in this file.- Add ability to filter and sort products of a category - #10917 by @yemeksepeti-cihankarluk, @ogunheper- Add `filter` argument to `Category.products`- Add `sortBy` argument to `Category.products`+ - Allow to mutate objects, by newly added `externalReference` field, instead of Saleor-assigned ID. Apply to following models:+ - `Product`+ - `ProductVariant`+ - `Attribute`+ - `AttributeValue`+ - `Order`+ - `User`+ - `Warehouse`### Other changes- Fix fetching the `checkout.availableCollectionPoints` - #11489 by @IKarbowiakdiff --git a/saleor/account/migrations/0071_user_external_reference.py b/saleor/account/migrations/0071_user_external_reference.pynew file mode 100644index 0000000000..1252676a53--- /dev/null+++ b/saleor/account/migrations/0071_user_external_reference.py@@ -0,0 +1,20 @@+# Generated by Django 3.2.16 on 2022-12-06 15:59++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("account", "0070_alter_user_uuid"),+ ]++ operations = [+ migrations.AddField(+ model_name="user",+ name="external_reference",+ field=models.CharField(+ blank=True, db_index=True, max_length=250, null=True, unique=True+ ),+ ),+ ]diff --git a/saleor/account/models.py b/saleor/account/models.pyindex 1cb96317dc..7d8057d1e1 100644--- a/saleor/account/models.py+++ b/saleor/account/models.py@@ -23,7 +23,7 @@ from django_countries.fields import Country, CountryFieldfrom phonenumber_field.modelfields import PhoneNumber, PhoneNumberFieldfrom ..app.models import App-from ..core.models import ModelWithMetadata+from ..core.models import ModelWithExternalReference, ModelWithMetadatafrom ..core.permissions import AccountPermissions, BasePermissionEnum, get_permissionsfrom ..core.utils.json_serializer import CustomJsonEncoderfrom ..order.models import Order@@ -162,7 +162,9 @@ class UserManager(BaseUserManager):return self.get_queryset().filter(is_staff=True)-class User(PermissionsMixin, ModelWithMetadata, AbstractBaseUser):+class User(+ PermissionsMixin, ModelWithMetadata, AbstractBaseUser, ModelWithExternalReference+):email = models.EmailField(unique=True)first_name = models.CharField(max_length=256, blank=True)last_name = models.CharField(max_length=256, blank=True)diff --git a/saleor/attribute/migrations/0027_auto_20221205_1650.py b/saleor/attribute/migrations/0027_auto_20221205_1650.pynew file mode 100644index 0000000000..9a210accb3--- /dev/null+++ b/saleor/attribute/migrations/0027_auto_20221205_1650.py@@ -0,0 +1,27 @@+# Generated by Django 3.2.16 on 2022-12-05 16:50++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("attribute", "0026_merge_20221019_0937"),+ ]++ operations = [+ migrations.AddField(+ model_name="attribute",+ name="external_reference",+ field=models.CharField(+ blank=True, db_index=True, max_length=250, null=True, unique=True+ ),+ ),+ migrations.AddField(+ model_name="attributevalue",+ name="external_reference",+ field=models.CharField(+ blank=True, db_index=True, max_length=250, null=True, unique=True+ ),+ ),+ ]diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.pyindex 1462a03e19..fe7d340751 100644--- a/saleor/attribute/models/base.py+++ b/saleor/attribute/models/base.py@@ -5,7 +5,7 @@ from django.db import modelsfrom django.db.models import F, Qfrom ...core.db.fields import SanitizedJSONField-from ...core.models import ModelWithMetadata, SortableModel+from ...core.models import ModelWithExternalReference, ModelWithMetadata, SortableModelfrom ...core.permissions import (PageTypePermissions,ProductTypePermissions,@@ -112,7 +112,7 @@ class AttributeQuerySet(BaseAttributeQuerySet):return self.filter(type=AttributeType.PAGE_TYPE)-class Attribute(ModelWithMetadata):+class Attribute(ModelWithMetadata, ModelWithExternalReference):slug = models.SlugField(max_length=250, unique=True, allow_unicode=True)name = models.CharField(max_length=255)type = models.CharField(max_length=50, choices=AttributeType.CHOICES)@@ -205,7 +205,7 @@ class AttributeTranslation(Translation):return {"name": self.name}-class AttributeValue(SortableModel):+class AttributeValue(SortableModel, ModelWithExternalReference):name = models.CharField(max_length=250)# keeps hex code color value in #RRGGBBAA formatvalue = models.CharField(max_length=100, blank=True, default="")diff --git a/saleor/core/error_codes.py b/saleor/core/error_codes.pyindex f5e6458534..5ea70e40b8 100644--- a/saleor/core/error_codes.py+++ b/saleor/core/error_codes.py@@ -28,3 +28,7 @@ class TranslationErrorCode(Enum):class UploadErrorCode(Enum):GRAPHQL_ERROR = "graphql_error"+++class CoreErrorCode(Enum):+ GRAPHQL_ERROR = "graphql_error"diff --git a/saleor/core/models.py b/saleor/core/models.pyindex c08d793a3d..f4a15b2385 100644--- a/saleor/core/models.py+++ b/saleor/core/models.py@@ -112,6 +112,19 @@ class ModelWithMetadata(models.Model):del self.metadata[key]+class ModelWithExternalReference(models.Model):+ external_reference = models.CharField(+ max_length=250,+ unique=True,+ blank=True,+ null=True,+ db_index=True,+ )++ class Meta:+ abstract = True++class Job(models.Model):status = models.CharField(max_length=50, choices=JobStatus.CHOICES, default=JobStatus.PENDINGdiff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.pyindex 0701b7a864..2d41ca936f 100644--- a/saleor/graphql/account/mutations/base.py+++ b/saleor/graphql/account/mutations/base.py@@ -25,6 +25,7 @@ from ...account.types import Address, AddressInput, Userfrom ...app.dataloaders import get_app_promisefrom ...channel.utils import clean_channel, validate_channelfrom ...core.context import set_mutation_flag_in_context+from ...core.descriptions import ADDED_IN_310from ...core.enums import LanguageCodeEnumfrom ...core.mutations import (BaseMutation,@@ -421,6 +422,9 @@ class CustomerInput(UserInput, UserAddressInput):language_code = graphene.Field(LanguageCodeEnum, required=False, description="User language code.")+ external_reference = graphene.String(+ description="External ID of the customer." + ADDED_IN_310, required=False+ )class UserCreateInput(CustomerInput):diff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.pyindex a9e7398c1b..bfe0eecdce 100644--- a/saleor/graphql/account/mutations/staff.py+++ b/saleor/graphql/account/mutations/staff.py@@ -24,7 +24,13 @@ from ....thumbnail import models as thumbnail_modelsfrom ...account.enums import AddressTypeEnumfrom ...account.types import Address, AddressInput, Userfrom ...app.dataloaders import get_app_promise-from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation+from ...core.descriptions import ADDED_IN_310+from ...core.mutations import (+ BaseMutation,+ ModelDeleteMutation,+ ModelMutation,+ ModelWithExtRefMutation,+)from ...core.types import AccountError, NonNullList, StaffError, Uploadfrom ...core.validators.file import clean_image_filefrom ...plugins.dataloaders import get_plugin_manager_promise@@ -84,9 +90,13 @@ class CustomerCreate(BaseCustomerCreate):error_type_field = "account_errors"-class CustomerUpdate(CustomerCreate):+class CustomerUpdate(CustomerCreate, ModelWithExtRefMutation):class Arguments:- id = graphene.ID(description="ID of a customer to update.", required=True)+ id = graphene.ID(description="ID of a customer to update.", required=False)+ external_reference = graphene.String(+ required=False,+ description=f"External ID of a customer to update. {ADDED_IN_310}",+ )input = CustomerInput(description="Fields required to update a customer.", required=True)@@ -167,7 +177,7 @@ class CustomerUpdate(CustomerCreate):return cls.success_response(new_instance)-class UserDelete(UserDeleteMixin, ModelDeleteMutation):+class UserDelete(UserDeleteMixin, ModelDeleteMutation, ModelWithExtRefMutation):class Meta:abstract = True@@ -182,7 +192,11 @@ class CustomerDelete(CustomerDeleteMixin, UserDelete):error_type_field = "account_errors"class Arguments:- id = graphene.ID(required=True, description="ID of a customer to delete.")+ id = graphene.ID(required=False, description="ID of a customer to delete.")+ external_reference = graphene.String(+ required=False,+ description=f"External ID of a customer to update. {ADDED_IN_310}",+ )@classmethoddef perform_mutation(cls, root, info, **data):diff --git a/saleor/graphql/account/resolvers.py b/saleor/graphql/account/resolvers.pyindex 381fcdf903..f8b89d8190 100644--- a/saleor/graphql/account/resolvers.py+++ b/saleor/graphql/account/resolvers.py@@ -55,7 +55,7 @@ def resolve_staff_users(_info):@traced_resolver-def resolve_user(info, id=None, email=None):+def resolve_user(info, id=None, email=None, external_reference=None):requester = get_user_or_app_from_context(info.context)if requester:filter_kwargs = {}@@ -63,6 +63,8 @@ def resolve_user(info, id=None, email=None):_model, filter_kwargs["pk"] = from_global_id_or_error(id, User)if email:filter_kwargs["email"] = email+ if external_reference:+ filter_kwargs["external_reference"] = external_referenceif requester.has_perms([AccountPermissions.MANAGE_STAFF, AccountPermissions.MANAGE_USERS]):diff --git a/saleor/graphql/account/schema.py b/saleor/graphql/account/schema.pyindex 1243e39e54..84ad992fb5 100644--- a/saleor/graphql/account/schema.py+++ b/saleor/graphql/account/schema.py@@ -3,6 +3,7 @@ import graphenefrom ...core.permissions import AccountPermissions, OrderPermissionsfrom ..app.dataloaders import app_promise_callbackfrom ..core.connection import create_connection_slice, filter_connection_queryset+from ..core.descriptions import ADDED_IN_310from ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.types import FilterInputObjectTypefrom ..core.utils import from_global_id_or_error@@ -155,6 +156,9 @@ class AccountQueries(graphene.ObjectType):email=graphene.Argument(graphene.String, description="Email address of the user."),+ external_reference=graphene.Argument(+ graphene.String, description=f"External ID of the user. {ADDED_IN_310}"+ ),permissions=[AccountPermissions.MANAGE_STAFF,AccountPermissions.MANAGE_USERS,@@ -204,9 +208,11 @@ class AccountQueries(graphene.ObjectType):return create_connection_slice(qs, info, kwargs, UserCountableConnection)@staticmethod- def resolve_user(_root, info, *, id=None, email=None):- validate_one_of_args_is_in_query("id", id, "email", email)- return resolve_user(info, id, email)+ def resolve_user(_root, info, *, id=None, email=None, external_reference=None):+ validate_one_of_args_is_in_query(+ "id", id, "email", email, "external_reference", external_reference+ )+ return resolve_user(info, id, email, external_reference)@staticmethod@app_promise_callbackdiff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.pyindex 25e2a46e9d..a31ee668f9 100644--- a/saleor/graphql/account/tests/test_account.py+++ b/saleor/graphql/account/tests/test_account.py@@ -622,10 +622,11 @@ def test_query_staff_user_with_orders_and_manage_orders_perm(USER_QUERY = """- query User($id: ID $email: String) {- user(id: $id, email: $email) {+ query User($id: ID $email: String, $externalReference: String) {+ user(id: $id, email: $email, externalReference: $externalReference) {id+ externalReference}}"""@@ -644,6 +645,27 @@ def test_query_user_by_email_address(assert customer_user.email == data["email"]+def test_query_user_by_external_reference(+ user_api_client, customer_user, permission_manage_users+):+ # given+ user = customer_user+ ext_ref = "test-ext-ref"+ user.external_reference = ext_ref+ user.save(update_fields=["external_reference"])+ variables = {"externalReference": ext_ref}++ # when+ response = user_api_client.post_graphql(+ USER_QUERY, variables, permissions=[permission_manage_users]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["user"]+ assert data["externalReference"] == user.external_reference++def test_query_user_by_id_and_email(user_api_client, customer_user, permission_manage_users):@@ -1510,7 +1532,9 @@ CUSTOMER_CREATE_MUTATION = """mutation CreateCustomer($email: String, $firstName: String, $lastName: String, $channel: String$note: String, $billing: AddressInput, $shipping: AddressInput,- $redirect_url: String, $languageCode: LanguageCodeEnum) {+ $redirect_url: String, $languageCode: LanguageCodeEnum,+ $externalReference: String+ ) {customerCreate(input: {email: $email,firstName: $firstName,@@ -1521,6 +1545,7 @@ CUSTOMER_CREATE_MUTATION = """redirectUrl: $redirect_url,languageCode: $languageCode,channel: $channel,+ externalReference: $externalReference}) {errors {field@@ -1542,6 +1567,7 @@ CUSTOMER_CREATE_MUTATION = """isActiveisStaffnote+ externalReference}}}@@ -1566,6 +1592,7 @@ def test_customer_create(note = "Test user"address_data = convert_dict_keys_to_camel_case(address.as_data())redirect_url = "https://www.example.com"+ external_reference = "test-ext-ref"variables = {"email": email,"firstName": first_name,@@ -1576,6 +1603,7 @@ def test_customer_create("redirect_url": redirect_url,"languageCode": "PL","channel": channel_PLN.slug,+ "externalReference": external_reference,}response = staff_api_client.post_graphql(@@ -1600,6 +1628,7 @@ def test_customer_create(assert data["user"]["lastName"] == last_nameassert data["user"]["note"] == noteassert data["user"]["languageCode"] == "PL"+ assert data["user"]["externalReference"] == external_referenceassert not data["user"]["isStaff"]assert data["user"]["isActive"]@@ -1744,6 +1773,29 @@ def test_customer_create_with_upper_case_email(assert data["user"]["email"] == email.lower()+def test_customer_create_with_non_unique_external_reference(+ staff_api_client, permission_manage_users, customer_user+):+ # given+ ext_ref = "test-ext-ref"+ customer_user.external_reference = ext_ref+ customer_user.save(update_fields=["external_reference"])++ variables = {"email": "[email protected]", "externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_CREATE_MUTATION, variables, permissions=[permission_manage_users]+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["customerCreate"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == AccountErrorCode.UNIQUE.name+ assert error["message"] == "User with this External reference already exists."++def test_customer_update(staff_api_client, staff_user, customer_user, address, permission_manage_users):@@ -1751,16 +1803,22 @@ def test_customer_update(mutation UpdateCustomer($id: ID!, $firstName: String, $lastName: String,$isActive: Boolean, $note: String, $billing: AddressInput,- $shipping: AddressInput, $languageCode: LanguageCodeEnum) {- customerUpdate(id: $id, input: {- isActive: $isActive,- firstName: $firstName,- lastName: $lastName,- note: $note,- defaultBillingAddress: $billing- defaultShippingAddress: $shipping,- languageCode: $languageCode- }) {+ $shipping: AddressInput, $languageCode: LanguageCodeEnum,+ $externalReference: String+ ) {+ customerUpdate(+ id: $id,+ input: {+ isActive: $isActive,+ firstName: $firstName,+ lastName: $lastName,+ note: $note,+ defaultBillingAddress: $billing+ defaultShippingAddress: $shipping,+ languageCode: $languageCode,+ externalReference: $externalReference+ }+ ) {errors {fieldmessage@@ -1778,6 +1836,7 @@ def test_customer_update(languageCodeisActivenote+ externalReference}}}@@ -1794,6 +1853,7 @@ def test_customer_update(first_name = "new_first_name"last_name = "new_last_name"note = "Test update note"+ external_reference = "test-ext-ref"address_data = convert_dict_keys_to_camel_case(address.as_data())new_street_address = "Updated street address"@@ -1808,6 +1868,7 @@ def test_customer_update("billing": address_data,"shipping": address_data,"languageCode": "PL",+ "externalReference": external_reference,}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_users]@@ -1833,6 +1894,7 @@ def test_customer_update(assert data["user"]["lastName"] == last_nameassert data["user"]["note"] == noteassert data["user"]["languageCode"] == "PL"+ assert data["user"]["externalReference"] == external_referenceassert not data["user"]["isActive"](@@ -1859,6 +1921,130 @@ def test_customer_update()+UPDATE_CUSTOMER_BY_EXTERNAL_REFERENCE = """+ mutation UpdateCustomer(+ $id: ID, $externalReference: String, $input: CustomerInput!+ ) {+ customerUpdate(id: $id, externalReference: $externalReference, input: $input) {+ errors {+ field+ message+ code+ }+ user {+ id+ externalReference+ firstName+ }+ }+ }+ """+++def test_customer_update_by_external_reference(+ staff_api_client, customer_user, permission_manage_users+):+ # given+ query = UPDATE_CUSTOMER_BY_EXTERNAL_REFERENCE+ user = customer_user+ new_name = "updated name"+ ext_ref = "test-ext-ref"+ user.external_reference = ext_ref+ user.save(update_fields=["external_reference"])++ variables = {+ "externalReference": ext_ref,+ "input": {"firstName": new_name},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_users]+ )+ content = get_graphql_content(response)++ # then+ user.refresh_from_db()+ data = content["data"]["customerUpdate"]+ assert not data["errors"]+ assert data["user"]["firstName"] == new_name == user.first_name+ assert data["user"]["id"] == graphene.Node.to_global_id("User", user.id)+ assert data["user"]["externalReference"] == ext_ref+++def test_update_customer_by_both_id_and_external_reference(+ staff_api_client, customer_user, permission_manage_users+):+ # given+ query = UPDATE_CUSTOMER_BY_EXTERNAL_REFERENCE+ variables = {"input": {}, "externalReference": "whatever", "id": "whatever"}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_users]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["customerUpdate"]+ assert not data["user"]+ assert (+ data["errors"][0]["message"]+ == "Argument 'id' cannot be combined with 'external_reference'"+ )+++def test_update_customer_by_external_reference_not_existing(+ staff_api_client, customer_user, permission_manage_users+):+ # given+ query = UPDATE_CUSTOMER_BY_EXTERNAL_REFERENCE+ ext_ref = "non-existing-ext-ref"+ variables = {+ "input": {},+ "externalReference": ext_ref,+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_users]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["customerUpdate"]+ assert not data["user"]+ assert data["errors"][0]["message"] == f"Couldn't resolve to a node: {ext_ref}"+ assert data["errors"][0]["field"] == "externalReference"+++def test_update_customer_with_non_unique_external_reference(+ staff_api_client, permission_manage_users, user_list+):+ # given+ query = UPDATE_CUSTOMER_BY_EXTERNAL_REFERENCE++ ext_ref = "test-ext-ref"+ user_1 = user_list[0]+ user_1.external_reference = ext_ref+ user_1.save(update_fields=["external_reference"])+ user_2_id = graphene.Node.to_global_id("User", user_list[1].id)++ variables = {"input": {"externalReference": ext_ref}, "id": user_2_id}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_users]+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["customerUpdate"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == AccountErrorCode.UNIQUE.name+ assert error["message"] == "User with this External reference already exists."++UPDATE_CUSTOMER_EMAIL_MUTATION = """mutation UpdateCustomer($id: ID!, $firstName: String, $lastName: String, $email: String) {@@ -2560,14 +2746,15 @@ def test_account_delete_other_customer_token(user_api_client):CUSTOMER_DELETE_MUTATION = """- mutation CustomerDelete($id: ID!) {- customerDelete(id: $id){+ mutation CustomerDelete($id: ID, $externalReference: String) {+ customerDelete(id: $id, externalReference: $externalReference) {errors {fieldmessage}user {id+ externalReference}}}@@ -2698,6 +2885,72 @@ def test_customer_delete_errors(customer_user, admin_user, staff_user):CustomerDelete.clean_instance(info, customer_user)+def test_customer_delete_by_external_reference(+ staff_api_client, customer_user, permission_manage_users+):+ # given+ user = customer_user+ query = CUSTOMER_DELETE_MUTATION+ ext_ref = "test-ext-ref"+ user.external_reference = ext_ref+ user.save(update_fields=["external_reference"])+ variables = {"externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_users]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["customerDelete"]+ with pytest.raises(user._meta.model.DoesNotExist):+ user.refresh_from_db()+ assert not data["errors"]+ assert data["user"]["externalReference"] == ext_ref+ assert data["user"]["id"] == graphene.Node.to_global_id("User", user.id)+++def test_delete_customer_by_both_id_and_external_reference(+ staff_api_client, customer_user, permission_manage_users+):+ # given+ query = CUSTOMER_DELETE_MUTATION+ variables = {"externalReference": "whatever", "id": "whatever"}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_users]+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["customerDelete"]["errors"]+ assert (+ errors[0]["message"]+ == "Argument 'id' cannot be combined with 'external_reference'"+ )+++def test_delete_customer_by_external_reference_not_existing(+ staff_api_client, customer_user, permission_manage_users+):+ # given+ query = CUSTOMER_DELETE_MUTATION+ ext_ref = "non-existing-ext-ref"+ variables = {"externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_users]+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["customerDelete"]["errors"]+ assert errors[0]["message"] == f"Couldn't resolve to a node: {ext_ref}"++STAFF_CREATE_MUTATION = """mutation CreateStaff($email: String, $redirect_url: String, $add_groups: [ID!]diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.pyindex 96d85df3d2..dd79e8b99a 100644--- a/saleor/graphql/account/types.py+++ b/saleor/graphql/account/types.py@@ -25,7 +25,7 @@ from ..app.types import Appfrom ..checkout.dataloaders import CheckoutByUserAndChannelLoader, CheckoutByUserLoaderfrom ..checkout.types import Checkout, CheckoutCountableConnectionfrom ..core.connection import CountableConnection, create_connection_slice-from ..core.descriptions import ADDED_IN_38, DEPRECATED_IN_3X_FIELD+from ..core.descriptions import ADDED_IN_38, ADDED_IN_310, DEPRECATED_IN_3X_FIELDfrom ..core.enums import LanguageCodeEnumfrom ..core.federation import federated_entity, resolve_federation_referencesfrom ..core.fields import ConnectionField, PermissionsField@@ -329,6 +329,9 @@ class User(ModelObjectType):)default_shipping_address = graphene.Field(Address)default_billing_address = graphene.Field(Address)+ external_reference = graphene.String(+ description=f"External ID of this user. {ADDED_IN_310}", required=False+ )last_login = graphene.DateTime()date_joined = graphene.DateTime(required=True)diff --git a/saleor/graphql/attribute/mutations/attribute_create.py b/saleor/graphql/attribute/mutations/attribute_create.pyindex 906cf4660b..d26d53ddeb 100644--- a/saleor/graphql/attribute/mutations/attribute_create.py+++ b/saleor/graphql/attribute/mutations/attribute_create.py@@ -6,7 +6,7 @@ from ....attribute import models as modelsfrom ....attribute.error_codes import AttributeErrorCodefrom ....core.exceptions import PermissionDeniedfrom ....core.permissions import PageTypePermissions, ProductTypePermissions-from ...core.descriptions import DEPRECATED_IN_3X_INPUT+from ...core.descriptions import ADDED_IN_310, DEPRECATED_IN_3X_INPUTfrom ...core.enums import MeasurementUnitsEnumfrom ...core.fields import JSONStringfrom ...core.mutations import ModelMutation@@ -37,6 +37,10 @@ class AttributeValueInput(graphene.InputObjectType):description="URL of the file attribute. Every time, a new value is created.",)content_type = graphene.String(required=False, description="File content type.")+ external_reference = graphene.String(+ description="External ID of this attribute value." + ADDED_IN_310,+ required=False,+ )class AttributeValueCreateInput(AttributeValueInput):@@ -72,6 +76,9 @@ class AttributeCreateInput(graphene.InputObjectType):available_in_grid = graphene.Boolean(required=False, description=AttributeDescriptions.AVAILABLE_IN_GRID)+ external_reference = graphene.String(+ description="External ID of this attribute." + ADDED_IN_310, required=False+ )class AttributeCreate(AttributeMixin, ModelMutation):diff --git a/saleor/graphql/attribute/mutations/attribute_delete.py b/saleor/graphql/attribute/mutations/attribute_delete.pyindex 81b0d8dce1..fb5fb6cfc7 100644--- a/saleor/graphql/attribute/mutations/attribute_delete.py+++ b/saleor/graphql/attribute/mutations/attribute_delete.py@@ -2,15 +2,20 @@ import graphenefrom ....attribute import models as modelsfrom ....core.permissions import ProductTypePermissions-from ...core.mutations import ModelDeleteMutation+from ...core.descriptions import ADDED_IN_310+from ...core.mutations import ModelDeleteMutation, ModelWithExtRefMutationfrom ...core.types import AttributeErrorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Attribute-class AttributeDelete(ModelDeleteMutation):+class AttributeDelete(ModelDeleteMutation, ModelWithExtRefMutation):class Arguments:- id = graphene.ID(required=True, description="ID of an attribute to delete.")+ id = graphene.ID(required=False, description="ID of an attribute to delete.")+ external_reference = graphene.String(+ required=False,+ description=f"External ID of an attribute to delete. {ADDED_IN_310}",+ )class Meta:model = models.Attributediff --git a/saleor/graphql/attribute/mutations/attribute_update.py b/saleor/graphql/attribute/mutations/attribute_update.pyindex cf6374a42c..654b3fe6f5 100644--- a/saleor/graphql/attribute/mutations/attribute_update.py+++ b/saleor/graphql/attribute/mutations/attribute_update.py@@ -4,8 +4,9 @@ from django.core.exceptions import ValidationErrorfrom ....attribute import models as modelsfrom ....attribute.error_codes import AttributeErrorCodefrom ....core.permissions import ProductTypePermissions+from ...core.descriptions import ADDED_IN_310from ...core.enums import MeasurementUnitsEnum-from ...core.mutations import ModelMutation+from ...core.mutations import ModelWithExtRefMutationfrom ...core.types import AttributeError, NonNullListfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..descriptions import AttributeDescriptions, AttributeValueDescriptions@@ -51,9 +52,12 @@ class AttributeUpdateInput(graphene.InputObjectType):available_in_grid = graphene.Boolean(required=False, description=AttributeDescriptions.AVAILABLE_IN_GRID)+ external_reference = graphene.String(+ description="External ID of this product." + ADDED_IN_310, required=False+ )-class AttributeUpdate(AttributeMixin, ModelMutation):+class AttributeUpdate(AttributeMixin, ModelWithExtRefMutation):# Needed by AttributeMixin,# represents the input name for the passed list of valuesATTRIBUTE_VALUES_FIELD = "add_values"@@ -61,7 +65,11 @@ class AttributeUpdate(AttributeMixin, ModelMutation):attribute = graphene.Field(Attribute, description="The updated attribute.")class Arguments:- id = graphene.ID(required=True, description="ID of an attribute to update.")+ id = graphene.ID(required=False, description="ID of an attribute to update.")+ external_reference = graphene.String(+ required=False,+ description=f"External ID of an attribute to update. {ADDED_IN_310}",+ )input = AttributeUpdateInput(required=True, description="Fields required to update an attribute.")@@ -97,8 +105,8 @@ class AttributeUpdate(AttributeMixin, ModelMutation):attribute_value.delete()@classmethod- def perform_mutation(cls, _root, info, id, input):- instance = cls.get_node_or_error(info, id, only_type=Attribute)+ def perform_mutation(cls, _root, info, input, **data):+ instance = cls.get_instance(info, **data)# Do cleaning and uniqueness checkscleaned_input = cls.clean_input(info, instance, input)diff --git a/saleor/graphql/attribute/mutations/attribute_value_delete.py b/saleor/graphql/attribute/mutations/attribute_value_delete.pyindex 769ce9cc73..733a6de546 100644--- a/saleor/graphql/attribute/mutations/attribute_value_delete.py+++ b/saleor/graphql/attribute/mutations/attribute_value_delete.py@@ -4,17 +4,22 @@ from django.db.models import Exists, OuterRef, Qfrom ....attribute import models as modelsfrom ....core.permissions import ProductTypePermissionsfrom ....product import models as product_models-from ...core.mutations import ModelDeleteMutation+from ...core.descriptions import ADDED_IN_310+from ...core.mutations import ModelDeleteMutation, ModelWithExtRefMutationfrom ...core.types import AttributeErrorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Attribute, AttributeValue-class AttributeValueDelete(ModelDeleteMutation):+class AttributeValueDelete(ModelDeleteMutation, ModelWithExtRefMutation):attribute = graphene.Field(Attribute, description="The updated attribute.")class Arguments:- id = graphene.ID(required=True, description="ID of a value to delete.")+ id = graphene.ID(required=False, description="ID of a value to delete.")+ external_reference = graphene.String(+ required=False,+ description=f"External ID of a value to delete. {ADDED_IN_310}",+ )class Meta:model = models.AttributeValue@@ -26,8 +31,7 @@ class AttributeValueDelete(ModelDeleteMutation):@classmethoddef perform_mutation(cls, _root, info, **data):- node_id = data.get("id")- instance = cls.get_node_or_error(info, node_id, only_type=AttributeValue)+ instance = cls.get_instance(info, **data)product_ids = cls.get_product_ids_to_update(instance)response = super().perform_mutation(_root, info, **data)product_models.Product.objects.filter(id__in=product_ids).update(diff --git a/saleor/graphql/attribute/mutations/attribute_value_update.py b/saleor/graphql/attribute/mutations/attribute_value_update.pyindex 99d95e58c7..129b533c4d 100644--- a/saleor/graphql/attribute/mutations/attribute_value_update.py+++ b/saleor/graphql/attribute/mutations/attribute_value_update.py@@ -5,6 +5,8 @@ from django.db.models import Exists, OuterRef, Qfrom ....attribute import models as modelsfrom ....core.permissions import ProductTypePermissionsfrom ....product import models as product_models+from ...core.descriptions import ADDED_IN_310+from ...core.mutations import ModelWithExtRefMutationfrom ...core.types import AttributeErrorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Attribute, AttributeValue@@ -33,12 +35,16 @@ def queryset_in_batches(queryset):start_pk = pks[-1]-class AttributeValueUpdate(AttributeValueCreate):+class AttributeValueUpdate(AttributeValueCreate, ModelWithExtRefMutation):attribute = graphene.Field(Attribute, description="The updated attribute.")class Arguments:id = graphene.ID(- required=True, description="ID of an AttributeValue to update."+ required=False, description="ID of an AttributeValue to update."+ )+ external_reference = graphene.String(+ required=False,+ description=f"External ID of an AttributeValue to update. {ADDED_IN_310}",)input = AttributeValueUpdateInput(required=True, description="Fields required to update an AttributeValue."diff --git a/saleor/graphql/attribute/resolvers.py b/saleor/graphql/attribute/resolvers.pyindex 1ca6097b17..fa80222b43 100644--- a/saleor/graphql/attribute/resolvers.py+++ b/saleor/graphql/attribute/resolvers.py@@ -6,11 +6,3 @@ def resolve_attributes(info, qs=None):requestor = get_user_or_app_from_context(info.context)qs = qs or models.Attribute.objects.get_visible_to_user(requestor)return qs.distinct()---def resolve_attribute_by_id(id):- return models.Attribute.objects.filter(id=id).first()---def resolve_attribute_by_slug(slug):- return models.Attribute.objects.filter(slug=slug).first()diff --git a/saleor/graphql/attribute/schema.py b/saleor/graphql/attribute/schema.pyindex 9974fd8849..e60a561008 100644--- a/saleor/graphql/attribute/schema.py+++ b/saleor/graphql/attribute/schema.py@@ -1,8 +1,10 @@import graphene+from ...attribute import modelsfrom ..core.connection import create_connection_slice, filter_connection_queryset+from ..core.descriptions import ADDED_IN_310from ..core.fields import FilterConnectionField-from ..core.utils import from_global_id_or_error+from ..core.utils.resolvers import resolve_by_global_id_slug_or_ext_reffrom ..translations.mutations import AttributeTranslate, AttributeValueTranslatefrom .bulk_mutations import AttributeBulkDelete, AttributeValueBulkDeletefrom .filters import AttributeFilterInput@@ -15,11 +17,7 @@ from .mutations import (AttributeValueDelete,AttributeValueUpdate,)-from .resolvers import (- resolve_attribute_by_id,- resolve_attribute_by_slug,- resolve_attributes,-)+from .resolvers import resolve_attributesfrom .sorters import AttributeSortingInputfrom .types import Attribute, AttributeCountableConnection@@ -38,7 +36,10 @@ class AttributeQueries(graphene.ObjectType):Attribute,id=graphene.Argument(graphene.ID, description="ID of the attribute."),slug=graphene.Argument(graphene.String, description="Slug of the attribute."),- description="Look up an attribute by ID.",+ external_reference=graphene.Argument(+ graphene.String, description=f"External ID of the attribute. {ADDED_IN_310}"+ ),+ description="Look up an attribute by ID, slug or external reference.",)def resolve_attributes(self, info, **kwargs):@@ -46,11 +47,10 @@ class AttributeQueries(graphene.ObjectType):qs = filter_connection_queryset(qs, kwargs, info.context)return create_connection_slice(qs, info, kwargs, AttributeCountableConnection)- def resolve_attribute(self, _info, *, id=None, slug=None):- if id:- _, id = from_global_id_or_error(id, Attribute)- return resolve_attribute_by_id(id)- return resolve_attribute_by_slug(slug=slug)+ def resolve_attribute(self, _info, *, id=None, slug=None, external_reference=None):+ return resolve_by_global_id_slug_or_ext_ref(+ models.Attribute, id, slug, external_reference+ )class AttributeMutations(graphene.ObjectType):diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_create.pyindex 8faa2f68ac..e0226389a6 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py@@ -37,6 +37,7 @@ CREATE_ATTRIBUTE_MUTATION = """filterableInDashboardavailableInGridstorefrontSearchPosition+ externalReferencechoices(first: 10) {edges {node {@@ -73,9 +74,11 @@ def test_create_attribute_and_attribute_values(attribute_name = "Example name"name = "Value name"+ external_reference = "test-ext-ref"variables = {"input": {"name": attribute_name,+ "externalReference": external_reference,"values": [{"name": name}],"type": AttributeTypeEnum.PRODUCT_TYPE.name,}@@ -104,6 +107,7 @@ def test_create_attribute_and_attribute_values(assert (data["attribute"]["productTypes"]["edges"] == []), "The attribute should not have been assigned to a product type"+ assert data["attribute"]["externalReference"] == external_reference# Check if the attribute values were correctly createdassert len(data["attribute"]["choices"]) == 1@@ -1255,3 +1259,42 @@ def test_create_attribute_and_attribute_values_errors(assert errors[0]["field"] == "values"assert errors[0]["message"] == error_msgassert errors[0]["code"] == error_code.name+++def test_create_attribute_with_non_unique_external_reference(+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ color_attribute,+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ ext_ref = "test-ext-ref"+ color_attribute.external_reference = ext_ref+ color_attribute.save(update_fields=["external_reference"])++ variables = {+ "input": {+ "name": "some test name",+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "externalReference": ext_ref,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["attributeCreate"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == AttributeErrorCode.UNIQUE.name+ assert error["message"] == "Attribute with this External reference already exists."diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py b/saleor/graphql/attribute/tests/mutations/test_attribute_delete.pyindex 4033523539..13c0c8e04c 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py@@ -127,3 +127,88 @@ def test_delete_file_attribute(assert data["attribute"]["id"] == variables["id"]with pytest.raises(attribute._meta.model.DoesNotExist):attribute.refresh_from_db()+++ATTRIBUTE_DELETE_BY_EXTERNAL_REFERENCE_MUTATION = """+ mutation deleteAttribute($id: ID, $externalReference: String) {+ attributeDelete(id: $id, externalReference: $externalReference) {+ attribute {+ id+ externalReference+ }+ errors {+ field+ message+ }+ }+ }+"""+++def test_delete_attribute_by_external_reference(+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ attribute = color_attribute+ query = ATTRIBUTE_DELETE_BY_EXTERNAL_REFERENCE_MUTATION+ ext_ref = "test-ext-ref"+ attribute.external_reference = ext_ref+ attribute.save(update_fields=["external_reference"])+ variables = {"externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["attributeDelete"]+ with pytest.raises(attribute._meta.model.DoesNotExist):+ attribute.refresh_from_db()+ assert data["attribute"]["externalReference"] == ext_ref+ assert (+ graphene.Node.to_global_id("Attribute", attribute.id) == data["attribute"]["id"]+ )+++def test_delete_attribute_by_both_id_and_external_reference(+ staff_api_client, permission_manage_product_types_and_attributes+):+ # given+ query = ATTRIBUTE_DELETE_BY_EXTERNAL_REFERENCE_MUTATION+ variables = {"externalReference": "whatever", "id": "whatever"}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["attributeDelete"]["errors"]+ assert (+ errors[0]["message"]+ == "Argument 'id' cannot be combined with 'external_reference'"+ )+++def test_delete_attribute_by_external_reference_not_existing(+ staff_api_client, permission_manage_product_types_and_attributes+):+ # given+ query = ATTRIBUTE_DELETE_BY_EXTERNAL_REFERENCE_MUTATION+ ext_ref = "non-existing-ext-ref"+ variables = {"externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["attributeDelete"]["errors"]+ assert errors[0]["message"] == f"Couldn't resolve to a node: {ext_ref}"diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_update.pyindex 76a90fce93..089b08567c 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py@@ -30,6 +30,7 @@ UPDATE_ATTRIBUTE_MUTATION = """nameslugunit+ externalReferencechoices(first: 10) {edges {node {@@ -51,17 +52,23 @@ UPDATE_ATTRIBUTE_MUTATION = """"""-def test_update_attribute_name(+def test_update_attribute(staff_api_client, color_attribute, permission_manage_product_types_and_attributes):# givenquery = UPDATE_ATTRIBUTE_MUTATIONattribute = color_attributename = "Wings name"+ external_reference = "test-ext-ref"slug = attribute.slugnode_id = graphene.Node.to_global_id("Attribute", attribute.id)variables = {- "input": {"name": name, "addValues": [], "removeValues": []},+ "input": {+ "name": name,+ "addValues": [],+ "removeValues": [],+ "externalReference": external_reference,+ },"id": node_id,}@@ -77,6 +84,11 @@ def test_update_attribute_name(assert data["attribute"]["name"] == name == attribute.nameassert data["attribute"]["slug"] == slug == attribute.slugassert data["attribute"]["productTypes"]["edges"] == []+ assert (+ data["attribute"]["externalReference"]+ == external_reference+ == attribute.external_reference+ )@freeze_time("2022-05-12 12:00:00")@@ -663,3 +675,139 @@ def test_update_attribute_and_remove_others_attribute_value(assert errorsassert errors[0]["field"] == "removeValues"assert errors[0]["code"] == AttributeErrorCode.INVALID.name+++UPDATE_ATTRIBUTE_BY_EXTERNAL_REFERENCE_MUTATION = """+ mutation updateAttribute(+ $id: ID, $externalReference: String, $input: AttributeUpdateInput!+ ) {+ attributeUpdate(+ id: $id,+ externalReference: $externalReference+ input: $input+ ) {+ errors {+ field+ message+ code+ }+ attribute {+ name+ id+ externalReference+ }+ }+}+"""+++def test_update_attribute_by_external_reference(+ staff_api_client, color_attribute, permission_manage_product_types_and_attributes+):+ # given+ query = UPDATE_ATTRIBUTE_BY_EXTERNAL_REFERENCE_MUTATION+ attribute = color_attribute+ new_name = "updated name"+ ext_ref = "test-ext-ref"+ attribute.external_reference = ext_ref+ attribute.save(update_fields=["external_reference"])++ variables = {+ "input": {"name": new_name},+ "externalReference": ext_ref,+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ # then+ attribute.refresh_from_db()+ data = content["data"]["attributeUpdate"]+ assert not data["errors"]+ assert data["attribute"]["name"] == new_name == attribute.name+ assert data["attribute"]["id"] == graphene.Node.to_global_id(+ "Attribute", attribute.id+ )+ assert data["attribute"]["externalReference"] == ext_ref+++def test_update_attribute_by_both_id_and_external_reference(+ staff_api_client, color_attribute, permission_manage_product_types_and_attributes+):+ # given+ query = UPDATE_ATTRIBUTE_BY_EXTERNAL_REFERENCE_MUTATION+ variables = {"input": {}, "externalReference": "whatever", "id": "whatever"}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["attributeUpdate"]+ assert not data["attribute"]+ assert (+ data["errors"][0]["message"]+ == "Argument 'id' cannot be combined with 'external_reference'"+ )+++def test_update_attribute_by_external_reference_not_existing(+ staff_api_client, color_attribute, permission_manage_product_types_and_attributes+):+ # given+ query = UPDATE_ATTRIBUTE_BY_EXTERNAL_REFERENCE_MUTATION+ ext_ref = "non-existing-ext-ref"+ variables = {+ "input": {},+ "externalReference": ext_ref,+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["attributeUpdate"]+ assert not data["attribute"]+ assert data["errors"][0]["message"] == f"Couldn't resolve to a node: {ext_ref}"+ assert data["errors"][0]["field"] == "externalReference"+++def test_update_attribute_with_non_unique_external_reference(+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+ numeric_attribute,+):+ # given+ query = UPDATE_ATTRIBUTE_BY_EXTERNAL_REFERENCE_MUTATION++ ext_ref = "test-ext-ref"+ color_attribute.external_reference = ext_ref+ color_attribute.save(update_fields=["external_reference"])++ attribute_id = graphene.Node.to_global_id("Attribute", numeric_attribute.id)++ variables = {+ "input": {"externalReference": ext_ref},+ "id": attribute_id,+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["attributeUpdate"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == AttributeErrorCode.UNIQUE.name+ assert error["message"] == "Attribute with this External reference already exists."diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.pyindex bd003c670f..13de989804 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.py@@ -35,12 +35,13 @@ def test_validate_value_is_unique(color_attribute):CREATE_ATTRIBUTE_VALUE_MUTATION = """mutation createAttributeValue(- $attributeId: ID!, $name: String!,+ $attributeId: ID!, $name: String!, $externalReference: String,$value: String, $fileUrl: String, $contentType: String) {attributeValueCreate(attribute: $attributeId, input: {- name: $name, value: $value, fileUrl: $fileUrl, contentType: $contentType+ name: $name, value: $value, fileUrl: $fileUrl,+ contentType: $contentType, externalReference: $externalReference}) {errors {field@@ -64,6 +65,7 @@ CREATE_ATTRIBUTE_VALUE_MUTATION = """attributeValue {nameslug+ externalReference}}}@@ -78,7 +80,12 @@ def test_create_attribute_value(query = CREATE_ATTRIBUTE_VALUE_MUTATIONattribute_id = graphene.Node.to_global_id("Attribute", attribute.id)name = "test name"- variables = {"name": name, "attributeId": attribute_id}+ external_reference = "test-ext-ref"+ variables = {+ "name": name,+ "attributeId": attribute_id,+ "externalReference": external_reference,+ }# whenresponse = staff_api_client.post_graphql(@@ -93,6 +100,7 @@ def test_create_attribute_value(attr_data = data["attributeValue"]assert attr_data["name"] == nameassert attr_data["slug"] == slugify(name)+ assert attr_data["externalReference"] == external_referenceassert name in [value["node"]["name"] for value in data["attribute"]["choices"]["edges"]]@@ -389,3 +397,37 @@ def test_create_attribute_value_capitalized_name(data = content["data"]["attributeValueCreate"]assert not data["errors"]assert data["attributeValue"]["slug"] == "red-2"+++def test_create_attribute_value_with_non_unique_external_reference(+ staff_api_client, color_attribute, permission_manage_products+):+ # given+ query = CREATE_ATTRIBUTE_VALUE_MUTATION++ ext_ref = "test-ext-ref"+ value = color_attribute.values.first()+ value.external_reference = ext_ref+ value.save(update_fields=["external_reference"])+ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)++ variables = {+ "name": "some value name",+ "attributeId": attribute_id,+ "externalReference": ext_ref,+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["attributeValueCreate"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == AttributeErrorCode.UNIQUE.name+ assert (+ error["message"]+ == "Attribute value with this External reference already exists."+ )diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.pyindex b384b84434..3957611db9 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py@@ -10,6 +10,7 @@ from .....attribute.utils import associate_attribute_values_to_instancefrom .....core.utils.json_serializer import CustomJsonEncoderfrom .....webhook.event_types import WebhookEventAsyncTypefrom .....webhook.payloads import generate_meta, generate_requestor+from ....tests.utils import get_graphql_contentATTRIBUTE_VALUE_DELETE_MUTATION = """mutation AttributeValueDelete($id: ID!) {@@ -221,3 +222,93 @@ def test_delete_attribute_value_product_search_document_updated_variant_attribut# thenwith pytest.raises(value._meta.model.DoesNotExist):value.refresh_from_db()+++ATTRIBUTE_VALUE_DELETE_BY_EXTERNAL_REFERENCE = """+ mutation AttributeValueDelete($id: ID, $externalReference: String) {+ attributeValueDelete(id: $id, externalReference: $externalReference) {+ attributeValue {+ id+ externalReference+ }+ errors {+ field+ message+ }+ }+ }+"""+++def test_delete_attribute_value_by_external_reference(+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ value = color_attribute.values.get(name="Red")+ query = ATTRIBUTE_VALUE_DELETE_BY_EXTERNAL_REFERENCE+ ext_ref = "test-ext-ref"+ value.external_reference = ext_ref+ value.save(update_fields=["external_reference"])+ variables = {"externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["attributeValueDelete"]+ with pytest.raises(value._meta.model.DoesNotExist):+ value.refresh_from_db()+ assert data["attributeValue"]["externalReference"] == ext_ref+ assert (+ graphene.Node.to_global_id("AttributeValue", value.id)+ == data["attributeValue"]["id"]+ )+++def test_delete_attribute_value_by_both_id_and_external_reference(+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ query = ATTRIBUTE_VALUE_DELETE_BY_EXTERNAL_REFERENCE+ variables = {"externalReference": "whatever", "id": "whatever"}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["attributeValueDelete"]["errors"]+ assert (+ errors[0]["message"]+ == "Argument 'id' cannot be combined with 'external_reference'"+ )+++def test_delete_attribute_value_by_external_reference_not_existing(+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ query = ATTRIBUTE_VALUE_DELETE_BY_EXTERNAL_REFERENCE+ ext_ref = "non-existing-ext-ref"+ variables = {"externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["attributeValueDelete"]["errors"]+ assert errors[0]["message"] == f"Couldn't resolve to a node: {ext_ref}"diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.pyindex 2bc569248c..48ce3536b1 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py@@ -15,10 +15,8 @@ from .....webhook.payloads import generate_meta, generate_requestorfrom ....tests.utils import get_graphql_contentUPDATE_ATTRIBUTE_VALUE_MUTATION = """-mutation AttributeValueUpdate(- $id: ID!, $input: AttributeValueUpdateInput!) {- attributeValueUpdate(- id: $id, input: $input) {+mutation AttributeValueUpdate($id: ID!, $input: AttributeValueUpdateInput!) {+ attributeValueUpdate(id: $id, input: $input) {errors {fieldmessage@@ -28,6 +26,7 @@ mutation AttributeValueUpdate(nameslugvalue+ externalReferencefile {urlcontentType@@ -57,7 +56,14 @@ def test_update_attribute_value(value = pink_attribute_valuenode_id = graphene.Node.to_global_id("AttributeValue", value.id)name = "Crimson name"- variables = {"input": {"name": name}, "id": node_id}+ external_reference = "test-ext-ref"+ variables = {+ "id": node_id,+ "input": {+ "name": name,+ "externalReference": external_reference,+ },+ }# whenresponse = staff_api_client.post_graphql(@@ -70,6 +76,11 @@ def test_update_attribute_value(value.refresh_from_db()assert data["attributeValue"]["name"] == name == value.nameassert data["attributeValue"]["slug"] == slugify(name)+ assert (+ data["attributeValue"]["externalReference"]+ == external_reference+ == value.external_reference+ )assert name in [value["node"]["name"] for value in data["attribute"]["choices"]["edges"]]@@ -461,3 +472,146 @@ def test_update_attribute_value_swatch_attr_value(assert data["attributeValue"]["name"] == value.nameassert data["attributeValue"]["slug"] == value.slugassert data["attributeValue"]["value"] == new_value+++UPDATE_ATTRIBUTE_VALUE_BY_EXTERNAL_REFERENCE_MUTATION = """+mutation AttributeValueUpdate(+ $id: ID, $externalReference: String, $input: AttributeValueUpdateInput!+) {+ attributeValueUpdate(+ id: $id, externalReference: $externalReference, input: $input+ ) {+ errors {+ field+ message+ code+ }+ attributeValue {+ name+ id+ externalReference+ }+ }+}+"""+++def test_update_attribute_value_by_external_reference(+ staff_api_client,+ pink_attribute_value,+ permission_manage_product_types_and_attributes,+):+ # given+ query = UPDATE_ATTRIBUTE_VALUE_BY_EXTERNAL_REFERENCE_MUTATION+ value = pink_attribute_value+ new_name = "updated name"+ ext_ref = "test-ext-ref"+ value.external_reference = ext_ref+ value.save(update_fields=["external_reference"])++ variables = {+ "input": {"name": new_name},+ "externalReference": ext_ref,+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ # then+ value.refresh_from_db()+ data = content["data"]["attributeValueUpdate"]+ assert not data["errors"]+ assert data["attributeValue"]["name"] == new_name == value.name+ assert data["attributeValue"]["id"] == graphene.Node.to_global_id(+ "AttributeValue", value.id+ )+ assert data["attributeValue"]["externalReference"] == ext_ref+++def test_update_attribute_value_by_both_id_and_external_reference(+ staff_api_client,+ pink_attribute_value,+ permission_manage_product_types_and_attributes,+):+ # given+ query = UPDATE_ATTRIBUTE_VALUE_BY_EXTERNAL_REFERENCE_MUTATION+ variables = {"input": {}, "externalReference": "whatever", "id": "whatever"}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["attributeValueUpdate"]+ assert not data["attributeValue"]+ assert (+ data["errors"][0]["message"]+ == "Argument 'id' cannot be combined with 'external_reference'"+ )+++def test_update_attribute_value_by_external_reference_not_existing(+ staff_api_client,+ pink_attribute_value,+ permission_manage_product_types_and_attributes,+):+ # given+ query = UPDATE_ATTRIBUTE_VALUE_BY_EXTERNAL_REFERENCE_MUTATION+ ext_ref = "non-existing-ext-ref"+ variables = {+ "input": {},+ "externalReference": ext_ref,+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["attributeValueUpdate"]+ assert not data["attributeValue"]+ assert data["errors"][0]["message"] == f"Couldn't resolve to a node: {ext_ref}"+ assert data["errors"][0]["field"] == "externalReference"+++def test_update_attribute_value_with_non_unique_external_reference(+ staff_api_client,+ color_attribute,+ numeric_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ query = UPDATE_ATTRIBUTE_VALUE_BY_EXTERNAL_REFERENCE_MUTATION+ value_1 = color_attribute.values.first()+ ext_ref = "test-ext-ref"+ value_1.external_reference = ext_ref+ value_1.save(update_fields=["external_reference"])+ value_2 = numeric_attribute.values.first()+ value_2_id = graphene.Node.to_global_id("AttributeValue", value_2.id)++ variables = {+ "input": {"externalReference": ext_ref},+ "id": value_2_id,+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["attributeValueUpdate"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == AttributeErrorCode.UNIQUE.name+ assert (+ error["message"]+ == "Attribute value with this External reference already exists."+ )diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_query.py b/saleor/graphql/attribute/tests/queries/test_attribute_query.pyindex 6eb9dbff07..34425b434a 100644--- a/saleor/graphql/attribute/tests/queries/test_attribute_query.py+++ b/saleor/graphql/attribute/tests/queries/test_attribute_query.py@@ -85,7 +85,6 @@ QUERY_ATTRIBUTE = """}}}-}valueRequiredvisibleInStorefront@@ -713,3 +712,38 @@ def test_attributes_with_choice_flag("-", "_")assert content["data"]["attribute"]["withChoices"] == expected_with_choice_return+++QUERY_ATTRIBUTE_BY_EXTERNAL_REFERENCE = """+ query($id: ID, $externalReference: String) {+ attribute(id: $id, externalReference: $externalReference) {+ id+ externalReference+ }+ }+"""+++def test_get_attribute_by_external_reference(+ staff_api_client, color_attribute_without_values, permission_manage_products+):+ # given+ attribute = color_attribute_without_values+ ext_ref = "test-ext-id"+ attribute.external_reference = ext_ref+ attribute.save(update_fields=["external_reference"])+ variables = {"externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ QUERY_ATTRIBUTE_BY_EXTERNAL_REFERENCE,+ variables=variables,+ permissions=(permission_manage_products,),+ check_no_permissions=False,+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["attribute"]+ assert data["externalReference"] == ext_ref+ assert data["id"] == graphene.Node.to_global_id("Attribute", attribute.id)diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.pyindex 611ba90081..98e95926a5 100644--- a/saleor/graphql/attribute/types.py+++ b/saleor/graphql/attribute/types.py@@ -15,7 +15,12 @@ from ..core.connection import (create_connection_slice,filter_connection_queryset,)-from ..core.descriptions import ADDED_IN_31, ADDED_IN_39, DEPRECATED_IN_3X_FIELD+from ..core.descriptions import (+ ADDED_IN_31,+ ADDED_IN_39,+ ADDED_IN_310,+ DEPRECATED_IN_3X_FIELD,+)from ..core.enums import MeasurementUnitsEnumfrom ..core.fields import ConnectionField, FilterConnectionField, JSONStringfrom ..core.scalars import Date@@ -65,6 +70,10 @@ class AttributeValue(ModelObjectType):date_time = graphene.DateTime(description=AttributeValueDescriptions.DATE_TIME, required=False)+ external_reference = graphene.String(+ description=f"External ID of this attribute value. {ADDED_IN_310}",+ required=False,+ )class Meta:description = "Represents a value of an attribute."@@ -231,6 +240,10 @@ class Attribute(ModelObjectType):"saleor.graphql.product.types.ProductTypeCountableConnection",required=True,)+ external_reference = graphene.String(+ description=f"External ID of this attribute. {ADDED_IN_310}",+ required=False,+ )class Meta:description = (diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex b604c16f8b..4903cb86e8 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -18,7 +18,7 @@ from graphene import ObjectTypefrom graphene.types.mutation import MutationOptionsfrom graphql.error import GraphQLError-from ...core.error_codes import MetadataErrorCode+from ...core.error_codes import CoreErrorCode, MetadataErrorCodefrom ...core.exceptions import PermissionDeniedfrom ...core.permissions import (AuthorizationFilters,@@ -26,6 +26,8 @@ from ...core.permissions import (one_of_permissions_or_auth_filter_required,)from ...core.utils.events import call_event+from ..core.utils import ext_ref_to_global_id_or_error+from ..core.validators import validate_one_of_args_is_in_mutationfrom ..meta.permissions import PRIVATE_META_PERMISSION_MAP, PUBLIC_META_PERMISSION_MAPfrom ..payment.utils import metadata_contains_empty_keyfrom ..plugins.dataloaders import get_plugin_manager_promise@@ -649,6 +651,36 @@ class ModelMutation(BaseMutation):return cls.success_response(instance)+class ModelWithExtRefMutation(ModelMutation):+ class Meta:+ abstract = True++ @classmethod+ def get_object_id(cls, **data):+ """Resolve object id by given id or external reference."""+ object_id, ext_ref = data.get("id"), data.get("external_reference")+ validate_one_of_args_is_in_mutation(+ CoreErrorCode, "id", object_id, "external_reference", ext_ref+ )++ if ext_ref and not object_id:+ object_id = ext_ref_to_global_id_or_error(cls._meta.model, ext_ref)++ return object_id++ @classmethod+ def get_instance(cls, info, **data):+ """Retrieve an instance from the supplied global id.++ The expected graphene type can be lazy (str).+ """+ object_id = cls.get_object_id(**data)+ qs = data.get("qs")+ if object_id:+ model_type = cls.get_type_for_model()+ return cls.get_node_or_error(info, object_id, only_type=model_type, qs=qs)++class ModelDeleteMutation(ModelMutation):class Meta:abstract = True@@ -664,13 +696,9 @@ class ModelDeleteMutation(ModelMutation):@classmethoddef perform_mutation(cls, _root, info, **data):"""Perform a mutation that deletes a model instance."""- node_id = data.get("id")- model_type = cls.get_type_for_model()- instance = cls.get_node_or_error(info, node_id, only_type=model_type)-- if instance:- cls.clean_instance(info, instance)+ instance = cls.get_instance(info, **data)+ cls.clean_instance(info, instance)db_id = instance.idinstance.delete()diff --git a/saleor/graphql/core/tests/test_core.py b/saleor/graphql/core/tests/test_core.pyindex d6ed222369..f3c3742ac6 100644--- a/saleor/graphql/core/tests/test_core.py+++ b/saleor/graphql/core/tests/test_core.py@@ -18,9 +18,14 @@ from ...utils import requestor_is_superuserfrom ...utils.filters import filter_range_field, reporting_period_to_datefrom ..enums import ReportingPeriodfrom ..filters import EnumFilter-from ..mutations import BaseMutation+from ..mutations import BaseMutation, ModelWithExtRefMutationfrom ..types import FilterInputObjectType-from ..utils import add_hash_to_file_name, get_duplicated_values, snake_to_camel_case+from ..utils import (+ add_hash_to_file_name,+ ext_ref_to_global_id_or_error,+ get_duplicated_values,+ snake_to_camel_case,+)from . import ErrorTest@@ -297,3 +302,40 @@ def test_add_hash_to_file_name(image, media_root):file_name, format = os.path.splitext(image._name)assert image._name.startswith(file_name)assert image._name.endswith(format)+++def test_external_reference_to_global_id(product):+ # given+ product.external_reference = "test-ext-id"+ product.save(update_fields=["external_reference"])+ model = product.__class__+ # when+ global_id = ext_ref_to_global_id_or_error(model, product.external_reference)+ # then+ assert global_id == graphene.Node.to_global_id(model.__name__, product.id)+++def test_external_reference_to_global_id_non_existing(product):+ # given+ product.external_reference = None+ product.save(update_fields=["external_reference"])+ non_existing_id = "non-existing-ext-ref"+ model = product.__class__+ # when+ with pytest.raises(ValidationError) as e:+ ext_ref_to_global_id_or_error(model, non_existing_id)+ # then+ assert e.value.messages[0] == f"Couldn't resolve to a node: {non_existing_id}"+++def test_get_instance_by_both_id_and_external_reference():+ # given+ data = {"id": "test-id", "external_reference": "test-ext-id"}+ # when+ with pytest.raises(ValidationError) as e:+ ModelWithExtRefMutation.get_object_id(**data)+ # then+ assert (+ e.value.messages[0]+ == "Argument 'id' cannot be combined with 'external_reference'"+ )diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.pyindex 1a85ff6478..9dc0cabb9c 100644--- a/saleor/graphql/core/utils/__init__.py+++ b/saleor/graphql/core/utils/__init__.py@@ -4,6 +4,7 @@ import secretsfrom typing import Unionimport graphene+from django.core.exceptions import ValidationErrorfrom graphene import ObjectTypefrom graphql.error import GraphQLError@@ -92,3 +93,23 @@ def add_hash_to_file_name(file):hash = secrets.token_hex(nbytes=4)new_name = f"{file_name}_{hash}{format}"file._name = new_name+++def ext_ref_to_global_id_or_error(model, external_reference):+ """Convert external reference to graphen global id."""+ internal_id = (+ model.objects.filter(external_reference=external_reference)+ .values_list("id", flat=True)+ .first()+ )+ if internal_id:+ return graphene.Node.to_global_id(model.__name__, internal_id)+ else:+ raise ValidationError(+ {+ "externalReference": ValidationError(+ f"Couldn't resolve to a node: {external_reference}",+ code="not_found",+ )+ }+ )diff --git a/saleor/graphql/core/utils/resolvers.py b/saleor/graphql/core/utils/resolvers.pynew file mode 100644index 0000000000..2b802e62a9--- /dev/null+++ b/saleor/graphql/core/utils/resolvers.py@@ -0,0 +1,24 @@+from ...core.validators import validate_one_of_args_is_in_query+from . import from_global_id_or_error+++def resolve_by_global_id_or_ext_ref(model, id, external_reference):+ validate_one_of_args_is_in_query("id", id, "external_reference", external_reference)+ if id:+ _, id = from_global_id_or_error(id, model.__name__)+ return model.objects.filter(id=id).first()+ else:+ return model.objects.filter(external_reference=external_reference).first()+++def resolve_by_global_id_slug_or_ext_ref(model, id, slug, external_reference):+ validate_one_of_args_is_in_query(+ "id", id, "slug", slug, "external_reference", external_reference+ )+ if id:+ _, id = from_global_id_or_error(id, model.__name__)+ return model.objects.filter(id=id).first()+ elif slug:+ return model.objects.filter(slug=slug).first()+ else:+ return model.objects.filter(external_reference=external_reference).first()diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.pyindex a2c429bf08..c49f45181b 100644--- a/saleor/graphql/order/mutations/draft_order_create.py+++ b/saleor/graphql/order/mutations/draft_order_create.py@@ -24,7 +24,7 @@ from ...account.i18n import I18nMixinfrom ...account.types import AddressInputfrom ...app.dataloaders import get_app_promisefrom ...channel.types import Channel-from ...core.descriptions import ADDED_IN_36, PREVIEW_FEATURE+from ...core.descriptions import ADDED_IN_36, ADDED_IN_310, PREVIEW_FEATUREfrom ...core.mutations import ModelMutationfrom ...core.scalars import PositiveDecimalfrom ...core.types import NonNullList, OrderError@@ -84,6 +84,9 @@ class DraftOrderInput(InputObjectType):"see the order details. URL in RFC 1808 format."),)+ external_reference = graphene.String(+ description="External ID of this order." + ADDED_IN_310, required=False+ )class DraftOrderCreateInput(DraftOrderInput):diff --git a/saleor/graphql/order/mutations/draft_order_delete.py b/saleor/graphql/order/mutations/draft_order_delete.pyindex 5af306d61c..1573e34c0a 100644--- a/saleor/graphql/order/mutations/draft_order_delete.py+++ b/saleor/graphql/order/mutations/draft_order_delete.py@@ -5,15 +5,20 @@ from ....core.permissions import OrderPermissionsfrom ....core.tracing import traced_atomic_transactionfrom ....order import OrderStatus, modelsfrom ....order.error_codes import OrderErrorCode-from ...core.mutations import ModelDeleteMutation+from ...core.descriptions import ADDED_IN_310+from ...core.mutations import ModelDeleteMutation, ModelWithExtRefMutationfrom ...core.types import OrderErrorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Order-class DraftOrderDelete(ModelDeleteMutation):+class DraftOrderDelete(ModelDeleteMutation, ModelWithExtRefMutation):class Arguments:- id = graphene.ID(required=True, description="ID of a draft order to delete.")+ id = graphene.ID(required=False, description="ID of a product to delete.")+ external_reference = graphene.String(+ required=False,+ description=f"External ID of a product to delete. {ADDED_IN_310}",+ )class Meta:description = "Deletes a draft order."diff --git a/saleor/graphql/order/mutations/draft_order_update.py b/saleor/graphql/order/mutations/draft_order_update.pyindex f8ad838668..db53520d26 100644--- a/saleor/graphql/order/mutations/draft_order_update.py+++ b/saleor/graphql/order/mutations/draft_order_update.py@@ -5,15 +5,21 @@ from ....core.permissions import OrderPermissionsfrom ....order import OrderStatus, modelsfrom ....order.error_codes import OrderErrorCodefrom ...app.dataloaders import get_app_promise+from ...core.descriptions import ADDED_IN_310+from ...core.mutations import ModelWithExtRefMutationfrom ...core.types import OrderErrorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Orderfrom .draft_order_create import DraftOrderCreate, DraftOrderInput-class DraftOrderUpdate(DraftOrderCreate):+class DraftOrderUpdate(DraftOrderCreate, ModelWithExtRefMutation):class Arguments:- id = graphene.ID(required=True, description="ID of a draft order to update.")+ id = graphene.ID(required=False, description="ID of a draft order to update.")+ external_reference = graphene.String(+ required=False,+ description=f"External ID of a draft order to update. {ADDED_IN_310}",+ )input = DraftOrderInput(required=True, description="Fields required to update an order.")diff --git a/saleor/graphql/order/mutations/order_update.py b/saleor/graphql/order/mutations/order_update.pyindex a6a7f19a7a..a9acf62e9f 100644--- a/saleor/graphql/order/mutations/order_update.py+++ b/saleor/graphql/order/mutations/order_update.py@@ -10,6 +10,8 @@ from ....order.error_codes import OrderErrorCodefrom ....order.search import prepare_order_search_vector_valuefrom ....order.utils import invalidate_order_pricesfrom ...account.types import AddressInput+from ...core.descriptions import ADDED_IN_310+from ...core.mutations import ModelWithExtRefMutationfrom ...core.types import OrderErrorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Order@@ -20,11 +22,18 @@ class OrderUpdateInput(graphene.InputObjectType):billing_address = AddressInput(description="Billing address of the customer.")user_email = graphene.String(description="Email address of the customer.")shipping_address = AddressInput(description="Shipping address of the customer.")+ external_reference = graphene.String(+ description="External ID of this order." + ADDED_IN_310, required=False+ )-class OrderUpdate(DraftOrderCreate):+class OrderUpdate(DraftOrderCreate, ModelWithExtRefMutation):class Arguments:- id = graphene.ID(required=True, description="ID of an order to update.")+ id = graphene.ID(required=False, description="ID of an order to update.")+ external_reference = graphene.String(+ required=False,+ description=f"External ID of an order to update. {ADDED_IN_310}",+ )input = OrderUpdateInput(required=True, description="Fields required to update an order.")@@ -42,7 +51,12 @@ class OrderUpdate(DraftOrderCreate):draft_order_cleaned_input = super().clean_input(info, instance, data)# We must to filter out field added by DraftOrderUpdate- editable_fields = ["billing_address", "shipping_address", "user_email"]+ editable_fields = [+ "billing_address",+ "shipping_address",+ "user_email",+ "external_reference",+ ]cleaned_input = {}for key in draft_order_cleaned_input:if key in editable_fields:diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.pyindex 3740b3c0c6..82f3bcbac7 100644--- a/saleor/graphql/order/schema.py+++ b/saleor/graphql/order/schema.py@@ -4,13 +4,15 @@ import graphenefrom graphql import GraphQLErrorfrom ...core.permissions import OrderPermissions+from ...order import modelsfrom ..core.connection import create_connection_slice, filter_connection_queryset-from ..core.descriptions import DEPRECATED_IN_3X_FIELD+from ..core.descriptions import ADDED_IN_310, DEPRECATED_IN_3X_FIELDfrom ..core.enums import ReportingPeriodfrom ..core.fields import ConnectionField, FilterConnectionField, PermissionsFieldfrom ..core.scalars import UUIDfrom ..core.types import FilterInputObjectType, TaxedMoney-from ..core.utils import from_global_id_or_error+from ..core.utils import ext_ref_to_global_id_or_error, from_global_id_or_error+from ..core.validators import validate_one_of_args_is_in_queryfrom .bulk_mutations.draft_orders import DraftOrderBulkDelete, DraftOrderLinesBulkDeletefrom .bulk_mutations.orders import OrderBulkCancelfrom .filters import DraftOrderFilter, OrderFilter@@ -84,8 +86,11 @@ class OrderQueries(graphene.ObjectType):)order = graphene.Field(Order,- description="Look up an order by ID.",- id=graphene.Argument(graphene.ID, description="ID of an order.", required=True),+ description="Look up an order by ID or external reference.",+ id=graphene.Argument(graphene.ID, description="ID of an order."),+ external_reference=graphene.Argument(+ graphene.String, description=f"External ID of an order. {ADDED_IN_310}"+ ),)orders = FilterConnectionField(OrderCountableConnection,@@ -134,7 +139,13 @@ class OrderQueries(graphene.ObjectType):@staticmethoddef resolve_order(_root, _info, **data):- _, id = from_global_id_or_error(data.get("id"), Order)+ node_id = data.get("id")+ ext_ref = data.get("external_reference")+ validate_one_of_args_is_in_query("id", node_id, "external_reference", ext_ref)++ if ext_ref:+ node_id = ext_ref_to_global_id_or_error(models.Order, ext_ref)+ _, id = from_global_id_or_error(node_id, Order)return resolve_order(id)@staticmethoddiff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.pyindex 12aeee1baa..fa05b3e980 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py@@ -20,58 +20,63 @@ DRAFT_ORDER_CREATE_MUTATION = """$user: ID, $discount: PositiveDecimal, $lines: [OrderLineCreateInput!],$shippingAddress: AddressInput, $billingAddress: AddressInput,$shippingMethod: ID, $voucher: ID, $customerNote: String, $channel: ID,- $redirectUrl: String+ $redirectUrl: String, $externalReference: String) {draftOrderCreate(- input: {user: $user, discount: $discount,- lines: $lines, shippingAddress: $shippingAddress,- billingAddress: $billingAddress,- shippingMethod: $shippingMethod, voucher: $voucher,- channelId: $channel,- redirectUrl: $redirectUrl,- customerNote: $customerNote}) {- errors {- field+ input: {+ user: $user, discount: $discount,+ lines: $lines, shippingAddress: $shippingAddress,+ billingAddress: $billingAddress,+ shippingMethod: $shippingMethod, voucher: $voucher,+ channelId: $channel,+ redirectUrl: $redirectUrl,+ customerNote: $customerNote,+ externalReference: $externalReference+ }+ ) {+ errors {+ field+ code+ variants+ message+ addressType+ }+ order {+ id+ discount {+ amount+ }+ discountName+ redirectUrl+ lines {+ productName+ productSku+ quantity+ }+ billingAddress{+ city+ streetAddress1+ postalCode+ }+ shippingAddress{+ city+ streetAddress1+ postalCode+ }+ status+ voucher {code- variants- message- addressType}- order {- id- discount {+ customerNote+ total {+ gross {amount}- discountName- redirectUrl- lines {- productName- productSku- quantity- }- billingAddress{- city- streetAddress1- postalCode- }- shippingAddress{- city- streetAddress1- postalCode- }- status- voucher {- code- }- customerNote- total {- gross {- amount- }- }- shippingMethodName}+ shippingMethodName+ externalReference}+ }}"""@@ -111,6 +116,7 @@ def test_draft_order_create(voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)redirect_url = "https://www.example.com"+ external_reference = "test-ext-ref"variables = {"user": user_id,@@ -123,6 +129,7 @@ def test_draft_order_create("customerNote": customer_note,"channel": channel_id,"redirectUrl": redirect_url,+ "externalReference": external_reference,}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_orders]@@ -134,6 +141,7 @@ def test_draft_order_create(assert data["voucher"]["code"] == voucher.codeassert data["customerNote"] == customer_noteassert data["redirectUrl"] == redirect_url+ assert data["externalReference"] == external_referenceassert (data["billingAddress"]["streetAddress1"]== graphql_address_data["streetAddress1"]@@ -150,6 +158,7 @@ def test_draft_order_create(assert order.billing_addressassert order.shipping_addressassert order.search_vector+ assert order.external_reference == external_reference# Ensure the correct event was createdcreated_draft_event = OrderEvent.objects.get(@@ -1174,3 +1183,32 @@ def test_draft_order_create_update_display_gross_prices(order = Order.objects.get(id=order_pk)assert not order.display_gross_prices+++def test_draft_order_create_with_non_unique_external_reference(+ staff_api_client,+ permission_manage_orders,+ channel_USD,+ order,+):+ # given+ query = DRAFT_ORDER_CREATE_MUTATION++ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ ext_ref = "test-ext-ref"+ order.external_reference = ext_ref+ order.save(update_fields=["external_reference"])++ variables = {"channel": channel_id, "externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["draftOrderCreate"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == OrderErrorCode.UNIQUE.name+ assert error["message"] == "Order with this External reference already exists."diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_delete.py b/saleor/graphql/order/tests/mutations/test_draft_order_delete.pyindex 8db7a1d389..a2728f6d24 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_delete.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_delete.py@@ -91,3 +91,84 @@ def test_draft_order_delete_non_draft_order(assert len(account_errors) == 1assert account_errors[0]["field"] == "id"assert account_errors[0]["code"] == OrderErrorCode.INVALID.name+++DRAFT_ORDER_DELETE_BY_EXTERNAL_REFERENCE = """+ mutation draftDelete($id: ID, $externalReference: String) {+ draftOrderDelete(id: $id, externalReference: $externalReference) {+ order {+ id+ externalReference+ }+ errors {+ field+ message+ }+ }+}+"""+++def test_draft_order_delete_by_external_reference(+ staff_api_client, permission_manage_orders, draft_order+):+ # given+ order = draft_order+ query = DRAFT_ORDER_DELETE_BY_EXTERNAL_REFERENCE+ ext_ref = "test-ext-ref"+ order.external_reference = ext_ref+ order.save(update_fields=["external_reference"])+ variables = {"externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["draftOrderDelete"]+ with pytest.raises(order._meta.model.DoesNotExist):+ order.refresh_from_db()+ assert graphene.Node.to_global_id("Order", order.id) == data["order"]["id"]+ assert data["order"]["externalReference"] == order.external_reference+++def test_draft_order_delete_by_both_id_and_external_reference(+ staff_api_client, permission_manage_orders+):+ # given+ query = DRAFT_ORDER_DELETE_BY_EXTERNAL_REFERENCE+ variables = {"externalReference": "whatever", "id": "whatever"}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["draftOrderDelete"]["errors"]+ assert (+ errors[0]["message"]+ == "Argument 'id' cannot be combined with 'external_reference'"+ )+++def test_draft_order_delete_by_external_reference_not_existing(+ staff_api_client, permission_manage_orders+):+ # given+ query = DRAFT_ORDER_DELETE_BY_EXTERNAL_REFERENCE+ ext_ref = "non-existing-ext-ref"+ variables = {"externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["draftOrderDelete"]["errors"]+ assert errors[0]["message"] == f"Couldn't resolve to a node: {ext_ref}"diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_update.py b/saleor/graphql/order/tests/mutations/test_draft_order_update.pyindex b59fd67296..89ad8a1ba5 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py@@ -86,14 +86,17 @@ def test_draft_order_update_voucher_not_available(DRAFT_ORDER_UPDATE_MUTATION = """mutation draftUpdate(- $id: ID!, $voucher: ID!, $customerNote: String, $shippingAddress: AddressInput+ $id: ID!, $voucher: ID!, $customerNote: String, $shippingAddress: AddressInput,+ $externalReference: String) {- draftOrderUpdate(id: $id,- input: {- voucher: $voucher,- customerNote: $customerNote,- shippingAddress: $shippingAddress,- }) {+ draftOrderUpdate(+ id: $id,+ input: {+ voucher: $voucher,+ customerNote: $customerNote,+ shippingAddress: $shippingAddress,+ externalReference: $externalReference+ }) {errors {fieldmessage@@ -101,6 +104,7 @@ DRAFT_ORDER_UPDATE_MUTATION = """}order {userEmail+ externalReference}}}@@ -117,10 +121,12 @@ def test_draft_order_update(order_id = graphene.Node.to_global_id("Order", order.id)voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)customer_note = "Test customer note"+ external_reference = "test-ext-ref"variables = {"id": order_id,"voucher": voucher_id,"customerNote": customer_note,+ "externalReference": external_reference,}response = staff_api_client.post_graphql(@@ -133,6 +139,11 @@ def test_draft_order_update(assert order.voucherassert order.customer_note == customer_noteassert order.search_vector+ assert (+ data["order"]["externalReference"]+ == external_reference+ == order.external_reference+ )def test_draft_order_update_with_non_draft_order(@@ -335,3 +346,146 @@ def test_draft_order_update_assign_user_when_existing_customer_email_provided(assert not data["errors"]assert order.user == userassert order.user_email == user_email+++DRAFT_ORDER_UPDATE_BY_EXTERNAL_REFERENCE = """+ mutation draftUpdate(+ $id: ID+ $externalReference: String+ $input: DraftOrderInput!+ ) {+ draftOrderUpdate(+ id: $id+ externalReference: $externalReference+ input: $input+ ) {+ errors {+ field+ message+ code+ }+ order {+ id+ externalReference+ voucher {+ id+ }+ }+ }+ }+ """+++def test_draft_order_update_by_external_reference(+ staff_api_client, permission_manage_orders, draft_order, voucher_free_shipping+):+ # given+ query = DRAFT_ORDER_UPDATE_BY_EXTERNAL_REFERENCE++ order = draft_order+ assert not order.voucher+ voucher = voucher_free_shipping+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)+ ext_ref = "test-ext-ref"+ order.external_reference = ext_ref+ order.save(update_fields=["external_reference"])++ variables = {+ "externalReference": ext_ref,+ "input": {"voucher": voucher_id},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["draftOrderUpdate"]+ assert not data["errors"]+ assert data["order"]["externalReference"] == ext_ref+ assert data["order"]["id"] == graphene.Node.to_global_id("Order", order.id)+ assert data["order"]["voucher"]["id"] == voucher_id+ order.refresh_from_db()+ assert order.voucher+++def test_draft_order_update_by_both_id_and_external_reference(+ staff_api_client, permission_manage_orders, voucher_free_shipping+):+ # given+ query = DRAFT_ORDER_UPDATE_BY_EXTERNAL_REFERENCE++ variables = {+ "id": "test-id",+ "externalReference": "test-ext-ref",+ "input": {},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["draftOrderUpdate"]+ assert not data["order"]+ assert (+ data["errors"][0]["message"]+ == "Argument 'id' cannot be combined with 'external_reference'"+ )+++def test_draft_order_update_by_external_reference_not_existing(+ staff_api_client, permission_manage_orders, voucher_free_shipping+):+ # given+ query = DRAFT_ORDER_UPDATE_BY_EXTERNAL_REFERENCE+ ext_ref = "non-existing-ext-ref"+ variables = {+ "externalReference": ext_ref,+ "input": {},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["draftOrderUpdate"]+ assert not data["order"]+ assert data["errors"][0]["message"] == f"Couldn't resolve to a node: {ext_ref}"+++def test_draft_order_update_with_non_unique_external_reference(+ staff_api_client,+ permission_manage_orders,+ draft_order,+ order_list,+):+ # given+ query = DRAFT_ORDER_UPDATE_BY_EXTERNAL_REFERENCE++ draft_order_id = graphene.Node.to_global_id("Order", draft_order.pk)+ ext_ref = "test-ext-ref"+ order = order_list[1]+ order.external_reference = ext_ref+ order.save(update_fields=["external_reference"])++ variables = {"id": draft_order_id, "input": {"externalReference": ext_ref}}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["draftOrderUpdate"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == OrderErrorCode.UNIQUE.name+ assert error["message"] == "Order with this External reference already exists."diff --git a/saleor/graphql/order/tests/mutations/test_order_update.py b/saleor/graphql/order/tests/mutations/test_order_update.pyindex 1ae27ce1ac..273c4c1b43 100644--- a/saleor/graphql/order/tests/mutations/test_order_update.py+++ b/saleor/graphql/order/tests/mutations/test_order_update.py@@ -8,18 +8,25 @@ from .....product.models import ProductVariantfrom ....tests.utils import get_graphql_contentORDER_UPDATE_MUTATION = """- mutation orderUpdate($id: ID!, $email: String, $address: AddressInput) {+ mutation orderUpdate(+ $id: ID!, $email: String, $address: AddressInput, $externalReference: String+ ) {orderUpdate(- id: $id, input: {+ id: $id,+ input: {userEmail: $email,+ externalReference: $externalReference,shippingAddress: $address,- billingAddress: $address}) {+ billingAddress: $address+ }+ ) {errors {fieldcode}order {userEmail+ externalReference}}}@@ -34,6 +41,7 @@ def test_order_update(order_with_lines,graphql_address_data,):+ # givenorder = order_with_linesorder.user = Noneorder.save()@@ -42,14 +50,26 @@ def test_order_update(assert not order.shipping_address.first_name == graphql_address_data["firstName"]assert not order.billing_address.last_name == graphql_address_data["lastName"]order_id = graphene.Node.to_global_id("Order", order.id)- variables = {"id": order_id, "email": email, "address": graphql_address_data}+ external_reference = "test-ext-ref"++ variables = {+ "id": order_id,+ "email": email,+ "address": graphql_address_data,+ "externalReference": external_reference,+ }++ # whenresponse = staff_api_client.post_graphql(ORDER_UPDATE_MUTATION, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)++ # thenassert not content["data"]["orderUpdate"]["errors"]data = content["data"]["orderUpdate"]["order"]assert data["userEmail"] == email+ assert data["externalReference"] == external_referenceorder.refresh_from_db()order.shipping_address.refresh_from_db()@@ -59,6 +79,7 @@ def test_order_update(assert order.user_email == emailassert order.user is Noneassert order.status == OrderStatus.UNFULFILLED+ assert order.external_reference == external_referenceorder_updated_webhook_mock.assert_called_once_with(order)@@ -209,3 +230,143 @@ def test_order_update_user_email_existing_user(assert order.billing_address.last_name == graphql_address_data["lastName"]assert order.user_email == emailassert order.user == customer_user+++ORDER_UPDATE_BY_EXTERNAL_REFERENCE = """+ mutation orderUpdate(+ $id: ID+ $externalReference: String+ $input: OrderUpdateInput!+ ) {+ orderUpdate(+ id: $id+ externalReference: $externalReference+ input: $input+ ) {+ errors {+ field+ message+ code+ }+ order {+ id+ externalReference+ shippingAddress {+ firstName+ }+ }+ }+ }+ """+++def test_order_update_by_external_reference(+ staff_api_client, permission_manage_orders, order, graphql_address_data+):+ # given+ query = ORDER_UPDATE_BY_EXTERNAL_REFERENCE++ ext_ref = "test-ext-ref"+ order.external_reference = ext_ref+ order.save(update_fields=["external_reference"])++ assert not order.shipping_address.first_name == graphql_address_data["firstName"]+ variables = {+ "externalReference": ext_ref,+ "input": {"shippingAddress": graphql_address_data},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["orderUpdate"]+ assert not data["errors"]+ assert data["order"]["externalReference"] == ext_ref+ assert data["order"]["id"] == graphene.Node.to_global_id("Order", order.id)+ assert (+ data["order"]["shippingAddress"]["firstName"]+ == graphql_address_data["firstName"]+ )+ order.refresh_from_db()+ assert order.shipping_address.first_name == graphql_address_data["firstName"]+++def test_order_update_by_both_id_and_external_reference(+ staff_api_client, permission_manage_orders+):+ # given+ query = ORDER_UPDATE_BY_EXTERNAL_REFERENCE++ variables = {+ "id": "test-id",+ "externalReference": "test-ext-ref",+ "input": {},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["orderUpdate"]+ assert not data["order"]+ assert (+ data["errors"][0]["message"]+ == "Argument 'id' cannot be combined with 'external_reference'"+ )+++def test_order_update_by_external_reference_not_existing(+ staff_api_client, permission_manage_orders, voucher_free_shipping+):+ # given+ query = ORDER_UPDATE_BY_EXTERNAL_REFERENCE+ ext_ref = "non-existing-ext-ref"+ variables = {+ "externalReference": ext_ref,+ "input": {},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["orderUpdate"]+ assert not data["order"]+ assert data["errors"][0]["message"] == f"Couldn't resolve to a node: {ext_ref}"+++def test_order_update_with_non_unique_external_reference(+ staff_api_client, permission_manage_orders, order, order_list+):+ # given+ query = ORDER_UPDATE_BY_EXTERNAL_REFERENCE++ ext_ref = "test-ext-ref"+ order_1 = order_list[0]+ order_1.external_reference = ext_ref+ order_1.save(update_fields=["external_reference"])+ order_id = graphene.Node.to_global_id("Order", order.id)++ variables = {"id": order_id, "input": {"externalReference": ext_ref}}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["orderUpdate"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == OrderErrorCode.UNIQUE.name+ assert error["message"] == "Order with this External reference already exists."diff --git a/saleor/graphql/order/tests/queries/test_order.py b/saleor/graphql/order/tests/queries/test_order.pyindex 1e1e335d07..8f303df861 100644--- a/saleor/graphql/order/tests/queries/test_order.py+++ b/saleor/graphql/order/tests/queries/test_order.py@@ -22,6 +22,7 @@ from ....order.enums import OrderAuthorizeStatusEnum, OrderChargeStatusEnumfrom ....payment.enums import TransactionStatusEnumfrom ....payment.types import PaymentChargeStatusEnumfrom ....tests.utils import (+ assert_graphql_error_with_message,assert_no_permission,get_graphql_content,get_graphql_content_from_response,@@ -943,7 +944,7 @@ def test_order_query_in_pln_channel(QUERY_ORDER_BY_ID = """- query OrderQuery($id: ID!) {+ query OrderQuery($id: ID) {order(id: $id) {numberid@@ -1037,6 +1038,65 @@ def test_staff_query_order_with_invalid_object_type(staff_api_client, order):assert content["data"]["order"] is None+QUERY_ORDER_BY_EXTERNAL_REFERENCE = """+ query OrderQuery($externalReference: String, $id: ID) {+ order(externalReference: $externalReference, id: $id) {+ number+ id+ externalReference+ }+ }+"""+++def test_query_order_by_external_reference(user_api_client, order):+ # given+ query = QUERY_ORDER_BY_EXTERNAL_REFERENCE+ ext_ref = "test-ext-ref"+ order.external_reference = ext_ref+ order.save(update_fields=["external_reference"])+ variables = {"externalReference": ext_ref}++ # when+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["order"]+ assert data["number"] == str(order.number)+ assert data["externalReference"] == ext_ref+ assert data["id"] == graphene.Node.to_global_id("Order", order.id)+++def test_query_order_by_external_reference_and_id(user_api_client, order):+ # given+ query = QUERY_ORDER_BY_EXTERNAL_REFERENCE+ ext_ref = "test-ext-ref"+ id = "test-id"+ variables = {"externalReference": ext_ref, "id": id}++ # when+ response = user_api_client.post_graphql(query, variables)++ # then+ assert_graphql_error_with_message(+ response, "Argument 'id' cannot be combined with 'external_reference'"+ )+++def test_query_order_without_external_reference_or_id(user_api_client, order):+ # given+ query = QUERY_ORDER_BY_EXTERNAL_REFERENCE++ # when+ response = user_api_client.post_graphql(query)++ # then+ assert_graphql_error_with_message(+ response, "At least one of arguments is required: 'id', 'external_reference'."+ )++QUERY_ORDER_FIELDS_BY_ID = """query OrderQuery($id: ID!) {order(id: $id) {diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 299e969d30..b82b0b7729 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -62,6 +62,7 @@ from ..core.descriptions import (ADDED_IN_34,ADDED_IN_38,ADDED_IN_39,+ ADDED_IN_310,DEPRECATED_IN_3X_FIELD,PREVIEW_FEATURE,)@@ -1132,6 +1133,9 @@ class Order(ModelObjectType):),required=True,)+ external_reference = graphene.String(+ description=f"External ID of this order. {ADDED_IN_310}", required=False+ )class Meta:description = "Represents an order in the shop."diff --git a/saleor/graphql/product/mutations/product/product_create.py b/saleor/graphql/product/mutations/product/product_create.pyindex bba7c21bcf..9290972fc4 100644--- a/saleor/graphql/product/mutations/product/product_create.py+++ b/saleor/graphql/product/mutations/product/product_create.py@@ -13,7 +13,12 @@ from .....product.search import update_product_search_vectorfrom ....attribute.types import AttributeValueInputfrom ....attribute.utils import AttributeAssignmentMixin, AttrValuesInputfrom ....channel import ChannelContext-from ....core.descriptions import ADDED_IN_38, DEPRECATED_IN_3X_INPUT, RICH_CONTENT+from ....core.descriptions import (+ ADDED_IN_38,+ ADDED_IN_310,+ DEPRECATED_IN_3X_INPUT,+ RICH_CONTENT,+)from ....core.fields import JSONStringfrom ....core.mutations import ModelMutationfrom ....core.scalars import WeightScalar@@ -70,6 +75,9 @@ class ProductInput(graphene.InputObjectType):),required=False,)+ external_reference = graphene.String(+ description="External ID of this product." + ADDED_IN_310, required=False+ )class StockInput(graphene.InputObjectType):@@ -165,24 +173,6 @@ class ProductCreate(ModelMutation):clean_seo_fields(cleaned_input)return cleaned_input- @classmethod- def get_instance(cls, info, **data):- """Prefetch related fields that are needed to process the mutation."""- # If we are updating an instance and want to update its attributes,- # prefetch them.-- object_id = data.get("id")- if object_id and data.get("attributes"):- # Prefetches needed by AttributeAssignmentMixin and- # associate_attribute_values_to_instance- qs = cls.Meta.model.objects.prefetch_related(- "product_type__product_attributes__values",- "product_type__attributeproduct",- )- return cls.get_node_or_error(info, object_id, only_type="Product", qs=qs)-- return super().get_instance(info, **data)-@classmethoddef save(cls, info, instance, cleaned_input):with traced_atomic_transaction():diff --git a/saleor/graphql/product/mutations/product/product_delete.py b/saleor/graphql/product/mutations/product/product_delete.pyindex 509325e719..4e2dce02d2 100644--- a/saleor/graphql/product/mutations/product/product_delete.py+++ b/saleor/graphql/product/mutations/product/product_delete.py@@ -10,16 +10,21 @@ from .....order.tasks import recalculate_orders_taskfrom .....product import modelsfrom ....app.dataloaders import get_app_promisefrom ....channel import ChannelContext-from ....core.mutations import ModelDeleteMutation+from ....core.descriptions import ADDED_IN_310+from ....core.mutations import ModelDeleteMutation, ModelWithExtRefMutationfrom ....core.types import ProductErrorfrom ....plugins.dataloaders import get_plugin_manager_promisefrom ...types import Productfrom ...utils import get_draft_order_lines_data_for_variants-class ProductDelete(ModelDeleteMutation):+class ProductDelete(ModelDeleteMutation, ModelWithExtRefMutation):class Arguments:- id = graphene.ID(required=True, description="ID of a product to delete.")+ id = graphene.ID(required=False, description="ID of a product to delete.")+ external_reference = graphene.String(+ required=False,+ description=f"External ID of a product to delete. {ADDED_IN_310}",+ )class Meta:description = "Deletes a product."@@ -36,9 +41,7 @@ class ProductDelete(ModelDeleteMutation):@classmethoddef perform_mutation(cls, _root, info, **data):- node_id = data.get("id")-- instance = cls.get_node_or_error(info, node_id, only_type=Product)+ instance = cls.get_instance(info, **data)variants_id = list(instance.variants.all().values_list("id", flat=True))with traced_atomic_transaction():cls.delete_assigned_attribute_values(instance)diff --git a/saleor/graphql/product/mutations/product/product_update.py b/saleor/graphql/product/mutations/product/product_update.pyindex 575936784f..59a87b8f65 100644--- a/saleor/graphql/product/mutations/product/product_update.py+++ b/saleor/graphql/product/mutations/product/product_update.py@@ -4,10 +4,11 @@ import graphenefrom .....attribute import models as attribute_modelsfrom .....core.permissions import ProductPermissions-from .....core.tracing import traced_atomic_transactionfrom .....product import modelsfrom .....product.search import update_product_search_vectorfrom ....attribute.utils import AttributeAssignmentMixin, AttrValuesInput+from ....core.descriptions import ADDED_IN_310+from ....core.mutations import ModelWithExtRefMutationfrom ....core.types.common import ProductErrorfrom ....plugins.dataloaders import get_plugin_manager_promisefrom ...types import Product@@ -16,9 +17,13 @@ from .product_create import ProductCreate, ProductInputT_INPUT_MAP = List[Tuple[attribute_models.Attribute, AttrValuesInput]]-class ProductUpdate(ProductCreate):+class ProductUpdate(ProductCreate, ModelWithExtRefMutation):class Arguments:- id = graphene.ID(required=True, description="ID of a product to update.")+ id = graphene.ID(required=False, description="ID of a product to update.")+ external_reference = graphene.String(+ required=False,+ description=f"External ID of a product to update. {ADDED_IN_310}",+ )input = ProductInput(required=True, description="Fields required to update a product.")@@ -43,17 +48,26 @@ class ProductUpdate(ProductCreate):)return attributes- @classmethod- def save(cls, info, instance, cleaned_input):- with traced_atomic_transaction():- instance.save()- attributes = cleaned_input.get("attributes")- if attributes:- AttributeAssignmentMixin.save(instance, attributes)-@classmethoddef post_save_action(cls, info, instance, _cleaned_input):product = models.Product.objects.prefetched_for_webhook().get(pk=instance.pk)update_product_search_vector(instance)manager = get_plugin_manager_promise(info.context).get()cls.call_event(manager.product_updated, product)++ @classmethod+ def get_instance(cls, info, **data):+ """Prefetch related fields that are needed to process the mutation."""+ # If we are updating an instance and want to update its attributes,+ # prefetch them.+ object_id = cls.get_object_id(**data)+ if object_id and data.get("attributes"):+ # Prefetches needed by AttributeAssignmentMixin and+ # associate_attribute_values_to_instance+ qs = cls.Meta.model.objects.prefetch_related(+ "product_type__product_attributes__values",+ "product_type__attributeproduct",+ )+ return cls.get_node_or_error(info, object_id, only_type="Product", qs=qs)++ return super().get_instance(info, **data)diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_create.py b/saleor/graphql/product/mutations/product_variant/product_variant_create.pyindex d481d0968a..c5e978e1ba 100644--- a/saleor/graphql/product/mutations/product_variant/product_variant_create.py+++ b/saleor/graphql/product/mutations/product_variant/product_variant_create.py@@ -17,7 +17,12 @@ from .....product.utils.variants import generate_and_set_variant_namefrom ....attribute.types import AttributeValueInputfrom ....attribute.utils import AttributeAssignmentMixin, AttrValuesInputfrom ....channel import ChannelContext-from ....core.descriptions import ADDED_IN_31, ADDED_IN_38, PREVIEW_FEATURE+from ....core.descriptions import (+ ADDED_IN_31,+ ADDED_IN_38,+ ADDED_IN_310,+ PREVIEW_FEATURE,+)from ....core.mutations import ModelMutationfrom ....core.scalars import WeightScalarfrom ....core.types import NonNullList, ProductError@@ -85,6 +90,10 @@ class ProductVariantInput(graphene.InputObjectType):),required=False,)+ external_reference = graphene.String(+ description="External ID of this product variant." + ADDED_IN_310,+ required=False,+ )class ProductVariantCreateInput(ProductVariantInput):@@ -277,48 +286,6 @@ class ProductVariantCreate(ModelMutation):})- @classmethod- def get_instance(cls, info, **data):- """Prefetch related fields that are needed to process the mutation.-- If we are updating an instance and want to update its attributes,- # prefetch them.- """-- object_id = data.get("id")- object_sku = data.get("sku")- attributes = data.get("attributes")-- if attributes:- # Prefetches needed by AttributeAssignmentMixin and- # associate_attribute_values_to_instance- qs = cls.Meta.model.objects.prefetch_related(- "product__product_type__variant_attributes__values",- "product__product_type__attributevariant",- )- else:- # Use the default queryset.- qs = models.ProductVariant.objects.all()-- if object_id:- return cls.get_node_or_error(- info, object_id, only_type="ProductVariant", qs=qs- )- elif object_sku:- instance = qs.filter(sku=object_sku).first()- if not instance:- raise ValidationError(- {- "sku": ValidationError(- f"Couldn't resolve to a node: {object_sku}",- code="not_found",- )- }- )- return instance- else:- return cls._meta.model()-@classmethoddef save(cls, info, instance, cleaned_input):new_variant = instance.pk is Nonediff --git a/saleor/graphql/product/mutations/product_variant/product_variant_delete.py b/saleor/graphql/product/mutations/product_variant/product_variant_delete.pyindex 0b06a23d72..6e9dd4cbdc 100644--- a/saleor/graphql/product/mutations/product_variant/product_variant_delete.py+++ b/saleor/graphql/product/mutations/product_variant/product_variant_delete.py@@ -15,20 +15,25 @@ from .....product.search import update_product_search_vectorfrom .....product.tasks import update_product_discounted_price_taskfrom ....app.dataloaders import get_app_promisefrom ....channel import ChannelContext-from ....core.descriptions import ADDED_IN_38-from ....core.mutations import ModelDeleteMutation+from ....core.descriptions import ADDED_IN_38, ADDED_IN_310+from ....core.mutations import ModelDeleteMutation, ModelWithExtRefMutationfrom ....core.types import ProductError+from ....core.utils import ext_ref_to_global_id_or_errorfrom ....core.validators import validate_one_of_args_is_in_mutationfrom ....plugins.dataloaders import get_plugin_manager_promisefrom ...types import ProductVariantfrom ...utils import get_draft_order_lines_data_for_variants-class ProductVariantDelete(ModelDeleteMutation):+class ProductVariantDelete(ModelDeleteMutation, ModelWithExtRefMutation):class Arguments:id = graphene.ID(required=False, description="ID of a product variant to delete.")+ external_reference = graphene.String(+ required=False,+ description=f"External ID of a product variant to update. {ADDED_IN_310}",+ )sku = graphene.String(required=False,description="SKU of a product variant to delete." + ADDED_IN_38,@@ -57,10 +62,24 @@ class ProductVariantDelete(ModelDeleteMutation):@classmethoddef perform_mutation(cls, _root, info, **data):+ node_id = data.get("id")+ sku = data.get("sku")+ ext_ref = data.get("external_reference")+validate_one_of_args_is_in_mutation(- ProductErrorCode, "sku", data.get("sku"), "id", data.get("id")+ ProductErrorCode,+ "sku",+ sku,+ "id",+ node_id,+ "external_reference",+ ext_ref,)- if node_id := data.get("id"):++ if ext_ref:+ node_id = ext_ref_to_global_id_or_error(models.ProductVariant, ext_ref)++ if node_id:instance = cls.get_node_or_error(info, node_id, only_type=ProductVariant)if node_sku := data.get("sku"):diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_update.py b/saleor/graphql/product/mutations/product_variant/product_variant_update.pyindex 98230a8ec3..4c6148808b 100644--- a/saleor/graphql/product/mutations/product_variant/product_variant_update.py+++ b/saleor/graphql/product/mutations/product_variant/product_variant_update.py@@ -2,6 +2,7 @@ from collections import defaultdictfrom typing import List, Tupleimport graphene+from django.core.exceptions import ValidationErrorfrom django.utils.text import slugifyfrom .....attribute import AttributeInputType@@ -10,8 +11,10 @@ from .....core.permissions import ProductPermissionsfrom .....product import modelsfrom .....product.error_codes import ProductErrorCodefrom ....attribute.utils import AttributeAssignmentMixin, AttrValuesInput-from ....core.descriptions import ADDED_IN_38+from ....core.descriptions import ADDED_IN_38, ADDED_IN_310+from ....core.mutations import ModelWithExtRefMutationfrom ....core.types import ProductError+from ....core.utils import ext_ref_to_global_id_or_errorfrom ....core.validators import validate_one_of_args_is_in_mutationfrom ...types import ProductVariantfrom ...utils import get_used_attribute_values_for_variant@@ -20,10 +23,12 @@ from .product_variant_create import ProductVariantCreate, ProductVariantInputT_INPUT_MAP = List[Tuple[attribute_models.Attribute, AttrValuesInput]]-class ProductVariantUpdate(ProductVariantCreate):+class ProductVariantUpdate(ProductVariantCreate, ModelWithExtRefMutation):class Arguments:- id = graphene.ID(- required=False, description="ID of a product variant to update."+ id = graphene.ID(required=False, description="ID of a product to update.")+ external_reference = graphene.String(+ required=False,+ description=f"External ID of a product variant to update. {ADDED_IN_310}",)sku = graphene.String(required=False,@@ -80,9 +85,57 @@ class ProductVariantUpdate(ProductVariantCreate):attributes_data, used_attribute_values)+ @classmethod+ def get_instance(cls, info, **data):+ """Prefetch related fields that are needed to process the mutation.++ If we are updating an instance and want to update its attributes, prefetch them.+ """+ object_id = data.get("id")+ object_sku = data.get("sku")+ ext_ref = data.get("external_reference")+ attributes = data.get("attributes")++ if attributes:+ # Prefetches needed by AttributeAssignmentMixin and+ # associate_attribute_values_to_instance+ qs = cls.Meta.model.objects.prefetch_related(+ "product__product_type__variant_attributes__values",+ "product__product_type__attributevariant",+ )+ else:+ # Use the default queryset.+ qs = models.ProductVariant.objects.all()++ if ext_ref:+ object_id = ext_ref_to_global_id_or_error(models.ProductVariant, ext_ref)++ if object_id:+ return cls.get_node_or_error(+ info, object_id, only_type="ProductVariant", qs=qs+ )+ elif object_sku:+ instance = qs.filter(sku=object_sku).first()+ if not instance:+ raise ValidationError(+ {+ "sku": ValidationError(+ f"Couldn't resolve to a node: {object_sku}",+ code="not_found",+ )+ }+ )+ return instance+@classmethoddef perform_mutation(cls, _root, info, **data):validate_one_of_args_is_in_mutation(- ProductErrorCode, "sku", data.get("sku"), "id", data.get("id")+ ProductErrorCode,+ "sku",+ data.get("sku"),+ "id",+ data.get("id"),+ "external_reference",+ data.get("external_reference"),)return super().perform_mutation(_root, info, **data)diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.pyindex dccbef3268..1d338b6d5e 100644--- a/saleor/graphql/product/resolvers.py+++ b/saleor/graphql/product/resolvers.py@@ -60,24 +60,18 @@ def resolve_digital_contents(_info):return models.DigitalContent.objects.all()-def resolve_product_by_id(info, id, channel_slug, requestor):+def resolve_product(info, id, slug, external_reference, channel_slug, requestor):database_connection_name = get_database_connection_name(info.context)- return (- models.Product.objects.using(database_connection_name)- .visible_to_user(requestor, channel_slug=channel_slug)- .filter(id=id)- .first()- )---def resolve_product_by_slug(info, product_slug, channel_slug, requestor):- database_connection_name = get_database_connection_name(info.context)- return (- models.Product.objects.using(database_connection_name)- .visible_to_user(requestor, channel_slug=channel_slug)- .filter(slug=product_slug)- .first()+ qs = models.Product.objects.using(database_connection_name).visible_to_user(+ requestor, channel_slug=channel_slug)+ if id:+ _type, id = from_global_id_or_error(id, "Product")+ return qs.filter(id=id).first()+ elif slug:+ return qs.filter(slug=slug).first()+ else:+ return qs.filter(external_reference=external_reference).first()@traced_resolver@@ -100,19 +94,6 @@ def resolve_products(info, requestor, channel_slug=None) -> ChannelQsContext:return ChannelQsContext(qs=qs, channel_slug=channel_slug)-@traced_resolver-def resolve_variant_by_id(- _info, id, *, channel_slug, requestor, requestor_has_access_to_all-):- visible_products = models.Product.objects.visible_to_user(- requestor, channel_slug- ).values_list("pk", flat=True)- qs = models.ProductVariant.objects.filter(product__id__in=visible_products)- if not requestor_has_access_to_all:- qs = qs.available_in_channel(channel_slug)- return qs.filter(pk=id).first()--def resolve_product_type_by_id(id):return models.ProductType.objects.filter(pk=id).first()@@ -122,17 +103,29 @@ def resolve_product_types(_info):@traced_resolver-def resolve_product_variant_by_sku(- _info, sku, channel_slug, requestor, requestor_has_access_to_all+def resolve_variant(+ _info,+ id,+ sku,+ external_reference,+ *,+ channel_slug,+ requestor,+ requestor_has_access_to_all):- visible_products = models.Product.objects.visible_to_user(requestor, channel_slug)+ visible_products = models.Product.objects.visible_to_user(+ requestor, channel_slug+ ).values_list("pk", flat=True)qs = models.ProductVariant.objects.filter(product__id__in=visible_products)if not requestor_has_access_to_all:- visible_products = visible_products.annotate_visible_in_listings(- channel_slug- ).exclude(visible_in_listings=False)- qs = qs.filter(product__in=visible_products).available_in_channel(channel_slug)- return qs.filter(sku=sku).first()+ qs = qs.available_in_channel(channel_slug)+ if id:+ _, id = from_global_id_or_error(id, "ProductVariant")+ return qs.filter(pk=id).first()+ elif sku:+ return qs.filter(sku=sku).first()+ else:+ return qs.filter(external_reference=external_reference).first()@traced_resolverdiff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex 48e30af33b..ff73968b0b 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -9,6 +9,7 @@ from ...product.models import ALL_PRODUCTS_PERMISSIONSfrom ..channel import ChannelContextfrom ..channel.utils import get_default_channel_slug_or_graphql_errorfrom ..core.connection import create_connection_slice, filter_connection_queryset+from ..core.descriptions import ADDED_IN_310from ..core.enums import ReportingPeriodfrom ..core.fields import ConnectionField, FilterConnectionField, PermissionsFieldfrom ..core.types import NonNullList@@ -97,15 +98,13 @@ from .resolvers import (resolve_collections,resolve_digital_content_by_id,resolve_digital_contents,- resolve_product_by_id,- resolve_product_by_slug,+ resolve_product,resolve_product_type_by_id,resolve_product_types,- resolve_product_variant_by_sku,resolve_product_variants,resolve_products,resolve_report_product_sales,- resolve_variant_by_id,+ resolve_variant,)from .sorters import (CategorySortingInput,@@ -209,6 +208,9 @@ class ProductQueries(graphene.ObjectType):description="ID of the product.",),slug=graphene.Argument(graphene.String, description="Slug of the product."),+ external_reference=graphene.Argument(+ graphene.String, description=f"External ID of the product. {ADDED_IN_310}"+ ),channel=graphene.String(description="Slug of a channel for which the data should be returned."),@@ -255,6 +257,9 @@ class ProductQueries(graphene.ObjectType):sku=graphene.Argument(graphene.String, description="Sku of the product variant."),+ external_reference=graphene.Argument(+ graphene.String, description=f"External ID of the product. {ADDED_IN_310}"+ ),channel=graphene.String(description="Slug of a channel for which the data should be returned."),@@ -371,9 +376,17 @@ class ProductQueries(graphene.ObjectType):@staticmethod@traced_resolverdef resolve_product(- _root, info: graphene.ResolveInfo, *, id=None, slug=None, channel=None+ _root,+ info: graphene.ResolveInfo,+ *,+ id=None,+ slug=None,+ external_reference=None,+ channel=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(@@ -382,15 +395,16 @@ class ProductQueries(graphene.ObjectType):if channel is None and not has_required_permissions:channel = get_default_channel_slug_or_graphql_error()- if id:- _type, id = from_global_id_or_error(id, Product)- product = resolve_product_by_id(- info, id, channel_slug=channel, requestor=requestor- )- else:- product = resolve_product_by_slug(- info, product_slug=slug, channel_slug=channel, requestor=requestor- )++ product = resolve_product(+ info,+ id=id,+ slug=slug,+ external_reference=external_reference,+ channel_slug=channel,+ requestor=requestor,+ )+return ChannelContext(node=product, channel_slug=channel) if product else None@staticmethod@@ -440,9 +454,12 @@ class ProductQueries(graphene.ObjectType):*,id=None,sku=None,+ external_reference=None,channel=None,):- validate_one_of_args_is_in_query("id", id, "sku", sku)+ validate_one_of_args_is_in_query(+ "id", id, "sku", sku, "external_reference", external_reference+ )requestor = get_user_or_app_from_context(info.context)has_required_permissions = has_one_of_permissions(requestor, ALL_PRODUCTS_PERMISSIONS@@ -450,23 +467,17 @@ class ProductQueries(graphene.ObjectType):if channel is None and not has_required_permissions:channel = get_default_channel_slug_or_graphql_error()- if id:- _, id = from_global_id_or_error(id, ProductVariant)- variant = resolve_variant_by_id(- info,- id,- channel_slug=channel,- requestor=requestor,- requestor_has_access_to_all=has_required_permissions,- )- else:- variant = resolve_product_variant_by_sku(- info,- sku=sku,- channel_slug=channel,- requestor=requestor,- requestor_has_access_to_all=has_required_permissions,- )++ variant = resolve_variant(+ info,+ id,+ sku,+ external_reference,+ channel_slug=channel,+ requestor=requestor,+ requestor_has_access_to_all=has_required_permissions,+ )+return ChannelContext(node=variant, channel_slug=channel) if variant else None@staticmethoddiff --git a/saleor/graphql/product/tests/mutations/test_product_create.py b/saleor/graphql/product/tests/mutations/test_product_create.pyindex 59841213df..beaeed7f53 100644--- a/saleor/graphql/product/tests/mutations/test_product_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_create.py@@ -73,6 +73,7 @@ CREATE_PRODUCT_MUTATION = """}}}+ externalReference}errors {field@@ -111,6 +112,7 @@ def test_create_product(product_charge_taxes = Trueproduct_tax_rate = "STANDARD"tax_class_id = graphene.Node.to_global_id("TaxClass", tax_classes[0].pk)+ external_reference = "test-ext-ref"# Mock tax interface with fake response from tax gatewaymonkeypatch.setattr(@@ -147,6 +149,7 @@ def test_create_product(],"metadata": [{"key": metadata_key, "value": metadata_value}],"privateMetadata": [{"key": metadata_key, "value": metadata_value}],+ "externalReference": external_reference,}}@@ -167,6 +170,7 @@ def test_create_product(assert data["product"]["productType"]["name"] == product_type.nameassert data["product"]["category"]["name"] == category.nameassert data["product"]["taxClass"]["id"] == tax_class_id+ assert data["product"]["externalReference"] == external_referencevalues = (data["product"]["attributes"][0]["values"][0]["slug"],data["product"]["attributes"][1]["values"][0]["slug"],@@ -2404,3 +2408,41 @@ def test_create_product_with_weight_input(result_weight = content["data"]["productCreate"]["product"]["weight"]assert result_weight["value"] == expected_weight_valueassert result_weight["unit"] == site_settings.default_weight_unit.upper()+++def test_create_product_with_non_unique_external_reference(+ staff_api_client,+ product_type,+ category,+ product,+ permission_manage_products,+):+ # given+ query = CREATE_PRODUCT_MUTATION+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)+ category_id = graphene.Node.to_global_id("Category", category.pk)+ ext_ref = "test-ext-ref"+ product.external_reference = ext_ref+ product.save(update_fields=["external_reference"])++ variables = {+ "input": {+ "productType": product_type_id,+ "category": category_id,+ "externalReference": ext_ref,+ "name": "test prod",+ "slug": "test-prod",+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["productCreate"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == ProductErrorCode.UNIQUE.name+ assert error["message"] == "Product with this External reference already exists."diff --git a/saleor/graphql/product/tests/mutations/test_product_delete.py b/saleor/graphql/product/tests/mutations/test_product_delete.pyindex 2475c75efb..432fb0ad1f 100644--- a/saleor/graphql/product/tests/mutations/test_product_delete.py+++ b/saleor/graphql/product/tests/mutations/test_product_delete.py@@ -422,3 +422,90 @@ def test_product_delete_removes_reference_to_page(product.refresh_from_db()assert not data["errors"]+++DELETE_PRODUCT_BY_EXTERNAL_REFERENCE = """+ mutation DeleteProduct($id: ID, $externalReference: String) {+ productDelete(id: $id, externalReference: $externalReference) {+ product {+ id+ externalReference+ }+ errors {+ field+ message+ }+ }+ }+"""+++@patch("saleor.order.tasks.recalculate_orders_task.delay")+def test_delete_product_by_external_reference(+ mocked_recalculate_orders_task,+ staff_api_client,+ product,+ permission_manage_products,+):+ # given+ query = DELETE_PRODUCT_BY_EXTERNAL_REFERENCE+ product.external_reference = "test-ext-id"+ product.save(update_fields=["external_reference"])+ variables = {"externalReference": product.external_reference}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ data = content["data"]["productDelete"]++ # then+ with pytest.raises(product._meta.model.DoesNotExist):+ product.refresh_from_db()+ assert (+ graphene.Node.to_global_id(product._meta.model.__name__, product.id)+ == data["product"]["id"]+ )+ assert data["product"]["externalReference"] == product.external_reference+ mocked_recalculate_orders_task.assert_not_called()+++def test_delete_product_by_both_id_and_external_reference(+ staff_api_client, permission_manage_products+):+ # given+ query = DELETE_PRODUCT_BY_EXTERNAL_REFERENCE+ variables = {"externalReference": "whatever", "id": "whatever"}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["productDelete"]["errors"]+ assert (+ errors[0]["message"]+ == "Argument 'id' cannot be combined with 'external_reference'"+ )+++def test_delete_product_by_external_reference_not_existing(+ staff_api_client, permission_manage_products+):+ # given+ query = DELETE_PRODUCT_BY_EXTERNAL_REFERENCE+ ext_ref = "non-existing-ext-ref"+ variables = {"externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["productDelete"]["errors"]+ assert errors[0]["message"] == f"Couldn't resolve to a node: {ext_ref}"diff --git a/saleor/graphql/product/tests/mutations/test_product_update.py b/saleor/graphql/product/tests/mutations/test_product_update.pyindex 7c74560be0..5b8d37cb17 100644--- a/saleor/graphql/product/tests/mutations/test_product_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_update.py@@ -67,6 +67,7 @@ MUTATION_UPDATE_PRODUCT = """}}}+ externalReference}errors {message@@ -113,6 +114,7 @@ def test_update_product(metadata_key = "md key"metadata_value = "md value"+ external_reference = "test-ext-ref"# Mock tax interface with fake response from tax gatewaymonkeypatch.setattr(@@ -136,6 +138,7 @@ def test_update_product("attributes": [{"id": attribute_id, "values": [attr_value]}],"metadata": [{"key": metadata_key, "value": metadata_value}],"privateMetadata": [{"key": metadata_key, "value": metadata_value}],+ "externalReference": external_reference,},}@@ -157,6 +160,11 @@ def test_update_product(assert not data["product"]["category"]["name"] == category.nameassert product.metadata == {metadata_key: metadata_value, **old_meta}assert product.private_metadata == {metadata_key: metadata_value, **old_meta}+ assert (+ data["product"]["externalReference"]+ == external_reference+ == product.external_reference+ )attributes = data["product"]["attributes"]@@ -2738,3 +2746,153 @@ def test_update_product_with_multiselect_attribute_by_name_duplicated(assert not data["product"]assert len(errors) == 1assert errors[0]["message"] == AttributeInputErrors.ERROR_DUPLICATED_VALUES[0]+++MUTATION_UPDATE_PRODUCT_BY_EXTERNAL_REFERENCE = """+ mutation updateProduct($id: ID, $externalReference: String, $input: ProductInput!) {+ productUpdate(id: $id, externalReference: $externalReference, input: $input) {+ product {+ name+ id+ externalReference+ }+ errors {+ message+ field+ code+ }+ }+ }+"""+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+@patch("saleor.plugins.manager.PluginsManager.product_created")+def test_update_product_by_external_reference(+ created_webhook_mock,+ updated_webhook_mock,+ staff_api_client,+ product,+ permission_manage_products,+):+ # given+ new_name = "updated name"+ product.external_reference = "test-ext-id"+ product.save(update_fields=["external_reference"])++ variables = {+ "externalReference": product.external_reference,+ "input": {"name": new_name},+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_PRODUCT_BY_EXTERNAL_REFERENCE,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ product.refresh_from_db()++ # then+ assert data["errors"] == []+ assert data["product"]["name"] == new_name+ assert data["product"]["externalReference"] == product.external_reference+ assert data["product"]["id"] == graphene.Node.to_global_id(+ product._meta.model.__name__, product.id+ )++ updated_webhook_mock.assert_called_once_with(product)+ created_webhook_mock.assert_not_called()+++def test_update_product_by_both_id_and_external_reference(+ staff_api_client,+ product,+ permission_manage_products,+):+ # given+ new_name = "updated name"+ product.external_reference = "test-ext-id"+ product.save(update_fields=["external_reference"])++ variables = {+ "externalReference": product.external_reference,+ "id": product.id,+ "input": {"name": new_name},+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_PRODUCT_BY_EXTERNAL_REFERENCE,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]++ # then+ assert data["errors"]+ assert (+ data["errors"][0]["message"]+ == "Argument 'id' cannot be combined with 'external_reference'"+ )+++def test_update_product_external_reference_not_existing(+ staff_api_client,+ permission_manage_products,+):+ # given+ ext_ref = "non-existing-ext-ref"+ variables = {+ "externalReference": ext_ref,+ "input": {},+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_PRODUCT_BY_EXTERNAL_REFERENCE,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]++ # then+ assert data["errors"]+ assert data["errors"][0]["message"] == f"Couldn't resolve to a node: {ext_ref}"+++def test_update_product_with_non_unique_external_reference(+ staff_api_client,+ product_list,+ permission_manage_products,+):+ # given+ product_1 = product_list[0]+ product_2 = product_list[1]+ ext_ref = "test-ext-ref"+ product_1.external_reference = ext_ref+ product_1.save(update_fields=["external_reference"])+ product_2_id = graphene.Node.to_global_id("Product", product_2.id)++ variables = {+ "id": product_2_id,+ "input": {"externalReference": ext_ref},+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_PRODUCT_BY_EXTERNAL_REFERENCE,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["productUpdate"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == ProductErrorCode.UNIQUE.name+ assert error["message"] == "Product with this External reference already exists."diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_create.pyindex a527a62e81..bca9936320 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_create.py@@ -68,6 +68,7 @@ CREATE_VARIANT_MUTATION = """keyvalue}+ externalReference}}}@@ -104,6 +105,7 @@ def test_create_variant_with_name("quantity": 20,}]+ external_reference = "test-ext-ref"variables = {"input": {@@ -116,6 +118,7 @@ def test_create_variant_with_name("trackInventory": True,"metadata": [{"key": metadata_key, "value": metadata_value}],"privateMetadata": [{"key": metadata_key, "value": metadata_value}],+ "externalReference": external_reference,}}@@ -142,6 +145,7 @@ def test_create_variant_with_name(assert data["metadata"][0]["value"] == metadata_valueassert data["privateMetadata"][0]["key"] == metadata_keyassert data["privateMetadata"][0]["value"] == metadata_value+ assert data["externalReference"] == external_referencecreated_webhook_mock.assert_called_once_with(product.variants.last())updated_webhook_mock.assert_not_called()@@ -1837,3 +1841,46 @@ def test_variant_create_product_with_variant_attributes_variant_flag_false(errors = content["data"]["productVariantCreate"]["errors"]assert errorsassert errors[0]["code"] == ProductErrorCode.INVALID.name+++def test_create_product_variant_with_non_unique_external_reference(+ staff_api_client,+ category,+ product,+ product_type,+ permission_manage_products,+):+ # given+ query = CREATE_VARIANT_MUTATION+ product_id = graphene.Node.to_global_id("Product", product.pk)+ variant = product.variants.first()+ attribute_id = graphene.Node.to_global_id(+ "Attribute", product_type.variant_attributes.first().pk+ )++ ext_ref = "test-ext-ref"+ variant.external_reference = ext_ref+ variant.save(update_fields=["external_reference"])++ variables = {+ "input": {+ "product": product_id,+ "attributes": [{"id": attribute_id, "values": ["test-value"]}],+ "externalReference": ext_ref,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["productVariantCreate"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == ProductErrorCode.UNIQUE.name+ assert (+ error["message"]+ == "Product variant with this External reference already exists."+ )diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_delete.py b/saleor/graphql/product/tests/mutations/test_product_variant_delete.pyindex 71b0ea0fe3..949c44acc5 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_delete.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_delete.py@@ -445,3 +445,97 @@ def test_delete_variant_delete_product_channel_listing_not_deleted(mocked_recalculate_orders_task.assert_not_called()product.refresh_from_db()assert product.channel_listings.count() == product_channel_listing_count+++DELETE_VARIANT_BY_EXTERNAL_REFERENCE = """+ mutation variantDelete($id: ID, $externalReference: String) {+ productVariantDelete(id: $id, externalReference: $externalReference) {+ productVariant {+ externalReference+ id+ }+ errors {+ field+ message+ }+ }+ }+"""+++@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")+@patch("saleor.order.tasks.recalculate_orders_task.delay")+def test_delete_variant_by_external_reference(+ mocked_recalculate_orders_task,+ product_variant_deleted_webhook_mock,+ staff_api_client,+ product,+ permission_manage_products,+):+ # given+ query = DELETE_VARIANT_BY_EXTERNAL_REFERENCE+ ext_ref = "test-ext-ref"+ variant = product.variants.first()+ variant.external_reference = ext_ref+ variant.save(update_fields=["external_reference"])+ variables = {"externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantDelete"]++ # then+ product_variant_deleted_webhook_mock.assert_called_once_with(variant)+ assert data["productVariant"]["externalReference"] == ext_ref+ assert data["productVariant"]["id"] == graphene.Node.to_global_id(+ variant._meta.model.__name__, variant.id+ )+ with pytest.raises(variant._meta.model.DoesNotExist):+ variant.refresh_from_db()+ mocked_recalculate_orders_task.assert_not_called()+++def test_delete_product_by_both_id_and_external_reference(+ staff_api_client, permission_manage_products+):+ # given+ query = DELETE_VARIANT_BY_EXTERNAL_REFERENCE+ variables = {"externalReference": "whatever", "id": "whatever"}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["productVariantDelete"]["errors"]+ assert (+ errors[0]["message"]+ == "Argument 'id' cannot be combined with 'external_reference'"+ )+++def test_delete_product_by_external_reference_not_existing(+ staff_api_client, permission_manage_products+):+ # given+ query = DELETE_VARIANT_BY_EXTERNAL_REFERENCE+ ext_ref = "non-existing-ext-ref"+ variables = {"externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["productVariantDelete"]["errors"]+ assert errors[0]["message"] == f"Couldn't resolve to a node: {ext_ref}"diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_update.pyindex cbe53fda51..d8f8314f16 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_update.py@@ -103,10 +103,11 @@ def test_update_product_variant_by_id():query = """mutation updateVariant (- $id: ID!,- $sku: String!,+ $id: ID!+ $sku: String!$quantityLimitPerCustomer: Int!- $trackInventory: Boolean!,+ $trackInventory: Boolean!+ $externalReference: String$attributes: [AttributeValueInput!]) {productVariantUpdate(id: $id,@@ -114,12 +115,14 @@ def test_update_product_variant_by_id(sku: $sku,trackInventory: $trackInventory,attributes: $attributes,+ externalReference: $externalReferencequantityLimitPerCustomer: $quantityLimitPerCustomer,}) {productVariant {nameskuquantityLimitPerCustomer+ externalReferencechannelListings {channel {slug@@ -135,6 +138,7 @@ def test_update_product_variant_by_id(sku = "test sku"quantity_limit_per_customer = 5attr_value = "S"+ external_reference = "test-ext-ref"variables = {"id": variant_id,@@ -142,6 +146,7 @@ def test_update_product_variant_by_id("trackInventory": True,"quantityLimitPerCustomer": quantity_limit_per_customer,"attributes": [{"id": attribute_id, "values": [attr_value]}],+ "externalReference": external_reference,}response = staff_api_client.post_graphql(@@ -154,6 +159,7 @@ def test_update_product_variant_by_id(assert data["name"] == variant.nameassert data["sku"] == sku+ assert data["externalReference"] == external_reference == variant.external_referenceassert data["quantityLimitPerCustomer"] == quantity_limit_per_customerproduct_variant_updated_webhook_mock.assert_called_once_with(product.variants.last()@@ -277,6 +283,156 @@ def test_update_product_variant_by_sku_return_error_when_sku_dont_exists(assert data["errors"][0]["code"] == "NOT_FOUND"+UPDATE_VARIANT_BY_EXTERNAL_REFERENCE = """+ mutation updateVariant (+ $id: ID, $externalReference: String, $input: ProductVariantInput!+ ) {+ productVariantUpdate(+ id: $id,+ externalReference: $externalReference,+ input: $input+ ) {+ productVariant {+ id+ sku+ externalReference+ }+ errors {+ message+ field+ code+ }+ }+ }+ """+++@patch("saleor.plugins.manager.PluginsManager.product_variant_created")+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+def test_update_product_variant_by_external_reference(+ product_variant_updated_webhook_mock,+ product_variant_created_webhook_mock,+ staff_api_client,+ product,+ size_attribute,+ permission_manage_products,+):+ # given+ query = UPDATE_VARIANT_BY_EXTERNAL_REFERENCE++ ext_ref = "test-ext-ref"+ new_sku = "new-test-sku"+ variant = product.variants.first()+ variant.external_reference = ext_ref+ variant.save(update_fields=["external_reference"])++ variables = {+ "externalReference": ext_ref,+ "input": {"sku": new_sku},+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ variant.refresh_from_db()+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantUpdate"]++ # then+ assert not data["errors"]+ assert data["productVariant"]["sku"] == new_sku+ assert data["productVariant"]["externalReference"] == ext_ref+ assert data["productVariant"]["id"] == graphene.Node.to_global_id(+ variant._meta.model.__name__, variant.id+ )+ product_variant_updated_webhook_mock.assert_called_once_with(+ product.variants.last()+ )+ product_variant_created_webhook_mock.assert_not_called()+++def test_update_product_variant_by_both_id_and_external_reference(+ staff_api_client,+ product,+ permission_manage_products,+):+ # given+ query = UPDATE_VARIANT_BY_EXTERNAL_REFERENCE+ variables = {"externalReference": "whatever", "id": "whatever", "input": {}}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["productVariantUpdate"]["errors"]+ assert (+ errors[0]["message"]+ == "Argument 'id' cannot be combined with 'external_reference'"+ )+++def test_update_product_variant_by_external_reference_not_existing(+ staff_api_client,+ product,+ permission_manage_products,+):+ # given+ query = UPDATE_VARIANT_BY_EXTERNAL_REFERENCE+ ext_ref = "non-existing-ext-ref"+ variables = {"externalReference": ext_ref, "input": {}}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)++ # then+ errors = content["data"]["productVariantUpdate"]["errors"]+ assert errors[0]["message"] == f"Couldn't resolve to a node: {ext_ref}"+++def test_update_product_variant_with_non_unique_external_reference(+ staff_api_client,+ product_list,+ permission_manage_products,+):+ # given+ query = UPDATE_VARIANT_BY_EXTERNAL_REFERENCE+ ext_ref = "test-ext-ref"++ product_1 = product_list[0]+ variant_1 = product_1.variants.first()+ variant_1.external_reference = ext_ref+ variant_1.save(update_fields=["external_reference"])++ product_2 = product_list[1]+ variant_2 = product_2.variants.first()+ variant_2_id = graphene.Node.to_global_id("ProductVariant", variant_2.pk)++ variables = {"id": variant_2_id, "input": {"externalReference": ext_ref}}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["productVariantUpdate"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == ProductErrorCode.UNIQUE.name+ assert (+ error["message"]+ == "Product variant with this External reference already exists."+ )++def test_update_product_variant_with_negative_weight(staff_api_client, product, permission_manage_products):diff --git a/saleor/graphql/product/tests/queries/test_product_query.py b/saleor/graphql/product/tests/queries/test_product_query.pyindex 194a62c5a0..13122d8979 100644--- a/saleor/graphql/product/tests/queries/test_product_query.py+++ b/saleor/graphql/product/tests/queries/test_product_query.py@@ -2355,3 +2355,46 @@ def test_fetch_all_products_with_availability_data(}}assert data in product_data+++QUERY_PRODUCT_BY_EXTERNAL_REFERENCE = """+ query ($id: ID, $externalReference: String, $slug: String, $channel:String){+ product(+ id: $id,+ slug: $slug,+ externalReference: $externalReference,+ channel: $channel+ ) {+ id+ name+ externalReference+ }+ }+"""+++def test_product_query_by_external_reference(+ staff_api_client, permission_manage_products, product, channel_USD+):+ # given+ product.external_reference = "test-ext-id"+ product.save(update_fields=["external_reference"])+ variables = {+ "externalReference": product.external_reference,+ "channel": channel_USD.slug,+ }++ # when+ response = staff_api_client.post_graphql(+ QUERY_PRODUCT_BY_EXTERNAL_REFERENCE,+ variables=variables,+ permissions=(permission_manage_products,),+ check_no_permissions=False,+ )+ content = get_graphql_content(response)++ # then+ product_data = content["data"]["product"]+ assert product_data is not None+ assert product_data["name"] == product.name+ assert product_data["externalReference"] == product.external_referencediff --git a/saleor/graphql/product/tests/queries/test_variant_query.py b/saleor/graphql/product/tests/queries/test_variant_query.pyindex 1561c9f0e1..62d6d75e86 100644--- a/saleor/graphql/product/tests/queries/test_variant_query.py+++ b/saleor/graphql/product/tests/queries/test_variant_query.py@@ -15,11 +15,18 @@ from ...enums import VariantAttributeScopeVARIANT_QUERY = """query variant(- $id: ID, $sku: String, $variantSelection: VariantAttributeScope, $channel: String+ $id: ID,+ $sku: String,+ $externalReference: String,+ $variantSelection: VariantAttributeScope,+ $channel: String){- productVariant(id:$id, sku:$sku, channel: $channel){+ productVariant(+ id:$id, sku:$sku, externalReference: $externalReference, channel: $channel+ ){idsku+ externalReferenceattributes(variantSelection: $variantSelection) {attribute {slug@@ -34,7 +41,9 @@ query variant("""-def test_get_variant_without_id_and_sku(staff_api_client, permission_manage_products):+def test_get_variant_without_id_sku_and_external_reference(+ staff_api_client, permission_manage_products+):# given# when@@ -46,7 +55,8 @@ def test_get_variant_without_id_and_sku(staff_api_client, permission_manage_prod# thenassert_graphql_error_with_message(- response, "At least one of arguments is required: 'id', 'sku'."+ response,+ "At least one of arguments is required: 'id', 'sku', 'external_reference'.",)@@ -422,6 +432,29 @@ def test_get_variant_by_sku_as_staff(assert data["sku"] == variant.sku+def test_get_variant_by_external_reference(+ staff_api_client, permission_manage_products, variant+):+ # given+ ext_ref = "test-ext-ref"+ variant.external_reference = ext_ref+ variant.save(update_fields=["external_reference"])+ variables = {"externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ VARIANT_QUERY,+ variables,+ permissions=[permission_manage_products],+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productVariant"]+ assert data["externalReference"] == ext_ref++def test_get_variant_by_sku_as_app(app_api_client, permission_manage_products, variant):# givenvariables = {"sku": variant.sku}diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex b89b0973de..1895223b5f 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -55,6 +55,7 @@ from ...core.connection import (from ...core.descriptions import (ADDED_IN_31,ADDED_IN_39,+ ADDED_IN_310,DEPRECATED_IN_3X_FIELD,DEPRECATED_IN_3X_INPUT,PREVIEW_FEATURE,@@ -362,6 +363,10 @@ class ProductVariant(ChannelContextTypeWithMetadata, ModelObjectType):)created = graphene.DateTime(required=True)updated_at = graphene.DateTime(required=True)+ external_reference = graphene.String(+ description=f"External ID of this product. {ADDED_IN_310}",+ required=False,+ )class Meta:default_resolver = ChannelContextType.resolver_with_context@@ -950,6 +955,10 @@ class Product(ChannelContextTypeWithMetadata, ModelObjectType):required=False,permissions=[AuthorizationFilters.AUTHENTICATED_STAFF_USER],)+ external_reference = graphene.String(+ description=f"External ID of this product. {ADDED_IN_310}",+ required=False,+ )class Meta:default_resolver = ChannelContextType.resolver_with_contextdiff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex cc2d07ab55..6939fdef52 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -34,8 +34,15 @@ type Query {Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS, MANAGE_SHIPPING."""warehouse(- """ID of an warehouse"""- id: ID!+ """ID of a warehouse."""+ id: ID++ """+ External ID of a warehouse.++ Added in Saleor 3.10.+ """+ externalReference: String): Warehouse"""@@ -389,6 +396,13 @@ type Query {"""Slug of the product."""slug: String+ """+ External ID of the product.++ Added in Saleor 3.10.+ """+ externalReference: String+"""Slug of a channel for which the data should be returned."""channel: String): Product@@ -456,6 +470,13 @@ type Query {"""Sku of the product variant."""sku: String+ """+ External ID of the product.++ Added in Saleor 3.10.+ """+ externalReference: String+"""Slug of a channel for which the data should be returned."""channel: String): ProductVariant@@ -636,10 +657,17 @@ type Query {last: Int): OrderEventCountableConnection- """Look up an order by ID."""+ """Look up an order by ID or external reference."""order("""ID of an order."""- id: ID!+ id: ID++ """+ External ID of an order.++ Added in Saleor 3.10.+ """+ externalReference: String): Order"""@@ -1161,13 +1189,20 @@ type Query {last: Int): AttributeCountableConnection- """Look up an attribute by ID."""+ """Look up an attribute by ID, slug or external reference."""attribute("""ID of the attribute."""id: ID"""Slug of the attribute."""slug: String++ """+ External ID of the attribute.++ Added in Saleor 3.10.+ """+ externalReference: String): Attribute"""@@ -1372,6 +1407,13 @@ type Query {"""Email address of the user."""email: String++ """+ External ID of the user.++ Added in Saleor 3.10.+ """+ externalReference: String): User_entities(representations: [_Any]): [_Entity]_service: _Service@@ -3024,6 +3066,13 @@ type Warehouse implements Node & ObjectWithMetadata {"""Return the last n elements from the list."""last: Int): ShippingZoneCountableConnection!++ """+ External ID of this warehouse.++ Added in Saleor 3.10.+ """+ externalReference: String}"""Represents user address data."""@@ -4892,6 +4941,13 @@ type Product implements Node & ObjectWithMetadata {Requires one of the following permissions: AUTHENTICATED_STAFF_USER."""taxClass: TaxClass++ """+ External ID of this product.++ Added in Saleor 3.10.+ """+ externalReference: String}"""@@ -5276,6 +5332,13 @@ type Attribute implements Node & ObjectWithMetadata {"""Return the last n elements from the list."""last: Int): ProductTypeCountableConnection!++ """+ External ID of this attribute.++ Added in Saleor 3.10.+ """+ externalReference: String}"""An enumeration."""@@ -5407,6 +5470,13 @@ type AttributeValue implements Node {"""Represents the date/time value of the attribute value."""dateTime: DateTime++ """+ External ID of this attribute value.++ Added in Saleor 3.10.+ """+ externalReference: String}type AttributeValueTranslation implements Node {@@ -6158,6 +6228,13 @@ type ProductVariant implements Node & ObjectWithMetadata {preorder: PreorderDatacreated: DateTime!updatedAt: DateTime!++ """+ External ID of this product.++ Added in Saleor 3.10.+ """+ externalReference: String}"""Represents product varaint channel listing."""@@ -8524,6 +8601,13 @@ type User implements Node & ObjectWithMetadata {languageCode: LanguageCodeEnum!defaultShippingAddress: AddressdefaultBillingAddress: Address++ """+ External ID of this user.++ Added in Saleor 3.10.+ """+ externalReference: StringlastLogin: DateTimedateJoined: DateTime!updatedAt: DateTime!@@ -9440,6 +9524,13 @@ type Order implements Node & ObjectWithMetadata {Note: this API is currently in Feature Preview and can be subject to changes at later point."""displayGrossPrices: Boolean!++ """+ External ID of this order.++ Added in Saleor 3.10.+ """+ externalReference: String}"""An enumeration."""@@ -12431,8 +12522,15 @@ type Mutation {Requires one of the following permissions: MANAGE_PRODUCTS."""productDelete(+ """+ External ID of a product to delete.++ Added in Saleor 3.10.+ """+ externalReference: String+"""ID of a product to delete."""- id: ID!+ id: ID): ProductDelete"""@@ -12451,8 +12549,15 @@ type Mutation {Requires one of the following permissions: MANAGE_PRODUCTS."""productUpdate(+ """+ External ID of a product to update.++ Added in Saleor 3.10.+ """+ externalReference: String+"""ID of a product to update."""- id: ID!+ id: ID"""Fields required to update a product."""input: ProductInput!@@ -12691,6 +12796,13 @@ type Mutation {Requires one of the following permissions: MANAGE_PRODUCTS."""productVariantDelete(+ """+ External ID of a product variant to update.++ Added in Saleor 3.10.+ """+ externalReference: String+"""ID of a product variant to delete."""id: ID@@ -12783,7 +12895,14 @@ type Mutation {Requires one of the following permissions: MANAGE_PRODUCTS."""productVariantUpdate(- """ID of a product variant to update."""+ """+ External ID of a product variant to update.++ Added in Saleor 3.10.+ """+ externalReference: String++ """ID of a product to update."""id: ID"""Fields required to update a product variant."""@@ -13208,8 +13327,15 @@ type Mutation {Requires one of the following permissions: MANAGE_ORDERS."""draftOrderDelete(- """ID of a draft order to delete."""- id: ID!+ """+ External ID of a product to delete.++ Added in Saleor 3.10.+ """+ externalReference: String++ """ID of a product to delete."""+ id: ID): DraftOrderDelete"""@@ -13238,8 +13364,15 @@ type Mutation {Requires one of the following permissions: MANAGE_ORDERS."""draftOrderUpdate(+ """+ External ID of a draft order to update.++ Added in Saleor 3.10.+ """+ externalReference: String+"""ID of a draft order to update."""- id: ID!+ id: ID"""Fields required to update an order."""input: DraftOrderInput!@@ -13501,8 +13634,15 @@ type Mutation {Requires one of the following permissions: MANAGE_ORDERS."""orderUpdate(+ """+ External ID of an order to update.++ Added in Saleor 3.10.+ """+ externalReference: String+"""ID of an order to update."""- id: ID!+ id: ID"""Fields required to update an order."""input: OrderUpdateInput!@@ -14789,8 +14929,15 @@ type Mutation {Requires one of the following permissions: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES."""attributeDelete(+ """+ External ID of an attribute to delete.++ Added in Saleor 3.10.+ """+ externalReference: String+"""ID of an attribute to delete."""- id: ID!+ id: ID): AttributeDelete"""@@ -14799,8 +14946,15 @@ type Mutation {Requires one of the following permissions: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES."""attributeUpdate(+ """+ External ID of an attribute to update.++ Added in Saleor 3.10.+ """+ externalReference: String+"""ID of an attribute to update."""- id: ID!+ id: ID"""Fields required to update an attribute."""input: AttributeUpdateInput!@@ -14859,8 +15013,15 @@ type Mutation {Requires one of the following permissions: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES."""attributeValueDelete(+ """+ External ID of a value to delete.++ Added in Saleor 3.10.+ """+ externalReference: String+"""ID of a value to delete."""- id: ID!+ id: ID): AttributeValueDelete"""@@ -14869,8 +15030,15 @@ type Mutation {Requires one of the following permissions: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES."""attributeValueUpdate(+ """+ External ID of an AttributeValue to update.++ Added in Saleor 3.10.+ """+ externalReference: String+"""ID of an AttributeValue to update."""- id: ID!+ id: ID"""Fields required to update an AttributeValue."""input: AttributeValueUpdateInput!@@ -15357,8 +15525,15 @@ type Mutation {Requires one of the following permissions: MANAGE_USERS."""customerUpdate(+ """+ External ID of a customer to update.++ Added in Saleor 3.10.+ """+ externalReference: String+"""ID of a customer to update."""- id: ID!+ id: ID"""Fields required to update a customer."""input: CustomerInput!@@ -15370,8 +15545,15 @@ type Mutation {Requires one of the following permissions: MANAGE_USERS."""customerDelete(+ """+ External ID of a customer to update.++ Added in Saleor 3.10.+ """+ externalReference: String+"""ID of a customer to delete."""- id: ID!+ id: ID): CustomerDelete"""@@ -15688,6 +15870,13 @@ input WarehouseCreateInput {"""The email address of the warehouse."""email: String+ """+ External ID of the warehouse.++ Added in Saleor 3.10.+ """+ externalReference: String+"""Warehouse name."""name: String!@@ -15720,6 +15909,13 @@ input WarehouseUpdateInput {"""The email address of the warehouse."""email: String+ """+ External ID of the warehouse.++ Added in Saleor 3.10.+ """+ externalReference: String+"""Warehouse name."""name: String@@ -17395,6 +17591,13 @@ input ProductCreateInput {"""privateMetadata: [MetadataInput!]+ """+ External ID of this product.++ Added in Saleor 3.10.+ """+ externalReference: String+"""ID of the type that product belongs to."""productType: ID!}@@ -17567,6 +17770,13 @@ input ProductInput {Added in Saleor 3.8."""privateMetadata: [MetadataInput!]++ """+ External ID of this product.++ Added in Saleor 3.10.+ """+ externalReference: String}"""@@ -18068,6 +18278,13 @@ input ProductVariantCreateInput {"""privateMetadata: [MetadataInput!]+ """+ External ID of this product variant.++ Added in Saleor 3.10.+ """+ externalReference: String+"""Product ID of which type is the variant."""product: ID!@@ -18195,6 +18412,13 @@ input ProductVariantBulkCreateInput {"""privateMetadata: [MetadataInput!]+ """+ External ID of this product variant.++ Added in Saleor 3.10.+ """+ externalReference: String+"""Stocks of a product available for sale."""stocks: [StockInput!]@@ -18390,6 +18614,13 @@ input ProductVariantInput {Added in Saleor 3.8."""privateMetadata: [MetadataInput!]++ """+ External ID of this product variant.++ Added in Saleor 3.10.+ """+ externalReference: String}"""@@ -19160,6 +19391,13 @@ input DraftOrderCreateInput {"""redirectUrl: String+ """+ External ID of this order.++ Added in Saleor 3.10.+ """+ externalReference: String+"""Variant line input consisting of variant ID and quantity of products."""lines: [OrderLineCreateInput!]}@@ -19259,6 +19497,13 @@ input DraftOrderInput {URL of a view where users should be redirected to see the order details. URL in RFC 1808 format."""redirectUrl: String++ """+ External ID of this order.++ Added in Saleor 3.10.+ """+ externalReference: String}"""@@ -19705,6 +19950,13 @@ input OrderUpdateInput {"""Shipping address of the customer."""shippingAddress: AddressInput++ """+ External ID of this order.++ Added in Saleor 3.10.+ """+ externalReference: String}"""@@ -21834,6 +22086,13 @@ input AttributeCreateInput {"""Whether the attribute can be displayed in the admin product list."""availableInGrid: Boolean++ """+ External ID of this attribute.++ Added in Saleor 3.10.+ """+ externalReference: String}input AttributeValueCreateInput {@@ -21864,6 +22123,13 @@ input AttributeValueCreateInput {"""File content type."""contentType: String+ """+ External ID of this attribute value.++ Added in Saleor 3.10.+ """+ externalReference: String+"""Name of a value displayed in the interface."""name: String!}@@ -21928,6 +22194,13 @@ input AttributeUpdateInput {"""Whether the attribute can be displayed in the admin product list."""availableInGrid: Boolean++ """+ External ID of this product.++ Added in Saleor 3.10.+ """+ externalReference: String}input AttributeValueUpdateInput {@@ -21958,6 +22231,13 @@ input AttributeValueUpdateInput {"""File content type."""contentType: String+ """+ External ID of this attribute value.++ Added in Saleor 3.10.+ """+ externalReference: String+"""Name of a value displayed in the interface."""name: String}@@ -22805,6 +23085,13 @@ input UserCreateInput {"""User language code."""languageCode: LanguageCodeEnum+ """+ External ID of the customer.++ Added in Saleor 3.10.+ """+ externalReference: String+"""URL of a view where users should be redirected to set the password. URL in RFC 1808 format."""@@ -22851,6 +23138,13 @@ input CustomerInput {"""User language code."""languageCode: LanguageCodeEnum++ """+ External ID of the customer.++ Added in Saleor 3.10.+ """+ externalReference: String}"""diff --git a/saleor/graphql/warehouse/resolvers.py b/saleor/graphql/warehouse/resolvers.pyindex 6a967957cd..8e665c1f04 100644--- a/saleor/graphql/warehouse/resolvers.py+++ b/saleor/graphql/warehouse/resolvers.py@@ -9,9 +9,5 @@ def resolve_stocks():return models.Stock.objects.all()-def resolve_warehouse(id):- return models.Warehouse.objects.filter(id=id).first()--def resolve_warehouses():return models.Warehouse.objects.all()diff --git a/saleor/graphql/warehouse/schema.py b/saleor/graphql/warehouse/schema.pyindex 484a88c3c9..6db66b3faf 100644--- a/saleor/graphql/warehouse/schema.py+++ b/saleor/graphql/warehouse/schema.py@@ -5,9 +5,12 @@ from ...core.permissions import (ProductPermissions,ShippingPermissions,)+from ...warehouse import modelsfrom ..core.connection import create_connection_slice, filter_connection_queryset+from ..core.descriptions import ADDED_IN_310from ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.utils import from_global_id_or_error+from ..core.utils.resolvers import resolve_by_global_id_or_ext_reffrom .filters import StockFilterInput, WarehouseFilterInputfrom .mutations import (WarehouseCreate,@@ -16,12 +19,7 @@ from .mutations import (WarehouseShippingZoneUnassign,WarehouseUpdate,)-from .resolvers import (- resolve_stock,- resolve_stocks,- resolve_warehouse,- resolve_warehouses,-)+from .resolvers import resolve_stock, resolve_stocks, resolve_warehousesfrom .sorters import WarehouseSortingInputfrom .types import (Stock,@@ -35,8 +33,9 @@ class WarehouseQueries(graphene.ObjectType):warehouse = PermissionsField(Warehouse,description="Look up a warehouse by ID.",- id=graphene.Argument(- graphene.ID, description="ID of an warehouse", required=True+ id=graphene.Argument(graphene.ID, description="ID of a warehouse."),+ external_reference=graphene.Argument(+ graphene.String, description=f"External ID of a warehouse. {ADDED_IN_310}"),permissions=[ProductPermissions.MANAGE_PRODUCTS,@@ -57,10 +56,8 @@ class WarehouseQueries(graphene.ObjectType):)@staticmethod- def resolve_warehouse(_root, _info, **data):- warehouse_pk = data.get("id")- _, id = from_global_id_or_error(warehouse_pk, Warehouse)- return resolve_warehouse(id)+ def resolve_warehouse(_root, _info, id=None, external_reference=None):+ return resolve_by_global_id_or_ext_ref(models.Warehouse, id, external_reference)@staticmethoddef resolve_warehouses(_root, info, **kwargs):diff --git a/saleor/graphql/warehouse/tests/test_warehouse.py b/saleor/graphql/warehouse/tests/test_warehouse.pyindex 9c68446939..eb4146a1d5 100644--- a/saleor/graphql/warehouse/tests/test_warehouse.py+++ b/saleor/graphql/warehouse/tests/test_warehouse.py@@ -112,6 +112,16 @@ query warehouse($id: ID!){"""+QUERY_WAREHOUSE_BY_EXTERNAL_REFERENCE = """+query warehouse($id: ID, $externalReference: String){+ warehouse(id: $id, externalReference: $externalReference) {+ id+ externalReference+ }+}+"""++MUTATION_CREATE_WAREHOUSE = """mutation createWarehouse($input: WarehouseCreateInput!) {createWarehouse(input: $input){@@ -120,6 +130,7 @@ mutation createWarehouse($input: WarehouseCreateInput!) {nameslugcompanyName+ externalReferenceaddress {id}@@ -155,6 +166,7 @@ mutation updateWarehouse($input: WarehouseUpdateInput!, $id: ID!) {companyNameisPrivateclickAndCollectOption+ externalReferenceaddress {idstreetAddress1@@ -658,6 +670,7 @@ def test_mutation_create_warehouse("name": "Test warehouse","slug": "test-warhouse","email": "[email protected]",+ "externalReference": "test-ext-ref","address": {"streetAddress1": "Teczowa 8","city": "Wroclaw",@@ -683,6 +696,7 @@ def test_mutation_create_warehouse(assert created_warehouse["name"] == warehouse.nameassert created_warehouse["slug"] == warehouse.slugassert created_warehouse["companyName"] == warehouse.address.company_name+ assert created_warehouse["externalReference"] == warehouse.external_referencedef test_mutation_create_warehouse_shipping_zone_provided(@@ -881,15 +895,52 @@ def test_create_warehouse_with_given_slug(assert data["warehouse"]["slug"] == expected_slug+def test_create_warehouse_with_non_unique_external_reference(+ staff_api_client, permission_manage_products, shipping_zone, warehouse+):+ # given+ ext_ref = "test-ext-ref"+ warehouse.external_reference = ext_ref+ warehouse.save(update_fields=["external_reference"])++ variables = {+ "input": {+ "name": "Test warehouse",+ "externalReference": ext_ref,+ "address": {+ "streetAddress1": "Teczowa 8",+ "city": "Wroclaw",+ "country": "PL",+ "postalCode": "53-601",+ },+ }+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_CREATE_WAREHOUSE,+ variables=variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["createWarehouse"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == WarehouseErrorCode.UNIQUE.name+ assert error["message"] == "Warehouse with this External reference already exists."++def test_mutation_update_warehouse(staff_api_client, warehouse, permission_manage_products):warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)warehouse_old_name = warehouse.namewarehouse_slug = warehouse.slug+ external_reference = "test-ext-ref"variables = {"id": warehouse_id,- "input": {"name": "New name"},+ "input": {"name": "New name", "externalReference": external_reference},}staff_api_client.post_graphql(MUTATION_UPDATE_WAREHOUSE,@@ -900,6 +951,36 @@ def test_mutation_update_warehouse(assert not (warehouse.name == warehouse_old_name)assert warehouse.name == "New name"assert warehouse.slug == warehouse_slug+ assert warehouse.external_reference == external_reference+++def test_mutation_update_warehouse_with_non_unique_external_reference(+ staff_api_client, warehouse, permission_manage_products, warehouse_JPY+):+ # given+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)+ ext_ref = "test-ext-ref"+ warehouse_JPY.external_reference = ext_ref+ warehouse_JPY.save(update_fields=["external_reference"])++ variables = {+ "id": warehouse_id,+ "input": {"externalReference": ext_ref},+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_WAREHOUSE,+ variables=variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)++ # then+ error = content["data"]["updateWarehouse"]["errors"][0]+ assert error["field"] == "externalReference"+ assert error["code"] == WarehouseErrorCode.UNIQUE.name+ assert error["message"] == "Warehouse with this External reference already exists."@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")@@ -1488,3 +1569,26 @@ def test_shipping_zone_unassign_from_warehouse(warehouse.refresh_from_db()shipping_zone.refresh_from_db()assert not warehouse.shipping_zones.all()+++def test_warehouse_query_by_external_reference(+ staff_api_client, warehouse, permission_manage_products+):+ # given+ ext_ref = "test-ext-ref"+ warehouse.external_reference = ext_ref+ warehouse.save(update_fields=["external_reference"])+ variables = {"externalReference": ext_ref}++ # when+ response = staff_api_client.post_graphql(+ QUERY_WAREHOUSE_BY_EXTERNAL_REFERENCE,+ variables=variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["warehouse"]+ assert data["externalReference"] == ext_ref+ assert data["id"] == graphene.Node.to_global_id("Warehouse", warehouse.id)diff --git a/saleor/graphql/warehouse/types.py b/saleor/graphql/warehouse/types.pyindex 041cd1c58a..686b66ecfa 100644--- a/saleor/graphql/warehouse/types.py+++ b/saleor/graphql/warehouse/types.py@@ -11,6 +11,7 @@ from ..channel import ChannelContextfrom ..core.connection import CountableConnection, create_connection_slicefrom ..core.descriptions import (ADDED_IN_31,+ ADDED_IN_310,DEPRECATED_IN_3X_FIELD,DEPRECATED_IN_3X_INPUT,PREVIEW_FEATURE,@@ -27,6 +28,9 @@ from .enums import WarehouseClickAndCollectOptionEnumclass WarehouseInput(graphene.InputObjectType):slug = graphene.String(description="Warehouse slug.")email = graphene.String(description="The email address of the warehouse.")+ external_reference = graphene.String(+ description="External ID of the warehouse." + ADDED_IN_310, required=False+ )class WarehouseCreateInput(WarehouseInput):@@ -91,6 +95,9 @@ class Warehouse(ModelObjectType):"saleor.graphql.shipping.types.ShippingZoneCountableConnection",required=True,)+ external_reference = graphene.String(+ description=f"External ID of this warehouse. {ADDED_IN_310}", required=False+ )class Meta:description = "Represents warehouse."diff --git a/saleor/order/migrations/0160_order_external_reference.py b/saleor/order/migrations/0160_order_external_reference.pynew file mode 100644index 0000000000..ef2c2fff6b--- /dev/null+++ b/saleor/order/migrations/0160_order_external_reference.py@@ -0,0 +1,20 @@+# Generated by Django 3.2.16 on 2022-12-02 17:29++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("order", "0159_order_shipping_tax_class_and_more"),+ ]++ operations = [+ migrations.AddField(+ model_name="order",+ name="external_reference",+ field=models.CharField(+ blank=True, db_index=True, max_length=250, null=True, unique=True+ ),+ ),+ ]diff --git a/saleor/order/models.py b/saleor/order/models.pyindex aa2086ca05..770e0dc895 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -19,7 +19,7 @@ from measurement.measures import Weightfrom ..app.models import Appfrom ..channel.models import Channel-from ..core.models import ModelWithMetadata+from ..core.models import ModelWithExternalReference, ModelWithMetadatafrom ..core.permissions import OrderPermissionsfrom ..core.units import WeightUnitsfrom ..core.utils.json_serializer import CustomJsonEncoder@@ -97,7 +97,7 @@ def get_order_number():return result[0]-class Order(ModelWithMetadata):+class Order(ModelWithMetadata, ModelWithExternalReference):id = models.UUIDField(primary_key=True, editable=False, unique=True, default=uuid4)number = models.IntegerField(unique=True, default=get_order_number, editable=False)use_old_id = models.BooleanField(default=False)diff --git a/saleor/product/migrations/0178_product_external_reference.py b/saleor/product/migrations/0178_product_external_reference.pynew file mode 100644index 0000000000..6e0162595a--- /dev/null+++ b/saleor/product/migrations/0178_product_external_reference.py@@ -0,0 +1,20 @@+# Generated by Django 3.2.16 on 2022-11-29 17:49++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("product", "0177_product_tax_class_producttype_tax_class"),+ ]++ operations = [+ migrations.AddField(+ model_name="product",+ name="external_reference",+ field=models.CharField(+ blank=True, db_index=True, max_length=250, null=True, unique=True+ ),+ ),+ ]diff --git a/saleor/product/migrations/0179_productvariant_external_reference.py b/saleor/product/migrations/0179_productvariant_external_reference.pynew file mode 100644index 0000000000..e1e7c381b6--- /dev/null+++ b/saleor/product/migrations/0179_productvariant_external_reference.py@@ -0,0 +1,20 @@+# Generated by Django 3.2.16 on 2022-12-02 12:26++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("product", "0178_product_external_reference"),+ ]++ operations = [+ migrations.AddField(+ model_name="productvariant",+ name="external_reference",+ field=models.CharField(+ blank=True, db_index=True, max_length=250, null=True, unique=True+ ),+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex ea0d26a3d9..c7ccc0b3f2 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -40,7 +40,12 @@ from prices import Moneyfrom ..channel.models import Channelfrom ..core.db.fields import SanitizedJSONField-from ..core.models import ModelWithMetadata, PublishableModel, SortableModel+from ..core.models import (+ ModelWithExternalReference,+ ModelWithMetadata,+ PublishableModel,+ SortableModel,+)from ..core.permissions import (DiscountPermissions,OrderPermissions,@@ -390,7 +395,7 @@ class ProductsQueryset(models.QuerySet):return self.prefetch_related("collections", "category", *common_fields)-class Product(SeoModel, ModelWithMetadata):+class Product(SeoModel, ModelWithMetadata, ModelWithExternalReference):product_type = models.ForeignKey(ProductType, related_name="products", on_delete=models.CASCADE)@@ -585,7 +590,7 @@ class ProductChannelListing(PublishableModel):)-class ProductVariant(SortableModel, ModelWithMetadata):+class ProductVariant(SortableModel, ModelWithMetadata, ModelWithExternalReference):sku = models.CharField(max_length=255, unique=True, null=True, blank=True)name = models.CharField(max_length=255, blank=True)product = models.ForeignKey(diff --git a/saleor/warehouse/migrations/0033_warehouse_external_reference.py b/saleor/warehouse/migrations/0033_warehouse_external_reference.pynew file mode 100644index 0000000000..5de3a26a3b--- /dev/null+++ b/saleor/warehouse/migrations/0033_warehouse_external_reference.py@@ -0,0 +1,20 @@+# Generated by Django 3.2.16 on 2022-12-06 12:33++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("warehouse", "0032_alter_channel_warehouse"),+ ]++ operations = [+ migrations.AddField(+ model_name="warehouse",+ name="external_reference",+ field=models.CharField(+ blank=True, db_index=True, max_length=250, null=True, unique=True+ ),+ ),+ ]diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex b6979b687f..9e7834bfbb 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -12,7 +12,7 @@ from django.utils import timezonefrom ..account.models import Addressfrom ..channel.models import Channelfrom ..checkout.models import CheckoutLine-from ..core.models import ModelWithMetadata, SortableModel+from ..core.models import ModelWithExternalReference, ModelWithMetadata, SortableModelfrom ..order.models import OrderLinefrom ..product.models import Product, ProductVariant, ProductVariantChannelListingfrom ..shipping.models import ShippingZone@@ -165,7 +165,7 @@ class ChannelWarehouse(SortableModel):return self.channel.channelwarehouse.all()-class Warehouse(ModelWithMetadata):+class Warehouse(ModelWithMetadata, ModelWithExternalReference):id = models.UUIDField(default=uuid.uuid4, primary_key=True)name = models.CharField(max_length=250)slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)