Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Assigning attributes to customer entities (#19633)
Marcin Wcisłodfdae075aa34
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0f1655bd6a..d3739fd3d7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -26,16 +26,16 @@ All notable, unreleased changes to this project will be documented in this file.- Removed the deprecated `orderAddNote` mutation, along with the `OrderAddNote` type and `OrderAddNoteInput` input. Use the `orderNoteAdd` mutation instead.- Removed the `DIGITAL_LINKS` value from the `OrderEventsEmailsEnum` enum and the `DIGITAL_LINK_DOWNLOADED` value from the `CustomerEventsEnum` enum. Events with these types were deleted in 3.23, along with the legacy digital content feature that emitted them.- Removed the always-empty `digital_lines` key from the fulfillment confirmation notification payload. Use `physical_lines`, which holds every line of the fulfillment.-- Attribute value and bulk attribute mutations now require the permission matching the attribute's type: `MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES` for `PRODUCT_TYPE` attributes and `MANAGE_PAGE_TYPES_AND_ATTRIBUTES` for `PAGE_TYPE` attributes. Previously each mutation required a single fixed permission regardless of the attribute's type, which let a requestor modify attributes of a type they were not authorized for - #19595 by @wcislo-saleor+- Attribute value and bulk attribute mutations now require the permission matching the attribute's type: `MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES` for `PRODUCT_TYPE` attributes, `MANAGE_PAGE_TYPES_AND_ATTRIBUTES` for `PAGE_TYPE` attributes, and `MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES` for `CUSTOMER_TYPE` attributes. Previously each mutation required a single fixed permission regardless of the attribute's type, which let a requestor modify attributes of a type they were not authorized for.The affected mutations and their previously required permission:- `attributeValueCreate` — previously `MANAGE_PRODUCTS`; `PRODUCT_TYPE` attributes now require `MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES` and `PAGE_TYPE` attributes now require `MANAGE_PAGE_TYPES_AND_ATTRIBUTES`- `attributeValueUpdate`, `attributeValueDelete`, `attributeReorderValues` — previously `MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES`; unchanged for `PRODUCT_TYPE` attributes, but `PAGE_TYPE` attributes now require `MANAGE_PAGE_TYPES_AND_ATTRIBUTES`.- - `attributeBulkDelete`, `attributeValueBulkDelete` — previously `MANAGE_PAGE_TYPES_AND_ATTRIBUTES`; unchanged for `PAGE_TYPE` attributes, but `PRODUCT_TYPE` attributes now require `MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES`. When the call targets both types, both permissions are required.+ - `attributeBulkDelete`, `attributeValueBulkDelete` — previously `MANAGE_PAGE_TYPES_AND_ATTRIBUTES`; unchanged for `PAGE_TYPE` attributes, but `PRODUCT_TYPE` attributes now require `MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES`. When the call targets several types, every matching permission is required.- `attributeBulkCreate` and `attributeBulkUpdate` already resolved the permission from the attribute type. They now reject an attribute type that has no permission mapped, instead of falling back to `MANAGE_PAGE_TYPES_AND_ATTRIBUTES`.To upgrade, grant staff members and apps the permission matching the attribute types they operate on. A requestor holding only `MANAGE_PRODUCTS` can no longer create attribute values.-- Providing an empty `attributes` list (`null` or `[]`) in `where` filters for pages, products, and product variants now matches no objects instead of being ignored.+- Providing an empty `attributes` list (`null` or `[]`) in `where` filters for pages, products, and product variants now matches no objects instead of being ignored. The same now applies to a no-op attribute filter that builds no condition, such as an empty reference container (`reference: { pageSlugs: {} }`) - previously such a filter matched all product variants.### GraphQL APIdiff --git a/saleor/account/error_codes.py b/saleor/account/error_codes.pyindex 1f356f1312..b41d6c3ddd 100644--- a/saleor/account/error_codes.py+++ b/saleor/account/error_codes.py@@ -53,6 +53,49 @@ class CustomerBulkUpdateErrorCode(Enum):MAX_LENGTH = "max_length"+class CustomerTypeCreateErrorCode(Enum):+ GRAPHQL_ERROR = "graphql_error"+ INVALID = "invalid"+ NOT_FOUND = "not_found"+ REQUIRED = "required"+ UNIQUE = "unique"+++class CustomerTypeUpdateErrorCode(Enum):+ CANNOT_UNSET_DEFAULT = "cannot_unset_default"+ GRAPHQL_ERROR = "graphql_error"+ INVALID = "invalid"+ NOT_FOUND = "not_found"+ REQUIRED = "required"+ UNIQUE = "unique"+++class CustomerTypeDeleteErrorCode(Enum):+ CANNOT_DELETE_DEFAULT = "cannot_delete_default"+ GRAPHQL_ERROR = "graphql_error"+ INVALID = "invalid"+ NOT_FOUND = "not_found"+++class CustomerTypeAssignAttributesErrorCode(Enum):+ ATTRIBUTE_ALREADY_ASSIGNED = "attribute_already_assigned"+ GRAPHQL_ERROR = "graphql_error"+ INVALID = "invalid"+ NOT_FOUND = "not_found"+++class CustomerTypeUnassignAttributesErrorCode(Enum):+ GRAPHQL_ERROR = "graphql_error"+ INVALID = "invalid"+ NOT_FOUND = "not_found"+++class CustomerTypeReorderAttributesErrorCode(Enum):+ GRAPHQL_ERROR = "graphql_error"+ INVALID = "invalid"+ NOT_FOUND = "not_found"++class PermissionGroupErrorCode(Enum):REQUIRED = "required"UNIQUE = "unique"diff --git a/saleor/account/exceptions.py b/saleor/account/exceptions.pynew file mode 100644index 0000000000..f514cd57de--- /dev/null+++ b/saleor/account/exceptions.py@@ -0,0 +1,5 @@+class NoDefaultCustomerType(Exception):+ def __init__(self, msg=None):+ if msg is None:+ msg = "The default customer type does not exist."+ super().__init__(msg)diff --git a/saleor/account/lock_objects.py b/saleor/account/lock_objects.pyindex 329d631c68..84ea95be51 100644--- a/saleor/account/lock_objects.py+++ b/saleor/account/lock_objects.py@@ -1,5 +1,9 @@-from .models import User+from .models import CustomerType, Userdef user_qs_select_for_update():return User.objects.order_by("pk").select_for_update(of=("self",))+++def customer_type_qs_select_for_update():+ return CustomerType.objects.order_by("pk").select_for_update(of=("self",))diff --git a/saleor/account/migrations/0100_customertype.py b/saleor/account/migrations/0100_customertype.pynew file mode 100644index 0000000000..6f7b81d5a8--- /dev/null+++ b/saleor/account/migrations/0100_customertype.py@@ -0,0 +1,78 @@+# Generated by Django 5.2.15 on 2026-07-21 07:09++import django.contrib.postgres.indexes+from django.db import migrations, models++import saleor.core.utils.json_serializer+++class Migration(migrations.Migration):+ dependencies = [+ ("account", "0099_remove_digitalcontent_customerevent_type"),+ ]++ operations = [+ migrations.CreateModel(+ name="CustomerType",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ (+ "private_metadata",+ models.JSONField(+ blank=True,+ db_default={},+ default=dict,+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,+ ),+ ),+ (+ "metadata",+ models.JSONField(+ blank=True,+ db_default={},+ default=dict,+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,+ ),+ ),+ ("name", models.CharField(max_length=250)),+ (+ "slug",+ models.SlugField(allow_unicode=True, max_length=255, unique=True),+ ),+ ("is_default", models.BooleanField(default=False)),+ ],+ options={+ "ordering": ("slug",),+ "permissions": (+ (+ "manage_customer_types_and_attributes",+ "Manage customer types and attributes.",+ ),+ ),+ "abstract": False,+ "indexes": [+ django.contrib.postgres.indexes.GinIndex(+ fields=["private_metadata"], name="customertype_p_meta_idx"+ ),+ django.contrib.postgres.indexes.GinIndex(+ fields=["metadata"], name="customertype_meta_idx"+ ),+ ],+ "constraints": [+ models.UniqueConstraint(+ condition=models.Q(("is_default", True)),+ fields=("is_default",),+ name="unique_default_customer_type",+ )+ ],+ },+ ),+ ]diff --git a/saleor/account/migrations/0101_user_customer_type.py b/saleor/account/migrations/0101_user_customer_type.pynew file mode 100644index 0000000000..43154c2f29--- /dev/null+++ b/saleor/account/migrations/0101_user_customer_type.py@@ -0,0 +1,25 @@+# Generated by Django 5.2.15 on 2026-07-21 07:10++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("account", "0100_customertype"),+ ]++ operations = [+ migrations.AddField(+ model_name="user",+ name="customer_type",+ field=models.ForeignKey(+ blank=True,+ db_index=False,+ null=True,+ on_delete=django.db.models.deletion.PROTECT,+ related_name="users",+ to="account.customertype",+ ),+ ),+ ]diff --git a/saleor/account/migrations/0102_user_user_customer_type_idx.py b/saleor/account/migrations/0102_user_user_customer_type_idx.pynew file mode 100644index 0000000000..09831ad8e7--- /dev/null+++ b/saleor/account/migrations/0102_user_user_customer_type_idx.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.15 on 2026-07-21 07:11++import django.contrib.postgres.indexes+from django.contrib.postgres.operations import AddIndexConcurrently+from django.db import migrations+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("account", "0101_user_customer_type"),+ ]++ operations = [+ AddIndexConcurrently(+ model_name="user",+ index=django.contrib.postgres.indexes.BTreeIndex(+ fields=["customer_type"], name="user_customer_type_idx"+ ),+ ),+ ]diff --git a/saleor/account/migrations/0103_create_default_customer_type.py b/saleor/account/migrations/0103_create_default_customer_type.pynew file mode 100644index 0000000000..9c4419e031--- /dev/null+++ b/saleor/account/migrations/0103_create_default_customer_type.py@@ -0,0 +1,18 @@+from django.db import migrations+++def create_default_customer_type(apps, _schema_editor):+ CustomerType = apps.get_model("account", "CustomerType")+ CustomerType.objects.get_or_create(+ is_default=True,+ defaults={"name": "Default", "slug": "default"},+ )+++class Migration(migrations.Migration):+ dependencies = [+ ("account", "0102_user_user_customer_type_idx"),+ ]+ operations = [+ migrations.RunPython(create_default_customer_type, migrations.RunPython.noop)+ ]diff --git a/saleor/account/migrations/0104_assign_default_customer_type_to_users.py b/saleor/account/migrations/0104_assign_default_customer_type_to_users.pynew file mode 100644index 0000000000..49d139b094--- /dev/null+++ b/saleor/account/migrations/0104_assign_default_customer_type_to_users.py@@ -0,0 +1,24 @@+from django.apps import apps as registry+from django.db import migrations+from django.db.models.signals import post_migrate++from .tasks.saleor3_23 import assign_default_customer_type_to_users_task+++def assign_default_customer_type_to_users(apps, _schema_editor):+ def on_migrations_complete(sender=None, **kwargs):+ assign_default_customer_type_to_users_task.delay()++ sender = registry.get_app_config("account")+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)+++class Migration(migrations.Migration):+ dependencies = [+ ("account", "0103_create_default_customer_type"),+ ]+ operations = [+ migrations.RunPython(+ assign_default_customer_type_to_users, migrations.RunPython.noop+ ),+ ]diff --git a/saleor/account/migrations/0105_add_manage_customer_types_and_attributes_perm.py b/saleor/account/migrations/0105_add_manage_customer_types_and_attributes_perm.pynew file mode 100644index 0000000000..ed38da29fb--- /dev/null+++ b/saleor/account/migrations/0105_add_manage_customer_types_and_attributes_perm.py@@ -0,0 +1,48 @@+from django.apps import apps as registry+from django.db import migrations+from django.db.models.signals import post_migrate+++def update_groups_with_manage_users_with_new_permission(apps, schema_editor):+ def on_migrations_complete(sender=None, **kwargs):+ try:+ apps = kwargs["apps"]+ except KeyError:+ # In test when we use use `@pytest.mark.django_db(transaction=True)`+ # pytest trigger additional post_migrate signal without `apps` in kwargs.+ return+ Group = apps.get_model("account", "Group")+ Permission = apps.get_model("permission", "Permission")+ ContentType = apps.get_model("contenttypes", "ContentType")++ ct, _ = ContentType.objects.get_or_create(+ app_label="account", model="customertype"+ )+ manage_customer_types_and_attributes_perm, _ = Permission.objects.get_or_create(+ codename="manage_customer_types_and_attributes",+ content_type=ct,+ name="Manage customer types and attributes.",+ )++ groups = Group.objects.filter(+ permissions__content_type__app_label="account",+ permissions__codename="manage_users",+ )+ for group in groups.iterator():+ group.permissions.add(manage_customer_types_and_attributes_perm)++ sender = registry.get_app_config("account")+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)+++class Migration(migrations.Migration):+ dependencies = [+ ("account", "0104_assign_default_customer_type_to_users"),+ ]++ operations = [+ migrations.RunPython(+ update_groups_with_manage_users_with_new_permission,+ migrations.RunPython.noop,+ ),+ ]diff --git a/saleor/account/migrations/0106_merge_20260807_0748.py b/saleor/account/migrations/0106_merge_20260807_0748.pynew file mode 100644index 0000000000..97be56a767--- /dev/null+++ b/saleor/account/migrations/0106_merge_20260807_0748.py@@ -0,0 +1,12 @@+# Generated by Django 5.2.15 on 2026-08-07 07:48++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("account", "0100_remove_digital_link_from_customerevent_type"),+ ("account", "0105_add_manage_customer_types_and_attributes_perm"),+ ]++ operations = []diff --git a/saleor/account/migrations/tasks/saleor3_23.py b/saleor/account/migrations/tasks/saleor3_23.pyindex 1fa316ade7..1a8bbcc910 100644--- a/saleor/account/migrations/tasks/saleor3_23.py+++ b/saleor/account/migrations/tasks/saleor3_23.py@@ -1,9 +1,12 @@from celery.utils.log import get_task_loggerfrom django.conf import settings+from django.db import transactionfrom ....celeryconf import appfrom ....core.db.connection import allow_writer-from ...models import CustomerEvent+from ...lock_objects import user_qs_select_for_update+from ...models import CustomerEvent, User+from ...utils import get_default_customer_type# Kills the task if it recurses more than 10000 times (=> 10M rows),# something is likely wrong if it does. Assuming 1 task = 1sec, it would@@ -57,3 +60,31 @@ def delete_digital_customer_events(delete_digital_customer_events.delay(current_depth=current_depth + 1, max_depth=max_depth)+++ASSIGN_DEFAULT_CUSTOMER_TYPE_BATCH_SIZE = 100++[email protected](queue=settings.DATA_MIGRATIONS_TASKS_QUEUE_NAME)+@allow_writer()+def assign_default_customer_type_to_users_task():+ """Assign the default customer type to users that don't have any type yet."""++ default_customer_type = get_default_customer_type()++ with transaction.atomic():+ batch_pks = list(+ user_qs_select_for_update()+ .filter(customer_type__isnull=True)+ .values_list("pk", flat=True)[:ASSIGN_DEFAULT_CUSTOMER_TYPE_BATCH_SIZE]+ )+ if batch_pks:+ User.objects.filter(pk__in=batch_pks).update(+ customer_type=default_customer_type+ )++ if batch_pks:+ task_logger.info(+ "Assigned the default customer type to %d users", len(batch_pks)+ )+ assign_default_customer_type_to_users_task.delay()diff --git a/saleor/account/models.py b/saleor/account/models.pyindex 4aa440ac83..79da5bdde0 100644--- a/saleor/account/models.py+++ b/saleor/account/models.py@@ -19,7 +19,12 @@ from ..app.models import Appfrom ..core.models import ModelWithExternalReference, ModelWithMetadatafrom ..core.utils.json_serializer import CustomJsonEncoderfrom ..order.models import Order-from ..permission.enums import AccountPermissions, BasePermissionEnum, get_permissions+from ..permission.enums import (+ AccountPermissions,+ BasePermissionEnum,+ CustomerTypePermissions,+ get_permissions,+)from ..permission.models import Permission, PermissionsMixin, _user_has_permfrom ..site.models import SiteSettingsfrom . import CustomerEvents@@ -136,6 +141,31 @@ class UserManager(BaseUserManager["User"]):return self.get_queryset().filter(is_staff=True)+class CustomerType(ModelWithMetadata):+ name = models.CharField(max_length=250)+ slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)+ is_default = models.BooleanField(default=False)++ class Meta(ModelWithMetadata.Meta):+ ordering = ("slug",)+ permissions = (+ (+ CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.codename,+ "Manage customer types and attributes.",+ ),+ )+ constraints = [+ models.UniqueConstraint(+ fields=["is_default"],+ condition=Q(is_default=True),+ name="unique_default_customer_type",+ ),+ ]++ def __str__(self) -> str:+ return self.name++class User(PermissionsMixin, ModelWithMetadata, AbstractBaseUser, ModelWithExternalReference):@@ -171,6 +201,19 @@ class User(search_document = models.TextField(blank=True, default="")uuid = models.UUIDField(default=uuid4, unique=True)+ # Already existing users may have their customer type empty until a migration+ # backfills it. Field readers are supposed to rely on default customer type when+ # null is encountered.+ # New users have their customer type set.+ customer_type = models.ForeignKey(+ CustomerType,+ related_name="users",+ null=True,+ blank=True,+ on_delete=models.PROTECT,+ db_index=False,+ )+# Denormalized number of orders placed by the usernumber_of_orders = models.PositiveIntegerField(default=0, db_default=0)@@ -225,6 +268,10 @@ class User(fields=["date_joined"],name="user_date_joined_idx",),+ BTreeIndex(+ fields=["customer_type"],+ name="user_customer_type_idx",+ ),BTreeIndex(fields=["email"],name="user_email_idx",diff --git a/saleor/account/search.py b/saleor/account/search.pyindex 744ee4d7db..041cffe752 100644--- a/saleor/account/search.py+++ b/saleor/account/search.py@@ -41,6 +41,10 @@ def generate_user_search_vector_value(attach_addresses_data: bool = True,already_prefetched: bool = False,) -> list[NoValidationSearchVector]:+ # Customer attribute values are deliberately not indexed here - customers+ # can be filtered with `where: {attributes: ...}`, but the free-text+ # `search` does not match attribute values. Indexing them would require+ # marking users as search-dirty on every attribute value write.search_vectors = [NoValidationSearchVector(Value(user.first_name),diff --git a/saleor/account/tests/fixtures/__init__.py b/saleor/account/tests/fixtures/__init__.pyindex 0892831594..4b31ac7473 100644--- a/saleor/account/tests/fixtures/__init__.py+++ b/saleor/account/tests/fixtures/__init__.py@@ -1 +1,2 @@+from .customer_type import * # noqa: F403from .user import * # noqa: F403diff --git a/saleor/account/tests/fixtures/customer_type.py b/saleor/account/tests/fixtures/customer_type.pynew file mode 100644index 0000000000..26114ed155--- /dev/null+++ b/saleor/account/tests/fixtures/customer_type.py@@ -0,0 +1,46 @@+import pytest++from ...models import CustomerType++__all__ = [+ "customer_type",+ "customer_type_with_attributes",+ "default_customer_type",+ "get_or_create_default_customer_type",+]+++def get_or_create_default_customer_type() -> CustomerType:+ # Transactional tests (django_db(transaction=True)) flush all tables on+ # teardown, wiping the default customer type created by the data migration,+ # so recreate it on demand instead of assuming the migration row exists.+ customer_type, _ = CustomerType.objects.get_or_create(+ is_default=True,+ defaults={"name": "Default", "slug": "default"},+ )+ return customer_type+++def customer_type(db):+ return CustomerType.objects.create(name="B2B", slug="b2b")+++def customer_type_with_attributes(+ customer_type,+ loyalty_customer_attribute,+ description_customer_attribute,+ hidden_customer_attribute,+):+ customer_type.customer_attributes.add(+ loyalty_customer_attribute,+ description_customer_attribute,+ hidden_customer_attribute,+ )+ return customer_type++[email protected](autouse=True)+def default_customer_type(db):+ return get_or_create_default_customer_type()diff --git a/saleor/account/tests/fixtures/user.py b/saleor/account/tests/fixtures/user.pyindex 9ccf7bba69..b9def73ff5 100644--- a/saleor/account/tests/fixtures/user.py+++ b/saleor/account/tests/fixtures/user.py@@ -4,6 +4,7 @@ import pytestfrom ....account.models import Group, User, UserManagerfrom ....permission.enums import get_permissions+from .customer_type import get_or_create_default_customer_typedef dangerously_get_or_create_superuser(@@ -38,6 +39,9 @@ def dangerously_create_test_user(# Google OAuth2 backend send unnecessary username fieldextra_fields.pop("username", None)+ if "customer_type" not in extra_fields and "customer_type_id" not in extra_fields:+ extra_fields["customer_type"] = get_or_create_default_customer_type()+user = User(email=email, is_active=is_active, is_staff=is_staff, **extra_fields)if password:# Semgrep rule that verifies whether the user's password is validated beforediff --git a/saleor/account/tests/test_customer_type.py b/saleor/account/tests/test_customer_type.pynew file mode 100644index 0000000000..d0988f862e--- /dev/null+++ b/saleor/account/tests/test_customer_type.py@@ -0,0 +1,142 @@+import pytest+from django.db import IntegrityError+from django.db.models.deletion import ProtectedError++from ..exceptions import NoDefaultCustomerType+from ..migrations.tasks.saleor3_23 import assign_default_customer_type_to_users_task+from ..models import CustomerType, User+from ..utils import get_default_customer_type+++def test_default_customer_type_is_seeded():+ # given the data migration ran++ # when+ default_type = CustomerType.objects.get(is_default=True)++ # then+ assert default_type.name == "Default"+ assert default_type.slug == "default"+++def test_get_default_customer_type_returns_default_type(+ customer_type, default_customer_type+):+ # given a non-default type existing alongside the default one++ # when+ result = get_default_customer_type()++ # then+ assert result == default_customer_type+ assert result != customer_type+++def test_get_default_customer_type_raises_when_default_is_missing():+ # given+ CustomerType.objects.all().delete()++ # when / then+ with pytest.raises(NoDefaultCustomerType):+ get_default_customer_type()+++def test_second_default_customer_type_is_rejected(default_customer_type):+ # given+ assert CustomerType.objects.filter(is_default=True).exists() is True++ # when / then+ with pytest.raises(IntegrityError, match="unique_default_customer_type"):+ CustomerType.objects.create(name="Other", slug="other", is_default=True)+++def test_multiple_non_default_customer_types_are_allowed():+ # when+ CustomerType.objects.create(name="B2B", slug="b2b")+ CustomerType.objects.create(name="B2C", slug="b2c")++ # then+ assert CustomerType.objects.filter(is_default=False).count() == 2+++def test_deleting_customer_type_assigned_to_user_is_protected(+ customer_user, customer_type+):+ # given+ customer_user.customer_type = customer_type+ customer_user.save(update_fields=["customer_type"])++ # when / then+ with pytest.raises(ProtectedError, match="User.customer_type"):+ customer_type.delete()+++def test_assign_default_customer_type_task_backfills_users_without_type(+ customer_user, customer_user2, default_customer_type+):+ # given+ User.objects.filter(pk__in=[customer_user.pk, customer_user2.pk]).update(+ customer_type=None+ )++ # when+ assign_default_customer_type_to_users_task()++ # then+ customer_user.refresh_from_db()+ customer_user2.refresh_from_db()+ assert customer_user.customer_type == default_customer_type+ assert customer_user2.customer_type == default_customer_type+++def test_assign_default_customer_type_task_keeps_existing_assignments(+ customer_user, customer_user2, customer_type, default_customer_type+):+ # given+ customer_user.customer_type = customer_type+ customer_user.save(update_fields=["customer_type"])+ customer_user2.customer_type = None+ customer_user2.save(update_fields=["customer_type"])++ # when+ assign_default_customer_type_to_users_task()++ # then+ customer_user.refresh_from_db()+ customer_user2.refresh_from_db()+ assert customer_user.customer_type == customer_type+ assert customer_user2.customer_type == default_customer_type+++def test_assign_default_customer_type_task_processes_all_batches(+ customer_user, customer_user2, staff_user, default_customer_type, monkeypatch+):+ # given a batch size smaller than the number of users to backfill+ monkeypatch.setattr(+ "saleor.account.migrations.tasks.saleor3_23"+ ".ASSIGN_DEFAULT_CUSTOMER_TYPE_BATCH_SIZE",+ 1,+ )++ # when the task self-chains (celery runs eagerly in tests)+ assign_default_customer_type_to_users_task()++ # then+ assert User.objects.filter(customer_type__isnull=True).count() == 0+ customer_user.refresh_from_db()+ staff_user.refresh_from_db()+ assert customer_user.customer_type == default_customer_type+ assert staff_user.customer_type == default_customer_type+++def test_assign_default_customer_type_task_raises_when_default_is_missing():+ # given+ CustomerType.objects.all().delete()++ # when / then+ with pytest.raises(NoDefaultCustomerType):+ assign_default_customer_type_to_users_task()diff --git a/saleor/account/utils.py b/saleor/account/utils.pyindex 2f4a8abef4..010a4b5240 100644--- a/saleor/account/utils.py+++ b/saleor/account/utils.py@@ -10,8 +10,9 @@ from ..core.tracing import traced_atomic_transactionfrom ..core.utils.events import call_eventfrom ..permission.models import Permissionfrom ..plugins.manager import get_plugins_manager+from .exceptions import NoDefaultCustomerTypefrom .lock_objects import user_qs_select_for_update-from .models import Group, User+from .models import CustomerType, Group, Userif TYPE_CHECKING:from ..plugins.manager import PluginsManager@@ -55,6 +56,23 @@ class RequestorAwareContext:}+def get_default_customer_type(+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+) -> CustomerType:+ """Return the default customer type.++ :raises NoDefaultCustomerType: When the default customer type is missing.+ """+ customer_type = (+ CustomerType.objects.using(database_connection_name)+ .filter(is_default=True)+ .first()+ )+ if customer_type is None:+ raise NoDefaultCustomerType()+ return customer_type++def store_user_address(user: User,address: "Address",diff --git a/saleor/attribute/__init__.py b/saleor/attribute/__init__.pyindex 811630bfc2..f2ec0fdfc1 100644--- a/saleor/attribute/__init__.py+++ b/saleor/attribute/__init__.py@@ -42,6 +42,7 @@ class AttributeInputType:TYPES_WITH_UNIQUE_VALUES = [FILE,REFERENCE,+ SINGLE_REFERENCE,RICH_TEXT,PLAIN_TEXT,NUMERIC,@@ -97,8 +98,13 @@ ATTRIBUTE_PROPERTIES_CONFIGURATION = {class AttributeType:PRODUCT_TYPE = "product-type"PAGE_TYPE = "page-type"+ CUSTOMER_TYPE = "customer-type"- CHOICES = [(PRODUCT_TYPE, "Product type"), (PAGE_TYPE, "Page type")]+ CHOICES = [+ (PRODUCT_TYPE, "Product type"),+ (PAGE_TYPE, "Page type"),+ (CUSTOMER_TYPE, "Customer type"),+ ]class AttributeEntityType:diff --git a/saleor/attribute/migrations/0056_attributecustomertype_attribute_customer_types.py b/saleor/attribute/migrations/0056_attributecustomertype_attribute_customer_types.pynew file mode 100644index 0000000000..1b1813cfe4--- /dev/null+++ b/saleor/attribute/migrations/0056_attributecustomertype_attribute_customer_types.py@@ -0,0 +1,63 @@+# Generated by Django 5.2.15 on 2026-07-21 07:10++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("account", "0101_user_customer_type"),+ ("attribute", "0055_assignedvariantattributevalue_variant"),+ ]++ operations = [+ migrations.CreateModel(+ name="AttributeCustomerType",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ (+ "sort_order",+ models.IntegerField(db_index=True, editable=False, null=True),+ ),+ (+ "attribute",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="attributecustomertype",+ to="attribute.attribute",+ ),+ ),+ (+ "customer_type",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="attributecustomertype",+ to="account.customertype",+ ),+ ),+ ],+ options={+ "ordering": ("sort_order", "pk"),+ "unique_together": {("attribute", "customer_type")},+ },+ ),+ migrations.AddField(+ model_name="attribute",+ name="customer_types",+ field=models.ManyToManyField(+ blank=True,+ related_name="customer_attributes",+ through="attribute.AttributeCustomerType",+ through_fields=("attribute", "customer_type"),+ to="account.customertype",+ ),+ ),+ ]diff --git a/saleor/attribute/migrations/0057_assigneduserattributevalue.py b/saleor/attribute/migrations/0057_assigneduserattributevalue.pynew file mode 100644index 0000000000..94deaf1c91--- /dev/null+++ b/saleor/attribute/migrations/0057_assigneduserattributevalue.py@@ -0,0 +1,59 @@+# Generated by Django 5.2.15 on 2026-07-21 07:10++import django.contrib.postgres.indexes+import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("account", "0101_user_customer_type"),+ ("attribute", "0056_attributecustomertype_attribute_customer_types"),+ ]++ operations = [+ migrations.CreateModel(+ name="AssignedUserAttributeValue",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ (+ "sort_order",+ models.IntegerField(db_index=True, editable=False, null=True),+ ),+ (+ "user",+ models.ForeignKey(+ db_index=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="attributevalues",+ to="account.user",+ ),+ ),+ (+ "value",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="uservalueassignment",+ to="attribute.attributevalue",+ ),+ ),+ ],+ options={+ "ordering": ("sort_order", "pk"),+ "indexes": [+ django.contrib.postgres.indexes.BTreeIndex(+ fields=["user"], name="assigneduserattrvalue_user_idx"+ )+ ],+ "unique_together": {("value", "user")},+ },+ ),+ ]diff --git a/saleor/attribute/migrations/0058_alter_attribute_type.py b/saleor/attribute/migrations/0058_alter_attribute_type.pynew file mode 100644index 0000000000..9780a3b9be--- /dev/null+++ b/saleor/attribute/migrations/0058_alter_attribute_type.py@@ -0,0 +1,24 @@+# Generated by Django 5.2.15 on 2026-07-22 08:27++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("attribute", "0057_assigneduserattributevalue"),+ ]++ operations = [+ migrations.AlterField(+ model_name="attribute",+ name="type",+ field=models.CharField(+ choices=[+ ("product-type", "Product type"),+ ("page-type", "Page type"),+ ("customer-type", "Customer type"),+ ],+ max_length=50,+ ),+ ),+ ]diff --git a/saleor/attribute/models/__init__.py b/saleor/attribute/models/__init__.pyindex 950b88a1c2..f223179bd6 100644--- a/saleor/attribute/models/__init__.py+++ b/saleor/attribute/models/__init__.py@@ -4,6 +4,7 @@ from .base import (AttributeValue,AttributeValueTranslation,)+from .customer import AssignedUserAttributeValue, AttributeCustomerTypefrom .page import AssignedPageAttributeValue, AttributePagefrom .product import AssignedProductAttributeValue, AttributeProductfrom .product_variant import (@@ -19,6 +20,8 @@ __all__ = ["AttributeValueTranslation","AssignedPageAttributeValue","AttributePage",+ "AssignedUserAttributeValue",+ "AttributeCustomerType","AssignedProductAttributeValue","AttributeProduct","AssignedVariantAttribute",diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.pyindex 766061155c..dd8354e74d 100644--- a/saleor/attribute/models/base.py+++ b/saleor/attribute/models/base.py@@ -4,13 +4,18 @@ from django.contrib.postgres.indexes import BTreeIndex, GinIndexfrom django.db import models, transactionfrom django.db.models import Case, Exists, F, OrderBy, OuterRef, Q, Value, When+from ...account.models import CustomerTypefrom ...core.db.fields import SanitizedJSONFieldfrom ...core.editorjs import clean_editorjsfrom ...core.models import ModelWithExternalReference, ModelWithMetadata, SortableModelfrom ...core.units import MeasurementUnitsfrom ...core.utils.translations import Translationfrom ...page.models import Page, PageType-from ...permission.enums import PageTypePermissions, ProductTypePermissions+from ...permission.enums import (+ CustomerTypePermissions,+ PageTypePermissions,+ ProductTypePermissions,+)from ...permission.utils import has_one_of_permissionsfrom ...product.models import Category, Collection, Product, ProductType, ProductVariantfrom .. import AttributeEntityType, AttributeInputType, AttributeType@@ -44,6 +49,7 @@ class BaseAttributeQuerySet(models.QuerySet[T]):[PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,+ CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES,],):return self.all()@@ -82,6 +88,16 @@ class AttributeQuerySet(BaseAttributeQuerySet[T]):Q(attributepage__page_type_id=product_type_pk))+ def get_unassigned_customer_type_attributes(self, customer_type_pk: int):+ return self.customer_type_attributes().exclude(+ attributecustomertype__customer_type_id=customer_type_pk+ )++ def get_assigned_customer_type_attributes(self, customer_type_pk: int):+ return self.customer_type_attributes().filter(+ attributecustomertype__customer_type_id=customer_type_pk+ )+def get_public_attributes(self):return self.filter(visible_in_storefront=True)@@ -109,6 +125,9 @@ class AttributeQuerySet(BaseAttributeQuerySet[T]):def page_type_attributes(self):return self.filter(type=AttributeType.PAGE_TYPE)+ def customer_type_attributes(self):+ return self.filter(type=AttributeType.CUSTOMER_TYPE)+AttributeManager = models.Manager.from_queryset(AttributeQuerySet)@@ -164,6 +183,13 @@ class Attribute(ModelWithMetadata, ModelWithExternalReference):through="attribute.AttributePage",through_fields=("attribute", "page_type"),)+ customer_types = models.ManyToManyField(+ CustomerType,+ blank=True,+ related_name="customer_attributes",+ through="attribute.AttributeCustomerType",+ through_fields=("attribute", "customer_type"),+ )unit = models.CharField(max_length=100,diff --git a/saleor/attribute/models/customer.py b/saleor/attribute/models/customer.pynew file mode 100644index 0000000000..a746d440a1--- /dev/null+++ b/saleor/attribute/models/customer.py@@ -0,0 +1,48 @@+from django.contrib.postgres.indexes import BTreeIndex+from django.db import models++from ...account.models import CustomerType, User+from ...core.models import SortableModel+from .base import AssociatedAttributeManager+++class AssignedUserAttributeValue(SortableModel):+ value = models.ForeignKey(+ "AttributeValue",+ on_delete=models.CASCADE,+ related_name="uservalueassignment",+ )+ user = models.ForeignKey(+ User,+ related_name="attributevalues",+ on_delete=models.CASCADE,+ null=False,+ blank=False,+ db_index=False,+ )++ class Meta:+ unique_together = (("value", "user"),)+ ordering = ("sort_order", "pk")+ indexes = [BTreeIndex(fields=["user"], name="assigneduserattrvalue_user_idx")]++ def get_ordering_queryset(self):+ return self.user.attributevalues.all()+++class AttributeCustomerType(SortableModel):+ attribute = models.ForeignKey(+ "Attribute", related_name="attributecustomertype", on_delete=models.CASCADE+ )+ customer_type = models.ForeignKey(+ CustomerType, related_name="attributecustomertype", on_delete=models.CASCADE+ )++ objects = AssociatedAttributeManager()++ class Meta:+ unique_together = (("attribute", "customer_type"),)+ ordering = ("sort_order", "pk")++ def get_ordering_queryset(self):+ return self.customer_type.attributecustomertype.all()diff --git a/saleor/attribute/tests/fixtures/attribute.py b/saleor/attribute/tests/fixtures/attribute.pyindex 0733765f91..e1862e869f 100644--- a/saleor/attribute/tests/fixtures/attribute.py+++ b/saleor/attribute/tests/fixtures/attribute.py@@ -893,3 +893,88 @@ def page_type_attribute_list() -> list[Attribute]:]))+++def customer_type_attribute_list() -> list[Attribute]:+ return list(+ Attribute.objects.bulk_create(+ [+ Attribute(slug="tier", name="Tier", type=AttributeType.CUSTOMER_TYPE),+ Attribute(+ slug="customer-segment",+ name="Segment",+ type=AttributeType.CUSTOMER_TYPE,+ ),+ Attribute(+ slug="region", name="Region", type=AttributeType.CUSTOMER_TYPE+ ),+ ]+ )+ )+++def loyalty_customer_attribute(db):+ attribute = Attribute.objects.create(+ slug="loyalty-level",+ name="Loyalty level",+ type=AttributeType.CUSTOMER_TYPE,+ )+ AttributeValue.objects.create(attribute=attribute, name="Gold", slug="gold")+ AttributeValue.objects.create(attribute=attribute, name="Silver", slug="silver")+ return attribute+++def segment_customer_attribute(db):+ attribute = Attribute.objects.create(+ slug="segment", name="Segment", type=AttributeType.CUSTOMER_TYPE+ )+ AttributeValue.objects.create(attribute=attribute, name="Retail", slug="retail")+ return attribute+++def description_customer_attribute(db):+ return Attribute.objects.create(+ slug="description",+ name="Description",+ type=AttributeType.CUSTOMER_TYPE,+ input_type=AttributeInputType.PLAIN_TEXT,+ )+++def hidden_customer_attribute(db):+ return Attribute.objects.create(+ slug="internal-score",+ name="Internal score",+ type=AttributeType.CUSTOMER_TYPE,+ visible_in_storefront=False,+ )+++def customer_type_page_single_reference_attribute(db):+ return Attribute.objects.create(+ slug="customer-single-page-reference",+ name="Single page reference",+ type=AttributeType.CUSTOMER_TYPE,+ input_type=AttributeInputType.SINGLE_REFERENCE,+ entity_type=AttributeEntityType.PAGE,+ )+++def interests_customer_attribute(db):+ attribute = Attribute.objects.create(+ slug="interests",+ name="Interests",+ type=AttributeType.CUSTOMER_TYPE,+ input_type=AttributeInputType.MULTISELECT,+ )+ AttributeValue.objects.create(attribute=attribute, name="Sports", slug="sports")+ AttributeValue.objects.create(attribute=attribute, name="Music", slug="music")+ AttributeValue.objects.create(attribute=attribute, name="Travel", slug="travel")+ return attributediff --git a/saleor/attribute/utils.py b/saleor/attribute/utils.pyindex 2d8795f957..a71f3586f5 100644--- a/saleor/attribute/utils.py+++ b/saleor/attribute/utils.py@@ -1,19 +1,53 @@from collections import defaultdict+from collections.abc import Iterable+from django.db import transactionfrom django.db.models import Exists, OuterRef, Q+from ..account.models import Userfrom ..page.models import Pagefrom ..product.models import Product, ProductVariant+from . import AttributeInputType+from .lock_objects import attribute_value_qs_select_for_updatefrom .models import (AssignedPageAttributeValue,AssignedProductAttributeValue,+ AssignedUserAttributeValue,AssignedVariantAttribute,AssignedVariantAttributeValue,+ Attribute,AttributeValue,AttributeVariant,)-T_INSTANCE = Product | ProductVariant | Page+T_INSTANCE = Product | ProductVariant | Page | User+++def delete_user_unique_attribute_values(user_pks: Iterable[int]) -> None:+ """Delete attribute values of unique-value input types assigned to the users.++ Values of selectable input types (dropdown, multiselect, swatch) are the+ attribute's shared choices, so on user deletion only their assignments go+ away (handled by the FK cascade). Values of input types listed in+ `TYPES_WITH_UNIQUE_VALUES` are created per user and may contain PII, so+ they must be deleted together with the user. Must be called before the+ user rows are deleted - the cascade removes the assignments needed to+ find the values.+ """+ assigned_values = AssignedUserAttributeValue.objects.filter(user_id__in=user_pks)+ unique_value_attributes = Attribute.objects.filter(+ input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES+ )+ with transaction.atomic():+ locked_ids = (+ attribute_value_qs_select_for_update()+ .filter(+ Exists(assigned_values.filter(value_id=OuterRef("id"))),+ Exists(unique_value_attributes.filter(id=OuterRef("attribute_id"))),+ )+ .values_list("id", flat=True)+ )+ AttributeValue.objects.filter(id__in=locked_ids).delete()instance_to_function_variables_mapping = {@@ -26,6 +60,7 @@ instance_to_function_variables_mapping = {"variant",),"Page": (AssignedPageAttributeValue, "page"),+ "User": (AssignedUserAttributeValue, "user"),}diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex c90180634a..5f4db33e02 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -29,7 +29,7 @@ from ...account.search import (update_user_search_vector,)from ...account.tests.fixtures.user import dangerously_create_test_user-from ...account.utils import store_user_address+from ...account.utils import get_default_customer_type, store_user_addressfrom ...app.models import Appfrom ...attribute.models import (AssignedProductAttributeValue,@@ -527,7 +527,7 @@ def create_address(save=True, **kwargs):return address-def create_fake_user(user_password, save=True, generate_id=False):+def create_fake_user(user_password, save=True, generate_id=False, customer_type=None):address = create_address(save=save)email = get_email(address.first_name, address.last_name)@@ -559,6 +559,7 @@ def create_fake_user(user_password, save=True, generate_id=False):)if save:+ user.customer_type = customer_type or get_default_customer_type()password_validation.validate_password(user_password, user)user.set_password(user_password)user.save()@@ -1115,8 +1116,9 @@ def create_fake_order_promotion():def create_users(user_password, how_many=10):+ default_customer_type = get_default_customer_type()for _ in range(how_many):- user = create_fake_user(user_password)+ user = create_fake_user(user_password, customer_type=default_customer_type)yield f"User: {user.email}"@@ -1142,6 +1144,7 @@ def create_permission_groups(staff_password):def create_staffs(staff_password):+ default_customer_type = get_default_customer_type()for permission in get_permissions():base_name = permission.codename.split("_")[1:]@@ -1153,7 +1156,9 @@ def create_staffs(staff_password):user_email = ".".join(email_base_name)user_email += "[email protected]"- user = _create_staff_user(staff_password, email=user_email)+ user = _create_staff_user(+ staff_password, email=user_email, customer_type=default_customer_type+ )group = create_group(group_name, [permission], [user])yield f"Group: {group}"@@ -1167,7 +1172,7 @@ def create_group(name, permissions, users):return group-def _create_staff_user(staff_password, email=None, superuser=False):+def _create_staff_user(staff_password, email=None, superuser=False, customer_type=None):address = create_address()first_name = address.first_namelast_name = address.last_name@@ -1188,6 +1193,7 @@ def _create_staff_user(staff_password, email=None, superuser=False):is_staff=True,is_active=True,is_superuser=superuser,+ customer_type=customer_type or get_default_customer_type(),)staff_user.addresses.add(address)update_user_search_vector(staff_user)@@ -1195,9 +1201,12 @@ def _create_staff_user(staff_password, email=None, superuser=False):def create_staff_users(staff_password, how_many=2, superuser=False):+ default_customer_type = get_default_customer_type()users = []for _ in range(how_many):- staff_user = _create_staff_user(staff_password, superuser=superuser)+ staff_user = _create_staff_user(+ staff_password, superuser=superuser, customer_type=default_customer_type+ )users.append(staff_user)return usersdiff --git a/saleor/graphql/account/bulk_mutations/customer_bulk_delete.py b/saleor/graphql/account/bulk_mutations/customer_bulk_delete.pyindex 52a2f4da85..808ffa2f3a 100644--- a/saleor/graphql/account/bulk_mutations/customer_bulk_delete.py+++ b/saleor/graphql/account/bulk_mutations/customer_bulk_delete.py@@ -2,6 +2,7 @@ import graphenefrom django.conf import settingsfrom ....account import models+from ....attribute.utils import delete_user_unique_attribute_valuesfrom ....core.tracing import traced_atomic_transactionfrom ....giftcard.utils import deactivate_assigned_gift_cardsfrom ....permission.enums import AccountPermissions@@ -63,6 +64,7 @@ class CustomerBulkDelete(CustomerDeleteMixin, UserBulkDelete):# on_delete=PROTECT, so restricted cards must be detached and# deactivated first, atomically with the deletion.deactivate_assigned_gift_cards(queryset)+ delete_user_unique_attribute_values(queryset.values_list("pk", flat=True))queryset.delete()webhooks = get_webhooks_for_event(WebhookEventAsyncType.CUSTOMER_DELETED)manager = get_plugin_manager_promise(info.context).get()diff --git a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py b/saleor/graphql/account/bulk_mutations/customer_bulk_update.pyindex 6c32e1d6bc..1f5f47bb53 100644--- a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py+++ b/saleor/graphql/account/bulk_mutations/customer_bulk_update.py@@ -9,6 +9,7 @@ from graphene.utils.str_converters import to_camel_casefrom ....account import modelsfrom ....account.events import CustomerEventsfrom ....account.search import update_user_search_vector+from ....account.utils import get_default_customer_typefrom ....checkout import AddressTypefrom ....core.tracing import traced_atomic_transactionfrom ....core.utils import metadata_manager@@ -18,6 +19,7 @@ from ....order.utils import match_orders_with_new_userfrom ....permission.enums import AccountPermissionsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.utils import get_webhooks_for_event+from ...attribute.utils.attribute_assignment import AttributeAssignmentMixinfrom ...core.doc_category import DOC_CATEGORY_USERSfrom ...core.enums import CustomerBulkUpdateErrorCode, ErrorPolicyEnumfrom ...core.mutations import BaseMutation, DeprecatedModelMutation@@ -37,9 +39,10 @@ from ..i18n import I18nMixinfrom ..mutations.base import (BILLING_ADDRESS_FIELD,SHIPPING_ADDRESS_FIELD,+ BaseCustomerCreate,CustomerInput,)-from ..types import User+from ..types import CustomerType, Userclass CustomerBulkResult(BaseObjectType):@@ -125,6 +128,7 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):path=f"input.{path}",message=e.messages[0],code=e.code,+ attributes=e.params.get("attributes") if e.params else None,))@@ -252,11 +256,24 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):billing_address_data = customer_input["input"].pop(BILLING_ADDRESS_FIELD, None)+ customer_type_id = customer_input["input"].pop("customer_type", None)customer_input["input"] = DeprecatedModelMutation.clean_input(info, None, customer_input["input"], input_cls=CustomerInput)+ if customer_type_id:+ try:+ customer_input["input"]["customer_type"] = cls.get_node_or_error(+ info,+ customer_type_id,+ field="customer_type",+ only_type=CustomerType,+ )+ except ValidationError as exc:+ cls.format_errors(index, exc, index_error_map)+ base_error_count += 1+new_external_ref = customer_input["input"].get("external_reference")base_error_count += cls.validate_customer(@@ -351,7 +368,11 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):)lookup |= single_customer_lookup- customers = models.User.objects.customers().filter(lookup)+ customers = (+ models.User.objects.customers()+ .filter(lookup)+ .select_related("customer_type")+ )return list(customers)@classmethod@@ -381,6 +402,7 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):def update_customers(cls, info, cleaned_inputs_map, index_error_map):instances_data_and_errors_list: list = []customers_list = cls.get_customers(cleaned_inputs_map)+ default_customer_type = Nonefor index, cleaned_input in cleaned_inputs_map.items():if not cleaned_input:@@ -394,6 +416,7 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):data = cleaned_input["input"]shipping_address_input = data.pop(SHIPPING_ADDRESS_FIELD, None)billing_address_input = data.pop(BILLING_ADDRESS_FIELD, None)+ attributes_input = data.pop("attributes", None)metadata_list: list[MetadataInput] = data.pop("metadata", None)private_metadata_list: list[MetadataInput] = data.pop("private_metadata", None@@ -414,6 +437,24 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):new_instance = cls.construct_instance(deepcopy(old_instance), data)new_instance.full_clean(exclude=["password"])+ cleaned_attributes = None+ if attributes_input:+ # Validate the values against the customer type the+ # user ends up with.+ if new_instance.customer_type_id:+ customer_type = new_instance.customer_type+ else:+ if default_customer_type is None:+ default_customer_type = get_default_customer_type()+ customer_type = default_customer_type++ try:+ cleaned_attributes = BaseCustomerCreate.clean_attributes(+ attributes_input, customer_type, creation=False+ )+ except ValidationError as e:+ raise ValidationError({"attributes": e}) from e+if shipping_address_input:shipping_address = cls.update_address(info,@@ -459,6 +500,7 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):"instance": new_instance,"old_instance": old_instance,"errors": index_error_map[index],+ "attributes": cleaned_attributes,SHIPPING_ADDRESS_FIELD: shipping_address,BILLING_ADDRESS_FIELD: billing_address,}@@ -550,12 +592,20 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):"note","language_code","external_reference",+ "customer_type","updated_at","metadata","private_metadata",],)+ for customer_data in instances_data_with_errors_list:+ customer = customer_data["instance"]+ if not customer:+ continue+ if attributes := customer_data.get("attributes"):+ AttributeAssignmentMixin.save(customer, attributes)+for customer in customers_to_update:if customer in customer_instance_new_addresses_map:customer.addresses.add(*customer_instance_new_addresses_map[customer])@@ -578,7 +628,10 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):return customers_to_update, old_instances@classmethod- def post_save_actions(cls, info, manager, instances, old_instances):+ def post_save_actions(+ cls, info, manager, instances, old_instances, user_pks_with_attributes=None+ ):+ user_pks_with_attributes = user_pks_with_attributes or set()customer_events = []app = get_app_promise(info.context).get()site = get_site_promise(info.context).get()@@ -671,6 +724,10 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):or old_instance.default_shipping_address_id!= updated_instance.default_shipping_address_id)+ customer_type_changed = (+ old_instance.customer_type_id != updated_instance.customer_type_id+ )+ attributes_updated = updated_instance.pk in user_pks_with_attributesinstance_modified = (has_new_nameor has_new_email@@ -681,6 +738,8 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):or note_changedor language_code_changedor external_reference_changed+ or customer_type_changed+ or attributes_updated)if instance_modified or (metadata_update and use_legacy_webhooks_emission):cls.call_event(@@ -745,6 +804,13 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):# prepare and return dataresults = cls.get_results(instances_data_with_errors_list)- cls.post_save_actions(info, manager, updated_customers, old_instances)+ user_pks_with_attributes = {+ item["instance"].pk+ for item in instances_data_with_errors_list+ if item.get("instance") and item.get("attributes")+ }+ cls.post_save_actions(+ info, manager, updated_customers, old_instances, user_pks_with_attributes+ )return CustomerBulkUpdate(count=len(updated_customers), results=results)diff --git a/saleor/graphql/account/bulk_mutations/staff_bulk_delete.py b/saleor/graphql/account/bulk_mutations/staff_bulk_delete.pyindex e11343344b..bf63555b8f 100644--- a/saleor/graphql/account/bulk_mutations/staff_bulk_delete.py+++ b/saleor/graphql/account/bulk_mutations/staff_bulk_delete.py@@ -4,6 +4,7 @@ from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom ....account import models+from ....attribute.utils import delete_user_unique_attribute_valuesfrom ....core.tracing import traced_atomic_transactionfrom ....giftcard.utils import deactivate_assigned_gift_cardsfrom ....permission.enums import AccountPermissions@@ -76,6 +77,7 @@ class StaffBulkDelete(StaffDeleteMixin, UserBulkDelete):# on_delete=PROTECT, so restricted cards must be detached and# deactivated first, atomically with the deletion.deactivate_assigned_gift_cards(queryset)+ delete_user_unique_attribute_values(queryset.values_list("pk", flat=True))queryset.delete()manager = get_plugin_manager_promise(info.context).get()webhooks = get_webhooks_for_event(WebhookEventAsyncType.STAFF_DELETED)diff --git a/saleor/graphql/account/dataloaders.py b/saleor/graphql/account/dataloaders.pyindex 8c539d52c7..ff5c5b41fe 100644--- a/saleor/graphql/account/dataloaders.py+++ b/saleor/graphql/account/dataloaders.py@@ -2,11 +2,15 @@ from collections import defaultdictfrom collections.abc import Iterablefrom typing import TypeVar, cast-from ...account.models import Address, CustomerEvent, Group, User+from ...account.exceptions import NoDefaultCustomerType+from ...account.models import Address, CustomerEvent, CustomerType, Group, User+from ...account.utils import get_default_customer_type+from ...attribute.models import Attribute, AttributeCustomerTypefrom ...channel.models import Channelfrom ...permission.models import Permissionfrom ...thumbnail.models import Thumbnailfrom ...thumbnail.utils import get_thumbnail_format+from ..attribute.dataloaders.attributes import AttributesByAttributeIdfrom ..core.dataloaders import DataLoader@@ -26,6 +30,93 @@ class UserByUserIdLoader(DataLoader[str, User]):return [user_map.get(user_id) for user_id in keys]+class CustomerTypeByIdLoader(DataLoader[int, CustomerType]):+ context_key = "customer_type_by_id"++ def batch_load(self, keys):+ customer_type_map = CustomerType.objects.using(+ self.database_connection_name+ ).in_bulk(keys)+ return [customer_type_map.get(customer_type_id) for customer_type_id in keys]+++DEFAULT_CUSTOMER_TYPE_LOADER_KEY = "default"+++class DefaultCustomerTypeLoader(DataLoader[str, CustomerType]):+ context_key = "default_customer_type"++ def batch_load(self, keys):+ try:+ default_customer_type = get_default_customer_type(+ database_connection_name=self.database_connection_name+ )+ except NoDefaultCustomerType:+ default_customer_type = None+ return [default_customer_type for _ in keys]+++class BaseCustomerAttributesByCustomerTypeIdLoader(DataLoader[int, list[Attribute]]):+ """Loads customer attributes by customer type ID."""++ context_key = "customer_attributes_by_customertype"++ @staticmethod+ def filter_attributes(attributes: list[Attribute]) -> list[Attribute]:+ """Filter attributes based on custom logic, if needed."""+ return attributes++ def batch_load(self, keys):+ customer_type_attribute_pairs = (+ AttributeCustomerType.objects.using(self.database_connection_name)+ .filter(customer_type_id__in=keys)+ .values_list("customer_type_id", "attribute_id")+ )+ attribute_ids = {attr_id for _, attr_id in customer_type_attribute_pairs}++ def map_attributes(attributes):+ attributes = self.filter_attributes(attributes)+ attributes_map = {attr.id: attr for attr in attributes}+ customer_type_to_attributes_map = defaultdict(list)+ for customer_type_id, attr_id in customer_type_attribute_pairs:+ if attr_id in attributes_map:+ # Only add attributes that are in the attributes_map to ensure+ # that filtered attributes are respected.+ customer_type_to_attributes_map[customer_type_id].append(+ attributes_map.get(attr_id)+ )+ return [+ customer_type_to_attributes_map.get(customer_type_id, [])+ for customer_type_id in keys+ ]++ return (+ AttributesByAttributeId(self.context)+ .load_many(attribute_ids)+ .then(map_attributes)+ )+++class CustomerAttributesAllByCustomerTypeIdLoader(+ BaseCustomerAttributesByCustomerTypeIdLoader+):+ """Loads all customer attributes by customer type ID."""++ context_key = "customer_attributes_all_by_customertype"+++class CustomerAttributesVisibleInStorefrontByCustomerTypeIdLoader(+ BaseCustomerAttributesByCustomerTypeIdLoader+):+ """Loads storefront-visible customer attributes by customer type ID."""++ context_key = "customer_attributes_visible_in_storefront_by_customertype"++ @staticmethod+ def filter_attributes(attributes: list[Attribute]) -> list[Attribute]:+ return [attr for attr in attributes if attr and attr.visible_in_storefront]++class CustomerEventsByUserLoader(DataLoader[str, list[CustomerEvent]]):context_key = "customer_events_by_user"diff --git a/saleor/graphql/account/filters.py b/saleor/graphql/account/filters.pyindex f1bf4e9927..6d89e39bd5 100644--- a/saleor/graphql/account/filters.py+++ b/saleor/graphql/account/filters.py@@ -1,9 +1,21 @@import django_filters-from django.db.models import Count, Exists, OuterRef--from ...account.models import Address, User+from django.db.models import Count, Exists, OuterRef, Q, QuerySet, Subquery+from django.db.models.functions import Coalesce++from ...account.models import Address, CustomerType, User+from ...attribute.models import (+ AssignedUserAttributeValue,+ AttributeCustomerType,+ AttributeValue,+)from ...core.search import prefix_searchfrom ...order.models import Order+from ..attribute.shared_filters import (+ AssignedAttributeWhereInput,+ filter_objects_by_attributes,+ validate_attribute_value_input,+)+from ..core.descriptions import ADDED_IN_323from ..core.doc_category import DOC_CATEGORY_USERSfrom ..core.filters import (BooleanWhereFilter,@@ -14,9 +26,14 @@ from ..core.filters import (ObjectTypeFilter,ObjectTypeWhereFilter,)-from ..core.filters.where_filters import MetadataWhereBase+from ..core.filters.where_filters import (+ ListObjectTypeWhereFilter,+ MetadataWhereBase,+ OperationObjectTypeWhereFilter,+)from ..core.filters.where_input import (FilterInputDescriptions,+ GlobalIDFilterInput,IntFilterInput,StringFilterInput,WhereInputObjectType,@@ -28,6 +45,7 @@ from ..core.types import (IntRangeInput,NonNullList,)+from ..utils import resolve_global_ids_to_primary_keysfrom ..utils.filters import (filter_by_id,filter_by_ids,@@ -111,6 +129,50 @@ class CustomerFilter(MetadataFilterBase):]+def filter_customer_type_search(qs, _, value):+ if not value:+ return qs+ return qs.filter(Q(name__trigram_similar=value) | Q(slug__trigram_similar=value))+++class CustomerTypeWhere(MetadataWhereBase):+ ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("CustomerType"))+ name = ObjectTypeWhereFilter(+ input_class=StringFilterInput,+ method="filter_name",+ help_text="Filter by customer type name.",+ )+ slug = ObjectTypeWhereFilter(+ input_class=StringFilterInput,+ method="filter_slug",+ help_text="Filter by customer type slug.",+ )+ is_default = BooleanWhereFilter(+ method="filter_is_default",+ help_text="Filter by whether the customer type is the default one.",+ )++ @staticmethod+ def filter_name(qs, _, value):+ return filter_where_by_value_field(qs, "name", value)++ @staticmethod+ def filter_slug(qs, _, value):+ return filter_where_by_value_field(qs, "slug", value)++ @staticmethod+ def filter_is_default(qs, _, value):+ if value is None:+ return qs.none()+ return qs.filter(is_default=value)+++class CustomerTypeWhereInput(WhereInputObjectType):+ class Meta:+ doc_category = DOC_CATEGORY_USERS+ filterset_class = CustomerTypeWhere++class CountryCodeEnumFilterInput(BaseInputObjectType):eq = CountryCodeEnum(description=FilterInputDescriptions.EQ, required=False)one_of = NonNullList(@@ -142,6 +204,48 @@ class AddressFilterInput(BaseInputObjectType):description = "Filtering options for addresses."+def _get_assigned_user_attribute_for_attribute_value(+ attribute_values: QuerySet[AttributeValue],+ db_connection_name: str,+):+ """Build an expression matching users by assigned attribute values.++ Values of attributes that are not assigned to the user's customer type+ are skipped, as such values are not exposed on the user. Users without+ an explicitly assigned customer type belong to the default one.+ """+ default_customer_type_id = Subquery(+ CustomerType.objects.using(db_connection_name)+ .filter(is_default=True)+ .values("id")[:1]+ )+ attribute_assigned_to_customer_type = AttributeCustomerType.objects.using(+ db_connection_name+ ).filter(+ attribute_id=OuterRef("value__attribute_id"),+ customer_type_id=Coalesce(+ OuterRef(OuterRef("customer_type_id")), default_customer_type_id+ ),+ )+ return Q(+ Exists(+ AssignedUserAttributeValue.objects.using(db_connection_name).filter(+ Exists(attribute_values.filter(id=OuterRef("value_id"))),+ Exists(attribute_assigned_to_customer_type),+ user_id=OuterRef("id"),+ )+ )+ )+++def filter_users_by_attributes(qs, value):+ return filter_objects_by_attributes(+ qs,+ value,+ _get_assigned_user_attribute_for_attribute_value,+ )++class CustomerWhereFilterInput(MetadataWhereBase):ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("User"))email = ObjectTypeWhereFilter(@@ -188,6 +292,20 @@ class CustomerWhereFilterInput(MetadataWhereBase):method="filter_number_of_orders",help_text="Filter by number of orders placed by the user.",)+ customer_type = OperationObjectTypeWhereFilter(+ input_class=GlobalIDFilterInput,+ method="filter_customer_type",+ help_text=(+ "Filter by customer type. Filtering by the default customer type "+ "also matches users without an explicitly assigned customer type."+ + ADDED_IN_323+ ),+ )+ attributes = ListObjectTypeWhereFilter(+ input_class=AssignedAttributeWhereInput,+ method="filter_attributes",+ help_text="Filter by attributes associated with the customer." + ADDED_IN_323,+ )@staticmethoddef filter_email(qs, _, value):@@ -241,6 +359,38 @@ class CustomerWhereFilterInput(MetadataWhereBase):return qs.none()return filter_where_range_field_with_conditions(qs, "number_of_orders", value)+ @staticmethod+ def filter_customer_type(qs, _, value):+ if not value:+ return qs.none()+ if eq := value.get("eq"):+ _, pks = resolve_global_ids_to_primary_keys([eq], "CustomerType", True)+ elif one_of := value.get("one_of"):+ _, pks = resolve_global_ids_to_primary_keys(one_of, "CustomerType", True)+ else:+ return qs.none()+ lookup = Q(customer_type_id__in=pks)+ if (+ CustomerType.objects.using(qs.db)+ .filter(is_default=True, pk__in=pks)+ .exists()+ ):+ # Users without an explicitly assigned customer type belong to the+ # default one.+ lookup |= Q(customer_type_id__isnull=True)+ return qs.filter(lookup)++ @staticmethod+ def filter_attributes(qs, _, value):+ if not value:+ return qs.none()+ return filter_users_by_attributes(qs, value)++ def is_valid(self):+ if attributes := self.data.get("attributes"):+ validate_attribute_value_input(attributes, self.queryset.db)+ return super().is_valid()+class CustomerWhereInput(WhereInputObjectType):class Meta:diff --git a/saleor/graphql/account/mutations/account/account_delete.py b/saleor/graphql/account/mutations/account/account_delete.pyindex f269cf9da6..ea7bed4ef8 100644--- a/saleor/graphql/account/mutations/account/account_delete.py+++ b/saleor/graphql/account/mutations/account/account_delete.py@@ -5,6 +5,7 @@ from django.core.exceptions import ValidationErrorfrom .....account import modelsfrom .....account.error_codes import AccountErrorCode+from .....attribute.utils import delete_user_unique_attribute_valuesfrom .....core.tokens import (account_delete_token_generator,legacy_account_delete_token_generator,@@ -89,6 +90,7 @@ class AccountDelete(ModelDeleteMutation):# on_delete=PROTECT, so restricted cards must be detached and# deactivated first, atomically with the deletion.deactivate_assigned_gift_cards([user])+ delete_user_unique_attribute_values([user.pk])user.delete()# After the instance is deleted, set its ID to the original database's# ID so that the success response contains ID of the deleted object.diff --git a/saleor/graphql/account/mutations/account/account_register.py b/saleor/graphql/account/mutations/account/account_register.pyindex ee733bb988..d13abb11d3 100644--- a/saleor/graphql/account/mutations/account/account_register.py+++ b/saleor/graphql/account/mutations/account/account_register.py@@ -7,7 +7,7 @@ from django.db import IntegrityError, transactionfrom .....account import modelsfrom .....account.error_codes import AccountErrorCodefrom .....account.tasks import finish_creating_user-from .....account.utils import RequestorAwareContext+from .....account.utils import RequestorAwareContext, get_default_customer_typefrom .....core.utils.url import validate_storefront_urlfrom .....webhook.event_types import WebhookEventAsyncTypefrom ....channel.utils import clean_channel@@ -237,6 +237,7 @@ class AccountRegister(DeprecatedModelMutation):cleaned_input["password"])instance.is_confirmed = False+ instance.customer_type = get_default_customer_type()user_created = Falseif not user_exists:diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.pyindex 111250e525..a3ddc3c8c6 100644--- a/saleor/graphql/account/mutations/base.py+++ b/saleor/graphql/account/mutations/base.py@@ -7,6 +7,7 @@ from ....account import events as account_eventsfrom ....account import modelsfrom ....account.error_codes import AccountErrorCodefrom ....account.search import update_user_search_vector+from ....account.utils import get_default_customer_typefrom ....checkout import AddressTypefrom ....core.exceptions import PermissionDeniedfrom ....core.utils import metadata_manager@@ -17,10 +18,12 @@ from ....graphql.utils import get_user_or_app_from_contextfrom ....permission.auth_filters import AuthorizationFiltersfrom ....permission.enums import AccountPermissionsfrom ...account.i18n import I18nMixin-from ...account.types import Address, AddressInput, User+from ...account.types import Address, AddressInput, CustomerType, Userfrom ...app.dataloaders import get_app_promise+from ...attribute.types import AttributeValueInput+from ...attribute.utils.attribute_assignment import AttributeAssignmentMixinfrom ...core import ResolveInfo, SaleorContext-from ...core.descriptions import DEPRECATED_IN_3X_INPUT+from ...core.descriptions import ADDED_IN_323, DEPRECATED_IN_3X_INPUTfrom ...core.doc_category import DOC_CATEGORY_USERSfrom ...core.enums import LanguageCodeEnumfrom ...core.mutations import DeprecatedModelMutation, ModelDeleteMutation@@ -220,6 +223,22 @@ class CustomerInput(UserInput, UserAddressInput):is_confirmed = graphene.Boolean(required=False, description="User account is confirmed.")+ customer_type = graphene.ID(+ required=False,+ description=(+ "ID of the customer type to assign to the user. If not provided "+ "when creating a customer, the default customer type is assigned."+ + ADDED_IN_323+ ),+ )+ attributes = NonNullList(+ AttributeValueInput,+ required=False,+ description=(+ "List of attribute values to assign to the user. The attributes "+ "must belong to the customer type the user ends up with." + ADDED_IN_323+ ),+ )class Meta:doc_category = DOC_CATEGORY_USERS@@ -263,12 +282,36 @@ class BaseCustomerCreate(DeprecatedModelMutation, I18nMixin):class Meta:abstract = True+ @classmethod+ def clean_attributes(+ cls,+ attributes: list[dict],+ customer_type: models.CustomerType,+ creation: bool,+ ):+ attributes_qs = customer_type.customer_attributes.all()+ return AttributeAssignmentMixin.clean_input(+ attributes,+ attributes_qs,+ creation=creation,+ error_class=AccountErrorCode,+ )+@classmethoddef clean_input(cls, info: ResolveInfo, instance, data, **kwargs):shipping_address_data = data.pop(SHIPPING_ADDRESS_FIELD, None)billing_address_data = data.pop(BILLING_ADDRESS_FIELD, None)+ customer_type_id = data.pop("customer_type", None)cleaned_input = super().clean_input(info, instance, data, **kwargs)+ if customer_type_id:+ cleaned_input["customer_type"] = cls.get_node_or_error(+ info,+ customer_type_id,+ field="customer_type",+ only_type=CustomerType,+ )+if shipping_address_data:shipping_address_metadata: list[MetadataInput] = shipping_address_data.pop("metadata", []@@ -338,6 +381,27 @@ class BaseCustomerCreate(DeprecatedModelMutation, I18nMixin):if not instance.id:cleaned_input["is_confirmed"] = False+ attributes = cleaned_input.get("attributes")+ if attributes:+ # The customer type from the input takes precedence over the+ # current one, so the values are validated against the type the+ # user ends up with.+ # TODO: when the customer type changes, values of attributes that+ # are not part of the new type persist in the database and are only+ # hidden from the API. Migrating or pruning those values is left+ # for a future iteration.+ customer_type = cleaned_input.get("customer_type")+ if customer_type is None and instance.customer_type_id:+ customer_type = instance.customer_type+ if customer_type is None:+ customer_type = get_default_customer_type()+ try:+ cleaned_input["attributes"] = cls.clean_attributes(+ attributes, customer_type, creation=instance.pk is None+ )+ except ValidationError as e:+ raise ValidationError({"attributes": e}) from e+return cleaned_input@classmethoddiff --git a/saleor/graphql/account/mutations/customer_type/__init__.py b/saleor/graphql/account/mutations/customer_type/__init__.pynew file mode 100644index 0000000000..1a496158f6--- /dev/null+++ b/saleor/graphql/account/mutations/customer_type/__init__.py@@ -0,0 +1,15 @@+from .customer_type_assign_attributes import CustomerTypeAssignAttributes+from .customer_type_create import CustomerTypeCreate+from .customer_type_delete import CustomerTypeDelete+from .customer_type_reorder_attributes import CustomerTypeReorderAttributes+from .customer_type_unassign_attributes import CustomerTypeUnassignAttributes+from .customer_type_update import CustomerTypeUpdate++__all__ = [+ "CustomerTypeAssignAttributes",+ "CustomerTypeUnassignAttributes",+ "CustomerTypeCreate",+ "CustomerTypeDelete",+ "CustomerTypeReorderAttributes",+ "CustomerTypeUpdate",+]diff --git a/saleor/graphql/account/mutations/customer_type/customer_type_assign_attributes.py b/saleor/graphql/account/mutations/customer_type/customer_type_assign_attributes.pynew file mode 100644index 0000000000..35d54c328a--- /dev/null+++ b/saleor/graphql/account/mutations/customer_type/customer_type_assign_attributes.py@@ -0,0 +1,164 @@+from collections import defaultdict++import graphene+from django.core.exceptions import ValidationError++from .....account import models as account_models+from .....attribute import AttributeType+from .....attribute import models as attribute_models+from .....permission.enums import CustomerTypePermissions+from .....webhook.event_types import WebhookEventAsyncType+from ....attribute.types import Attribute+from ....core import ResolveInfo+from ....core.descriptions import ADDED_IN_323+from ....core.doc_category import DOC_CATEGORY_USERS+from ....core.enums import CustomerTypeAssignAttributesErrorCode+from ....core.mutations import BaseMutation+from ....core.types import Error, NonNullList+from ....core.utils import WebhookEventInfo+from ....plugins.dataloaders import get_plugin_manager_promise+from ...types import CustomerType++ATTRIBUTES_LIMIT = 100+++class CustomerTypeAssignAttributesError(Error):+ code = CustomerTypeAssignAttributesErrorCode(+ description="The error code.", required=True+ )+ attributes = NonNullList(+ graphene.ID,+ description="List of attributes IDs which causes the error.",+ required=False,+ )++ class Meta:+ doc_category = DOC_CATEGORY_USERS+++class CustomerTypeAssignAttributes(BaseMutation):+ customer_type = graphene.Field(+ CustomerType, description="The updated customer type."+ )++ class Arguments:+ customer_type_id = graphene.ID(+ required=True,+ description="ID of the customer type to assign the attributes to.",+ )+ attribute_ids = NonNullList(+ graphene.ID,+ required=True,+ description=(+ "The IDs of the attributes to assign. "+ f"Maximum of {ATTRIBUTES_LIMIT} items."+ ),+ )++ class Meta:+ description = "Assign attributes to a given customer type." + ADDED_IN_323+ doc_category = DOC_CATEGORY_USERS+ error_type_class = CustomerTypeAssignAttributesError+ permissions = (CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES,)+ webhook_events_info = [+ WebhookEventInfo(+ type=WebhookEventAsyncType.CUSTOMER_TYPE_UPDATED,+ description="A customer type was updated.",+ ),+ ]++ @classmethod+ def clean_attributes(+ cls,+ errors: dict[str, list[ValidationError]],+ customer_type: account_models.CustomerType,+ attr_pks: list[int],+ ):+ """Ensure the attributes exist, are customer attributes, and are not assigned."""+ attr_type_by_pk = dict(+ attribute_models.Attribute.objects.filter(pk__in=attr_pks).values_list(+ "pk", "type"+ )+ )++ found_pks = {str(pk) for pk in attr_type_by_pk}+ missing_pks = [pk for pk in attr_pks if str(pk) not in found_pks]+ if missing_pks:+ missing_attributes_ids = [+ graphene.Node.to_global_id("Attribute", pk) for pk in missing_pks+ ]+ error = ValidationError(+ "Some of the attributes do not exist.",+ code=CustomerTypeAssignAttributesErrorCode.NOT_FOUND.value,+ params={"attributes": missing_attributes_ids},+ )+ errors["attribute_ids"].append(error)++ invalid_attributes_ids = [+ graphene.Node.to_global_id("Attribute", pk)+ for pk, attr_type in attr_type_by_pk.items()+ if attr_type != AttributeType.CUSTOMER_TYPE+ ]+ if invalid_attributes_ids:+ error = ValidationError(+ "Only customer attributes can be assigned.",+ code=CustomerTypeAssignAttributesErrorCode.INVALID.value,+ params={"attributes": invalid_attributes_ids},+ )+ errors["attribute_ids"].append(error)++ assigned_attrs = (+ attribute_models.Attribute.objects.get_assigned_customer_type_attributes(+ customer_type.pk+ ).filter(pk__in=attr_pks)+ )++ if assigned_attrs:+ assigned_attributes_ids = [+ graphene.Node.to_global_id("Attribute", attr.pk)+ for attr in assigned_attrs+ ]+ error = ValidationError(+ "Some of the attributes have been already assigned to this "+ "customer type.",+ code=CustomerTypeAssignAttributesErrorCode.ATTRIBUTE_ALREADY_ASSIGNED.value,+ params={"attributes": assigned_attributes_ids},+ )+ errors["attribute_ids"].append(error)++ @classmethod+ def perform_mutation( # type: ignore[override]+ cls, _root, info: ResolveInfo, /, *, attribute_ids, customer_type_id+ ):+ if len(attribute_ids) > ATTRIBUTES_LIMIT:+ raise ValidationError(+ {+ "attribute_ids": ValidationError(+ f"Cannot assign more than {ATTRIBUTES_LIMIT} attributes "+ "in a single mutation.",+ code=CustomerTypeAssignAttributesErrorCode.INVALID.value,+ )+ }+ )++ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)++ customer_type = cls.get_node_or_error(+ info, customer_type_id, only_type=CustomerType, field="customer_type_id"+ )++ attr_pks = cls.get_global_ids_or_error(+ attribute_ids, Attribute, field="attribute_ids"+ )++ cls.clean_attributes(errors, customer_type, attr_pks)++ if errors:+ raise ValidationError(errors)++ customer_type.customer_attributes.add(*attr_pks)++ manager = get_plugin_manager_promise(info.context).get()+ cls.call_event(manager.customer_type_updated, customer_type)++ return cls(customer_type=customer_type)diff --git a/saleor/graphql/account/mutations/customer_type/customer_type_create.py b/saleor/graphql/account/mutations/customer_type/customer_type_create.pynew file mode 100644index 0000000000..c6b338ccba--- /dev/null+++ b/saleor/graphql/account/mutations/customer_type/customer_type_create.py@@ -0,0 +1,113 @@+from collections import defaultdict++import graphene+from django.core.exceptions import ValidationError++from .....account import models+from .....account.lock_objects import customer_type_qs_select_for_update+from .....core.tracing import traced_atomic_transaction+from .....permission.enums import CustomerTypePermissions+from .....webhook.event_types import WebhookEventAsyncType+from ....core import ResolveInfo+from ....core.descriptions import ADDED_IN_323+from ....core.doc_category import DOC_CATEGORY_USERS+from ....core.enums import CustomerTypeCreateErrorCode+from ....core.mutations import DeprecatedModelMutation+from ....core.types import BaseInputObjectType, Error+from ....core.utils import WebhookEventInfo+from ....core.validators import validate_slug_and_generate_if_needed+from ....plugins.dataloaders import get_plugin_manager_promise+from ...types import CustomerType+++class CustomerTypeCreateError(Error):+ code = CustomerTypeCreateErrorCode(description="The error code.", required=True)++ class Meta:+ doc_category = DOC_CATEGORY_USERS+++class CustomerTypeCreateInput(BaseInputObjectType):+ name = graphene.String(description="Name of the customer type.")+ slug = graphene.String(+ description=(+ "Slug of the customer type. If not provided, it will be generated "+ "from the name."+ )+ )+ is_default = graphene.Boolean(+ description=(+ "Determines if the customer type should become the default one, "+ "assigned to every newly created user. Passing `true` clears the "+ "flag on the current default customer type - exactly one default "+ "customer type always exists."+ )+ )++ class Meta:+ doc_category = DOC_CATEGORY_USERS+++class CustomerTypeDefaultTransferMixin:+ """Atomically transfer the default flag when `isDefault: true` is passed.++ The whole mutation runs in a transaction that locks all customer type rows+ to serialize concurrent default transfers, then clears the current default+ before the instance is validated and saved, so the partial unique+ constraint on `is_default` is never violated and the last writer wins.+ """++ @classmethod+ def perform_mutation(cls, root, info: ResolveInfo, /, **data):+ input_data = data.get("input") or {}+ if not input_data.get("is_default"):+ return super().perform_mutation(root, info, **data) # type: ignore[misc]+ with traced_atomic_transaction():+ # Evaluate the queryset to acquire the locks.+ # Deliberately do not use the queryset for clearing the default flag.+ list(customer_type_qs_select_for_update().values_list("pk", flat=True))+ models.CustomerType.objects.filter(is_default=True).update(is_default=False)+ return super().perform_mutation(root, info, **data) # type: ignore[misc]+++class CustomerTypeCreate(CustomerTypeDefaultTransferMixin, DeprecatedModelMutation):+ class Arguments:+ input = CustomerTypeCreateInput(+ description="Fields required to create a customer type.", required=True+ )++ class Meta:+ description = "Creates a new customer type." + ADDED_IN_323+ model = models.CustomerType+ object_type = CustomerType+ permissions = (CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES,)+ error_type_class = CustomerTypeCreateError+ doc_category = DOC_CATEGORY_USERS+ webhook_events_info = [+ WebhookEventInfo(+ type=WebhookEventAsyncType.CUSTOMER_TYPE_CREATED,+ description="A new customer type was created.",+ ),+ ]++ @classmethod+ def clean_input(cls, info: ResolveInfo, instance, data, **kwargs):+ cleaned_input = super().clean_input(info, instance, data, **kwargs)+ errors = defaultdict(list)+ try:+ cleaned_input = validate_slug_and_generate_if_needed(+ instance, "name", cleaned_input+ )+ except ValidationError as error:+ error.code = CustomerTypeCreateErrorCode.REQUIRED.value+ errors["slug"].append(error)++ if errors:+ raise ValidationError(errors)++ return cleaned_input++ @classmethod+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):+ manager = get_plugin_manager_promise(info.context).get()+ cls.call_event(manager.customer_type_created, instance)diff --git a/saleor/graphql/account/mutations/customer_type/customer_type_delete.py b/saleor/graphql/account/mutations/customer_type/customer_type_delete.pynew file mode 100644index 0000000000..7f826a6dd4--- /dev/null+++ b/saleor/graphql/account/mutations/customer_type/customer_type_delete.py@@ -0,0 +1,87 @@+import graphene+from django.core.exceptions import ValidationError++from .....account import models+from .....account.lock_objects import customer_type_qs_select_for_update+from .....account.utils import get_default_customer_type+from .....core.tracing import traced_atomic_transaction+from .....permission.enums import CustomerTypePermissions+from .....webhook.event_types import WebhookEventAsyncType+from ....core import ResolveInfo+from ....core.descriptions import ADDED_IN_323+from ....core.doc_category import DOC_CATEGORY_USERS+from ....core.enums import CustomerTypeDeleteErrorCode+from ....core.mutations import ModelDeleteMutation+from ....core.types import Error+from ....core.utils import WebhookEventInfo+from ....plugins.dataloaders import get_plugin_manager_promise+from ...types import CustomerType+++class CustomerTypeDeleteError(Error):+ code = CustomerTypeDeleteErrorCode(description="The error code.", required=True)++ class Meta:+ doc_category = DOC_CATEGORY_USERS+++class CustomerTypeDelete(ModelDeleteMutation):+ class Arguments:+ id = graphene.ID(+ description="ID of the customer type to delete.", required=True+ )++ class Meta:+ description = (+ "Deletes a customer type. Users of the deleted customer type are "+ "reassigned to the default customer type." + ADDED_IN_323+ )+ model = models.CustomerType+ object_type = CustomerType+ permissions = (CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES,)+ error_type_class = CustomerTypeDeleteError+ doc_category = DOC_CATEGORY_USERS+ webhook_events_info = [+ WebhookEventInfo(+ type=WebhookEventAsyncType.CUSTOMER_TYPE_DELETED,+ description="A customer type was deleted.",+ ),+ ]++ @classmethod+ def clean_instance(cls, _info: ResolveInfo, instance, /):+ if instance.is_default:+ raise ValidationError(+ {+ "id": ValidationError(+ "The default customer type cannot be deleted. Mark "+ "another customer type as the default first.",+ code=CustomerTypeDeleteErrorCode.CANNOT_DELETE_DEFAULT.value,+ )+ }+ )++ @classmethod+ def perform_mutation( # type: ignore[override]+ cls, _root, info: ResolveInfo, /, *, id: str+ ):+ customer_type_pk = cls.get_global_id_or_error(+ id, only_type=CustomerType, field="pk"+ )+ with traced_atomic_transaction():+ # Evaluate the queryset to acquire the locks.+ list(customer_type_qs_select_for_update().values_list("pk", flat=True))+ default_customer_type = get_default_customer_type()+ if str(default_customer_type.pk) != str(customer_type_pk):+ # Deliberate lack of CUSTOMER_UPDATED events due to+ # an unbounded number of users that may be affected.+ # CUSTOMER_TYPE_DELETED event already implies the change.+ models.User.objects.filter(customer_type_id=customer_type_pk).update(+ customer_type=default_customer_type+ )+ return super().perform_mutation(_root, info, id=id)++ @classmethod+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):+ manager = get_plugin_manager_promise(info.context).get()+ cls.call_event(manager.customer_type_deleted, instance)diff --git a/saleor/graphql/account/mutations/customer_type/customer_type_reorder_attributes.py b/saleor/graphql/account/mutations/customer_type/customer_type_reorder_attributes.pynew file mode 100644index 0000000000..728a653b53--- /dev/null+++ b/saleor/graphql/account/mutations/customer_type/customer_type_reorder_attributes.py@@ -0,0 +1,96 @@+import graphene+from django.core.exceptions import ObjectDoesNotExist, ValidationError++from .....account import models+from .....core.tracing import traced_atomic_transaction+from .....permission.enums import CustomerTypePermissions+from .....webhook.event_types import WebhookEventAsyncType+from ....attribute.mutations import BaseReorderAttributesMutation+from ....core import ResolveInfo+from ....core.descriptions import ADDED_IN_323+from ....core.doc_category import DOC_CATEGORY_USERS+from ....core.enums import CustomerTypeReorderAttributesErrorCode+from ....core.inputs import ReorderInput+from ....core.types import Error, NonNullList+from ....core.utils import WebhookEventInfo+from ....core.utils.reordering import perform_reordering+from ....plugins.dataloaders import get_plugin_manager_promise+from ...types import CustomerType+++class CustomerTypeReorderAttributesError(Error):+ code = CustomerTypeReorderAttributesErrorCode(+ description="The error code.", required=True+ )+ attributes = NonNullList(+ graphene.ID,+ description="List of attributes IDs which causes the error.",+ required=False,+ )++ class Meta:+ doc_category = DOC_CATEGORY_USERS+++class CustomerTypeReorderAttributes(BaseReorderAttributesMutation):+ customer_type = graphene.Field(+ CustomerType, description="Customer type from which attributes are reordered."+ )++ class Arguments:+ customer_type_id = graphene.Argument(+ graphene.ID, required=True, description="ID of a customer type."+ )+ moves = NonNullList(+ ReorderInput,+ required=True,+ description="The list of attribute reordering operations.",+ )++ class Meta:+ description = "Reorder the attributes of a customer type." + ADDED_IN_323+ doc_category = DOC_CATEGORY_USERS+ error_type_class = CustomerTypeReorderAttributesError+ permissions = (CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES,)+ webhook_events_info = [+ WebhookEventInfo(+ type=WebhookEventAsyncType.CUSTOMER_TYPE_UPDATED,+ description="A customer type was updated.",+ ),+ ]++ @classmethod+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):+ customer_type_id = data["customer_type_id"]+ pk = cls.get_global_id_or_error(+ customer_type_id, only_type=CustomerType, field="customer_type_id"+ )++ try:+ customer_type = models.CustomerType.objects.get(pk=pk)+ except ObjectDoesNotExist as e:+ raise ValidationError(+ {+ "customer_type_id": ValidationError(+ f"Couldn't resolve to a customer type: {customer_type_id}",+ code=CustomerTypeReorderAttributesErrorCode.NOT_FOUND.value,+ )+ }+ ) from e++ customer_attributes = customer_type.attributecustomertype.all()+ moves = data["moves"]++ try:+ operations = cls.prepare_operations(moves, customer_attributes)+ except ValidationError as e:+ e.code = CustomerTypeReorderAttributesErrorCode.NOT_FOUND.value+ raise ValidationError({"moves": e}) from e++ with traced_atomic_transaction():+ perform_reordering(customer_attributes, operations)++ manager = get_plugin_manager_promise(info.context).get()+ cls.call_event(manager.customer_type_updated, customer_type)++ return CustomerTypeReorderAttributes(customer_type=customer_type)diff --git a/saleor/graphql/account/mutations/customer_type/customer_type_unassign_attributes.py b/saleor/graphql/account/mutations/customer_type/customer_type_unassign_attributes.pynew file mode 100644index 0000000000..f79e4632b5--- /dev/null+++ b/saleor/graphql/account/mutations/customer_type/customer_type_unassign_attributes.py@@ -0,0 +1,95 @@+import graphene+from django.core.exceptions import ValidationError++from .....permission.enums import CustomerTypePermissions+from .....webhook.event_types import WebhookEventAsyncType+from ....attribute.types import Attribute+from ....core import ResolveInfo+from ....core.descriptions import ADDED_IN_323+from ....core.doc_category import DOC_CATEGORY_USERS+from ....core.enums import CustomerTypeUnassignAttributesErrorCode+from ....core.mutations import BaseMutation+from ....core.types import Error, NonNullList+from ....core.utils import WebhookEventInfo+from ....plugins.dataloaders import get_plugin_manager_promise+from ....utils import resolve_global_ids_to_primary_keys+from ...types import CustomerType++ATTRIBUTES_LIMIT = 100+++class CustomerTypeUnassignAttributesError(Error):+ code = CustomerTypeUnassignAttributesErrorCode(+ description="The error code.", required=True+ )++ class Meta:+ doc_category = DOC_CATEGORY_USERS+++class CustomerTypeUnassignAttributes(BaseMutation):+ customer_type = graphene.Field(+ CustomerType, description="The updated customer type."+ )++ class Arguments:+ customer_type_id = graphene.ID(+ required=True,+ description=(+ "ID of the customer type from which the attributes should be "+ "unassigned."+ ),+ )+ attribute_ids = NonNullList(+ graphene.ID,+ required=True,+ description=(+ "The IDs of the attributes to unassign. "+ f"Maximum of {ATTRIBUTES_LIMIT} items."+ ),+ )++ class Meta:+ description = (+ "Unassign attributes from a given customer type. Values already "+ "assigned to users are kept in the database, but are hidden until "+ "the attribute is assigned to the user's customer type again."+ + ADDED_IN_323+ )+ doc_category = DOC_CATEGORY_USERS+ error_type_class = CustomerTypeUnassignAttributesError+ permissions = (CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES,)+ webhook_events_info = [+ WebhookEventInfo(+ type=WebhookEventAsyncType.CUSTOMER_TYPE_UPDATED,+ description="A customer type was updated.",+ ),+ ]++ @classmethod+ def perform_mutation( # type: ignore[override]+ cls, _root, info: ResolveInfo, /, *, attribute_ids, customer_type_id+ ):+ if len(attribute_ids) > ATTRIBUTES_LIMIT:+ raise ValidationError(+ {+ "attribute_ids": ValidationError(+ f"Cannot unassign more than {ATTRIBUTES_LIMIT} attributes "+ "in a single mutation.",+ code=CustomerTypeUnassignAttributesErrorCode.INVALID.value,+ )+ }+ )++ customer_type = cls.get_node_or_error(+ info, customer_type_id, only_type=CustomerType, field="customer_type_id"+ )++ _, attr_pks = resolve_global_ids_to_primary_keys(attribute_ids, Attribute)++ customer_type.customer_attributes.remove(*attr_pks)++ manager = get_plugin_manager_promise(info.context).get()+ cls.call_event(manager.customer_type_updated, customer_type)++ return cls(customer_type=customer_type)diff --git a/saleor/graphql/account/mutations/customer_type/customer_type_update.py b/saleor/graphql/account/mutations/customer_type/customer_type_update.pynew file mode 100644index 0000000000..84d5f66338--- /dev/null+++ b/saleor/graphql/account/mutations/customer_type/customer_type_update.py@@ -0,0 +1,89 @@+from collections import defaultdict++import graphene+from django.core.exceptions import ValidationError++from .....account import models+from .....permission.enums import CustomerTypePermissions+from .....webhook.event_types import WebhookEventAsyncType+from ....core import ResolveInfo+from ....core.descriptions import ADDED_IN_323+from ....core.doc_category import DOC_CATEGORY_USERS+from ....core.enums import CustomerTypeUpdateErrorCode+from ....core.mutations import DeprecatedModelMutation+from ....core.types import Error+from ....core.utils import WebhookEventInfo+from ....core.validators import validate_slug_and_generate_if_needed+from ....plugins.dataloaders import get_plugin_manager_promise+from ...types import CustomerType+from .customer_type_create import (+ CustomerTypeCreateInput,+ CustomerTypeDefaultTransferMixin,+)+++class CustomerTypeUpdateError(Error):+ code = CustomerTypeUpdateErrorCode(description="The error code.", required=True)++ class Meta:+ doc_category = DOC_CATEGORY_USERS+++class CustomerTypeUpdateInput(CustomerTypeCreateInput):+ class Meta:+ doc_category = DOC_CATEGORY_USERS+++class CustomerTypeUpdate(CustomerTypeDefaultTransferMixin, DeprecatedModelMutation):+ class Arguments:+ id = graphene.ID(+ description="ID of the customer type to update.", required=True+ )+ input = CustomerTypeUpdateInput(+ description="Fields required to update a customer type.", required=True+ )++ class Meta:+ description = "Updates a customer type." + ADDED_IN_323+ model = models.CustomerType+ object_type = CustomerType+ permissions = (CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES,)+ error_type_class = CustomerTypeUpdateError+ doc_category = DOC_CATEGORY_USERS+ webhook_events_info = [+ WebhookEventInfo(+ type=WebhookEventAsyncType.CUSTOMER_TYPE_UPDATED,+ description="A customer type was updated.",+ ),+ ]++ @classmethod+ def clean_input(cls, info: ResolveInfo, instance, data, **kwargs):+ cleaned_input = super().clean_input(info, instance, data, **kwargs)+ errors = defaultdict(list)+ try:+ cleaned_input = validate_slug_and_generate_if_needed(+ instance, "name", cleaned_input+ )+ except ValidationError as error:+ error.code = CustomerTypeUpdateErrorCode.REQUIRED.value+ errors["slug"].append(error)++ if cleaned_input.get("is_default") is False and instance.is_default:+ errors["is_default"].append(+ ValidationError(+ "The default flag cannot be unset. Mark another customer "+ "type as the default instead.",+ code=CustomerTypeUpdateErrorCode.CANNOT_UNSET_DEFAULT.value,+ )+ )++ if errors:+ raise ValidationError(errors)++ return cleaned_input++ @classmethod+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):+ manager = get_plugin_manager_promise(info.context).get()+ cls.call_event(manager.customer_type_updated, instance)diff --git a/saleor/graphql/account/mutations/staff/customer_create.py b/saleor/graphql/account/mutations/staff/customer_create.pyindex db5c91fc29..0e1999a47b 100644--- a/saleor/graphql/account/mutations/staff/customer_create.py+++ b/saleor/graphql/account/mutations/staff/customer_create.py@@ -7,6 +7,7 @@ from .....account import events as account_eventsfrom .....account import modelsfrom .....account.notifications import send_set_password_notificationfrom .....account.search import update_user_search_vector+from .....account.utils import get_default_customer_typefrom .....core.tokens import password_reset_token_generatorfrom .....core.tracing import traced_atomic_transactionfrom .....core.utils.url import prepare_url@@ -14,6 +15,7 @@ from .....permission.enums import AccountPermissionsfrom .....plugins.manager import PluginsManagerfrom .....webhook.event_types import WebhookEventAsyncTypefrom ....account.types import User+from ....attribute.utils.attribute_assignment import AttributeAssignmentMixinfrom ....channel.utils import clean_channel, validate_channelfrom ....core import ResolveInfofrom ....core.doc_category import DOC_CATEGORY_USERS@@ -108,8 +110,14 @@ class CustomerCreate(BaseCustomerCreate):addresses_to_set_on_user.append(default_billing_address)default_billing_address.save()+ if instance.customer_type_id is None:+ instance.customer_type = get_default_customer_type()+cls._save(instance)+ if attributes := cleaned_input.get("attributes"):+ AttributeAssignmentMixin.save(instance, attributes)+if addresses_to_set_on_user:instance.addresses.set(addresses_to_set_on_user)diff --git a/saleor/graphql/account/mutations/staff/customer_delete.py b/saleor/graphql/account/mutations/staff/customer_delete.pyindex ab3ca4acbd..8a59ffc29f 100644--- a/saleor/graphql/account/mutations/staff/customer_delete.py+++ b/saleor/graphql/account/mutations/staff/customer_delete.py@@ -1,6 +1,7 @@import graphenefrom .....account import models+from .....attribute.utils import delete_user_unique_attribute_valuesfrom .....core.tracing import traced_atomic_transactionfrom .....giftcard.utils import deactivate_assigned_gift_cardsfrom .....permission.enums import AccountPermissions@@ -51,6 +52,7 @@ class CustomerDelete(CustomerDeleteMixin, UserDelete):# Runs inside the deletion transaction, right before the user is# removed. Required because GiftCard.assigned_to is on_delete=PROTECT.deactivate_assigned_gift_cards([instance])+ delete_user_unique_attribute_values([instance.pk])@classmethoddef post_save_action(cls, info: ResolveInfo, instance, cleaned_input):diff --git a/saleor/graphql/account/mutations/staff/customer_update.py b/saleor/graphql/account/mutations/staff/customer_update.pyindex 3bfe307faa..a307c48c82 100644--- a/saleor/graphql/account/mutations/staff/customer_update.py+++ b/saleor/graphql/account/mutations/staff/customer_update.py@@ -15,6 +15,7 @@ from .....permission.enums import AccountPermissionsfrom .....webhook.event_types import WebhookEventAsyncTypefrom ....account.types import Userfrom ....app.dataloaders import get_app_promise+from ....attribute.utils.attribute_assignment import AttributeAssignmentMixinfrom ....core import ResolveInfofrom ....core.doc_category import DOC_CATEGORY_USERSfrom ....core.mutations import ModelWithExtRefMutation@@ -171,18 +172,29 @@ class CustomerUpdate(BaseCustomerCreate, ModelWithExtRefMutation):)cls._save_m2m(info, instance, cleaned_input)+ attributes_modified = False+ if attributes := cleaned_input.get("attributes"):+ AttributeAssignmentMixin.save(instance, attributes)+ attributes_modified = True+cls.generate_events(info, instance, instance_tracker, non_metadata_modified_fields)- if non_metadata_modified_fields or metadata_modified_fields:+ if (+ non_metadata_modified_fields+ or metadata_modified_fields+ or attributes_modified+ ):site = get_site_promise(info.context).get()use_legacy_webhooks_emission = (site.settings.use_legacy_update_webhook_emission)manager = get_plugin_manager_promise(info.context).get()- if non_metadata_modified_fields or (- metadata_modified_fields and use_legacy_webhooks_emission+ if (+ non_metadata_modified_fields+ or attributes_modified+ or (metadata_modified_fields and use_legacy_webhooks_emission)):cls.call_event(manager.customer_updated, instance)diff --git a/saleor/graphql/account/mutations/staff/staff_create.py b/saleor/graphql/account/mutations/staff/staff_create.pyindex 278d2cd821..b83aff18eb 100644--- a/saleor/graphql/account/mutations/staff/staff_create.py+++ b/saleor/graphql/account/mutations/staff/staff_create.py@@ -9,6 +9,7 @@ from .....account import modelsfrom .....account.error_codes import AccountErrorCodefrom .....account.notifications import send_set_password_notificationfrom .....account.search import USER_SEARCH_FIELDS, update_user_search_vector+from .....account.utils import get_default_customer_typefrom .....core.exceptions import PermissionDeniedfrom .....core.tokens import password_reset_token_generatorfrom .....core.tracing import traced_atomic_transaction@@ -171,6 +172,8 @@ class StaffCreate(DeprecatedModelMutation):):if any(field in cleaned_input for field in USER_SEARCH_FIELDS):update_user_search_vector(user, attach_addresses_data=False, save=False)+ if user.customer_type_id is None:+ user.customer_type = get_default_customer_type()user.save()redirect_url = cleaned_input.get("redirect_url")if redirect_url and send_notification:diff --git a/saleor/graphql/account/mutations/staff/staff_delete.py b/saleor/graphql/account/mutations/staff/staff_delete.pyindex 2c5f1ec92c..824e336ee0 100644--- a/saleor/graphql/account/mutations/staff/staff_delete.py+++ b/saleor/graphql/account/mutations/staff/staff_delete.py@@ -1,6 +1,7 @@import graphenefrom .....account import models+from .....attribute.utils import delete_user_unique_attribute_valuesfrom .....core.tracing import traced_atomic_transactionfrom .....giftcard.utils import deactivate_assigned_gift_cardsfrom .....permission.enums import AccountPermissions@@ -49,6 +50,7 @@ class StaffDelete(StaffDeleteMixin, UserDelete):# on_delete=PROTECT, so restricted cards must be detached and# deactivated first, atomically with the deletion.deactivate_assigned_gift_cards([instance])+ delete_user_unique_attribute_values([instance.pk])instance.delete()# After the instance is deleted, set its ID to the original database's# ID so that the success response contains ID of the deleted object.diff --git a/saleor/graphql/account/mutations/staff/utils.py b/saleor/graphql/account/mutations/staff/utils.pyindex 8ffb4302d4..581aadb2be 100644--- a/saleor/graphql/account/mutations/staff/utils.py+++ b/saleor/graphql/account/mutations/staff/utils.py@@ -7,6 +7,7 @@ CUSTOMER_UPDATE_FIELDS = {"external_reference","is_confirmed","language_code",+ "customer_type_id","metadata","private_metadata",}diff --git a/saleor/graphql/account/resolvers.py b/saleor/graphql/account/resolvers.pyindex 67e56aeb2b..c1deedb279 100644--- a/saleor/graphql/account/resolvers.py+++ b/saleor/graphql/account/resolvers.py@@ -42,6 +42,20 @@ def resolve_customers(info):)+def resolve_customer_type(info, id):+ return (+ models.CustomerType.objects.using(get_database_connection_name(info.context))+ .filter(id=id)+ .first()+ )+++def resolve_customer_types(info):+ return models.CustomerType.objects.using(+ get_database_connection_name(info.context)+ ).all()++def resolve_permission_group(info, id):return (models.Group.objects.using(get_database_connection_name(info.context))diff --git a/saleor/graphql/account/schema.py b/saleor/graphql/account/schema.pyindex 026cae02e2..c022483658 100644--- a/saleor/graphql/account/schema.py+++ b/saleor/graphql/account/schema.py@@ -2,12 +2,16 @@ import graphenefrom ...core.search import prefix_searchfrom ...permission.auth_filters import AuthorizationFilters-from ...permission.enums import AccountPermissions, OrderPermissions+from ...permission.enums import (+ AccountPermissions,+ CustomerTypePermissions,+ OrderPermissions,+)from ...permission.utils import message_one_of_permissions_requiredfrom ..app.dataloaders import app_promise_callbackfrom ..core import ResolveInfofrom ..core.connection import create_connection_slice, filter_connection_queryset-from ..core.descriptions import ADDED_IN_322, DEPRECATED_IN_3X_INPUT+from ..core.descriptions import ADDED_IN_322, ADDED_IN_323, DEPRECATED_IN_3X_INPUTfrom ..core.doc_category import DOC_CATEGORY_USERSfrom ..core.fields import BaseField, FilterConnectionField, PermissionsFieldfrom ..core.filters import FilterInputObjectType@@ -25,9 +29,11 @@ from .bulk_mutations import (from .enums import CountryCodeEnumfrom .filters import (CustomerFilter,+ CustomerTypeWhereInput,CustomerWhereInput,PermissionGroupFilter,StaffUserFilter,+ filter_customer_type_search,)from .mutations.account import (AccountAddressCreate,@@ -57,6 +63,14 @@ from .mutations.authentication import (SetPassword,VerifyToken,)+from .mutations.customer_type import (+ CustomerTypeAssignAttributes,+ CustomerTypeCreate,+ CustomerTypeDelete,+ CustomerTypeReorderAttributes,+ CustomerTypeUnassignAttributes,+ CustomerTypeUpdate,+)from .mutations.permission_group import (PermissionGroupCreate,PermissionGroupDelete,@@ -79,16 +93,25 @@ from .mutations.staff import (from .resolvers import (resolve_address,resolve_address_validation_rules,+ resolve_customer_type,+ resolve_customer_types,resolve_customers,resolve_permission_group,resolve_permission_groups,resolve_staff_users,resolve_user,)-from .sorters import PermissionGroupSortingInput, UserSortField, UserSortingInput+from .sorters import (+ CustomerTypeSortingInput,+ PermissionGroupSortingInput,+ UserSortField,+ UserSortingInput,+)from .types import (Address,AddressValidationData,+ CustomerType,+ CustomerTypeCountableConnection,Group,GroupCountableConnection,User,@@ -160,6 +183,36 @@ class AccountQueries(graphene.ObjectType):permissions=[OrderPermissions.MANAGE_ORDERS, AccountPermissions.MANAGE_USERS],doc_category=DOC_CATEGORY_USERS,)+ customer_type = PermissionsField(+ CustomerType,+ id=graphene.Argument(+ graphene.ID, description="ID of the customer type.", required=True+ ),+ description="Look up a customer type by ID." + ADDED_IN_323,+ permissions=[+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ AuthorizationFilters.AUTHENTICATED_APP,+ CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES,+ AccountPermissions.MANAGE_USERS,+ ],+ doc_category=DOC_CATEGORY_USERS,+ )+ customer_types = FilterConnectionField(+ CustomerTypeCountableConnection,+ where=CustomerTypeWhereInput(+ description="Where filtering options for customer types."+ ),+ search=graphene.String(description="Search customer types by name or slug."),+ sort_by=CustomerTypeSortingInput(description="Sort customer types."),+ description="List of the customer types." + ADDED_IN_323,+ permissions=[+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ AuthorizationFilters.AUTHENTICATED_APP,+ CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES,+ AccountPermissions.MANAGE_USERS,+ ],+ doc_category=DOC_CATEGORY_USERS,+ )permission_groups = FilterConnectionField(GroupCountableConnection,filter=PermissionGroupFilterInput(@@ -242,6 +295,23 @@ class AccountQueries(graphene.ObjectType):)return create_connection_slice(qs, info, kwargs, UserCountableConnection)+ @staticmethod+ def resolve_customer_type(_root, info: ResolveInfo, *, id):+ _, id = from_global_id_or_error(id, CustomerType)+ return resolve_customer_type(info, id)++ @staticmethod+ def resolve_customer_types(_root, info: ResolveInfo, **kwargs):+ qs = resolve_customer_types(info)+ if search := kwargs.get("search"):+ qs = filter_customer_type_search(qs, None, search)+ qs = filter_connection_queryset(+ qs, kwargs, allow_replica=info.context.allow_replica+ )+ return create_connection_slice(+ qs, info, kwargs, CustomerTypeCountableConnection+ )+@staticmethoddef resolve_permission_groups(_root, info: ResolveInfo, **kwargs):qs = resolve_permission_groups(info)@@ -328,6 +398,13 @@ class AccountMutations(graphene.ObjectType):customer_bulk_delete = CustomerBulkDelete.Field()customer_bulk_update = CustomerBulkUpdate.Field()+ customer_type_create = CustomerTypeCreate.Field()+ customer_type_update = CustomerTypeUpdate.Field()+ customer_type_delete = CustomerTypeDelete.Field()+ customer_type_assign_attributes = CustomerTypeAssignAttributes.Field()+ customer_type_unassign_attributes = CustomerTypeUnassignAttributes.Field()+ customer_type_reorder_attributes = CustomerTypeReorderAttributes.Field()+staff_create = StaffCreate.Field()staff_update = StaffUpdate.Field()staff_delete = StaffDelete.Field()diff --git a/saleor/graphql/account/sorters.py b/saleor/graphql/account/sorters.pyindex 4b727db1d4..8a60e64bd3 100644--- a/saleor/graphql/account/sorters.py+++ b/saleor/graphql/account/sorters.py@@ -35,6 +35,28 @@ class UserSortField(BaseEnum):return queryset.annotate(order_count=Count("orders__id"))+class CustomerTypeSortField(BaseEnum):+ NAME = ["name", "slug"]+ SLUG = ["slug"]++ class Meta:+ doc_category = DOC_CATEGORY_USERS++ @property+ def description(self):+ if self.name in CustomerTypeSortField.__enum__._member_names_:+ sort_name = self.name.lower().replace("_", " ")+ return f"Sort customer types by {sort_name}."+ raise ValueError(f"Unsupported enum value: {self.value}")+++class CustomerTypeSortingInput(SortInputObjectType):+ class Meta:+ doc_category = DOC_CATEGORY_USERS+ sort_enum = CustomerTypeSortField+ type_name = "customer types"++class UserSortingInput(SortInputObjectType):class Meta:doc_category = DOC_CATEGORY_USERSdiff --git a/saleor/graphql/account/tests/benchmark/test_customer_bulk_update.py b/saleor/graphql/account/tests/benchmark/test_customer_bulk_update.pynew file mode 100644index 0000000000..ecf959a73a--- /dev/null+++ b/saleor/graphql/account/tests/benchmark/test_customer_bulk_update.py@@ -0,0 +1,81 @@+import graphene+import pytest++from .....account.models import User+from ....tests.utils import get_graphql_content+from ..bulk_mutations.test_customer_bulk_update import (+ CUSTOMER_BULK_UPDATE_ATTRIBUTES_MUTATION,+)++[email protected]_queries(autouse=False)+def test_customer_bulk_update_with_attributes(+ staff_api_client,+ permission_manage_users,+ customer_users,+ customer_type_with_attributes,+ loyalty_customer_attribute,+ description_customer_attribute,+ default_customer_type,+ count_queries,+):+ # given: a row changing the type, a row keeping the user's current type,+ # and typeless users whose values validate against the default type+ default_customer_type.customer_attributes.add(loyalty_customer_attribute)+ retyped_user, typed_user, typeless_user = customer_users+ typed_user.customer_type = customer_type_with_attributes+ typed_user.save(update_fields=["customer_type"])+ typeless_user.customer_type = None+ typeless_user.save(update_fields=["customer_type"])+ typeless_users = [typeless_user] + list(+ User.objects.bulk_create(+ [+ User(email="[email protected]", is_active=True),+ User(email="[email protected]", is_active=True),+ ]+ )+ )++ loyalty_id = graphene.Node.to_global_id("Attribute", loyalty_customer_attribute.pk)+ description_id = graphene.Node.to_global_id(+ "Attribute", description_customer_attribute.pk+ )+ gold = loyalty_customer_attribute.values.get(slug="gold")+ gold_id = graphene.Node.to_global_id("AttributeValue", gold.pk)+ loyalty_input = {"id": loyalty_id, "dropdown": {"id": gold_id}}+ description_input = {"id": description_id, "plainText": "Benchmark customer."}+ customers_input = [+ {+ "id": graphene.Node.to_global_id("User", retyped_user.pk),+ "input": {+ "customerType": graphene.Node.to_global_id(+ "CustomerType", customer_type_with_attributes.pk+ ),+ "attributes": [loyalty_input, description_input],+ },+ },+ {+ "id": graphene.Node.to_global_id("User", typed_user.pk),+ "input": {"attributes": [loyalty_input, description_input]},+ },+ ] + [+ {+ "id": graphene.Node.to_global_id("User", user.pk),+ "input": {"attributes": [loyalty_input]},+ }+ for user in typeless_users+ ]+ variables = {"customers": customers_input}+ staff_api_client.user.user_permissions.add(permission_manage_users)++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_BULK_UPDATE_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerBulkUpdate"]+ assert data["count"] == len(customers_input)+ assert all(not result["errors"] for result in data["results"])diff --git a/saleor/graphql/account/tests/benchmark/test_customer_type.py b/saleor/graphql/account/tests/benchmark/test_customer_type.pynew file mode 100644index 0000000000..c2c0e5d068--- /dev/null+++ b/saleor/graphql/account/tests/benchmark/test_customer_type.py@@ -0,0 +1,134 @@+import graphene+import pytest++from .....account.models import CustomerType+from ....tests.utils import get_graphql_content++ATTRIBUTE_FRAGMENT = """+ fragment AttributeFields on Attribute {+ slug+ name+ type+ inputType+ choices(first: 10) {+ edges {+ node {+ name+ slug+ }+ }+ }+ valueRequired+ visibleInStorefront+ }+"""++[email protected]_queries(autouse=False)+def test_query_customer_type(+ customer_type,+ staff_api_client,+ loyalty_customer_attribute,+ hidden_customer_attribute,+ segment_customer_attribute,+ permission_manage_customer_types_and_attributes,+ count_queries,+):+ query = (+ ATTRIBUTE_FRAGMENT+ + """+ query CustomerType($id: ID!) {+ customerType(id: $id) {+ id+ name+ slug+ isDefault+ attributes {+ ...AttributeFields+ }+ availableAttributes(first: 10) {+ edges {+ node {+ ...AttributeFields+ }+ }+ }+ }+ }+ """+ )+ customer_type.customer_attributes.add(+ loyalty_customer_attribute, hidden_customer_attribute+ )+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[permission_manage_customer_types_and_attributes],+ )+ content = get_graphql_content(response)+ data = content["data"]["customerType"]+ assert data++[email protected]_queries(autouse=False)+def test_query_customer_types(+ customer_type,+ default_customer_type,+ staff_api_client,+ loyalty_customer_attribute,+ hidden_customer_attribute,+ segment_customer_attribute,+ permission_manage_customer_types_and_attributes,+ count_queries,+):+ query = (+ ATTRIBUTE_FRAGMENT+ + """+ query {+ customerTypes(first: 10) {+ edges {+ node {+ id+ name+ slug+ isDefault+ attributes {+ ...AttributeFields+ }+ availableAttributes(first: 10) {+ edges {+ node {+ ...AttributeFields+ }+ }+ }+ }+ }+ }+ }+ """+ )+ extra_customer_types = CustomerType.objects.bulk_create(+ [+ CustomerType(name="Wholesale", slug="wholesale"),+ CustomerType(name="Retail", slug="retail"),+ ]+ )+ customer_type.customer_attributes.add(+ loyalty_customer_attribute, hidden_customer_attribute+ )+ for extra_customer_type in extra_customer_types:+ extra_customer_type.customer_attributes.add(+ loyalty_customer_attribute, segment_customer_attribute+ )+ response = staff_api_client.post_graphql(+ query,+ {},+ permissions=[permission_manage_customer_types_and_attributes],+ )+ content = get_graphql_content(response)+ data = content["data"]["customerTypes"]+ assert datadiff --git a/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_delete.py b/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_delete.pyindex 1911c05748..bb64273c45 100644--- a/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_delete.py+++ b/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_delete.py@@ -3,6 +3,7 @@ from unittest.mock import patchimport graphenefrom .....account.models import User+from .....attribute.models import AssignedUserAttributeValue, AttributeValuefrom ....tests.utils import get_graphql_contentCUSTOMER_BULK_DELETE_MUTATION = """@@ -129,3 +130,53 @@ def test_delete_customers_by_app(app=app_api_client.app,deleted_count=len(deleted_customers),)+++def test_deletes_unique_attribute_values_and_keeps_shared_choices(+ staff_api_client,+ customer_user,+ customer_user2,+ permission_manage_users,+ description_customer_attribute,+ loyalty_customer_attribute,+):+ # given: each customer has a unique (plain text) value and a shared choice+ customers = [customer_user, customer_user2]+ unique_values = []+ choice_value = loyalty_customer_attribute.values.get(slug="gold")+ for customer in customers:+ plain_text = f"Notes about customer {customer.pk}"+ unique_value = AttributeValue.objects.create(+ attribute=description_customer_attribute,+ name=plain_text,+ slug=f"{customer.pk}_{description_customer_attribute.pk}",+ plain_text=plain_text,+ )+ unique_values.append(unique_value)+ AssignedUserAttributeValue.objects.create(user=customer, value=unique_value)+ AssignedUserAttributeValue.objects.create(user=customer, value=choice_value)+ variables = {+ "ids": [+ graphene.Node.to_global_id("User", customer.pk) for customer in customers+ ]+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_BULK_DELETE_MUTATION, variables, permissions=[permission_manage_users]+ )++ # then: the unique values are deleted with the users, the shared choice stays+ content = get_graphql_content(response)+ assert content["data"]["customerBulkDelete"]["count"] == len(customers)+ assert (+ User.objects.filter(pk__in=[customer.pk for customer in customers]).exists()+ is False+ )+ assert (+ AttributeValue.objects.filter(+ pk__in=[value.pk for value in unique_values]+ ).exists()+ is False+ )+ assert AttributeValue.objects.filter(pk=choice_value.pk).exists() is Truediff --git a/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py b/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.pyindex c68322c093..9182795441 100644--- a/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py+++ b/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py@@ -6,6 +6,7 @@ import pytestfrom .....account import modelsfrom .....account.error_codes import CustomerBulkUpdateErrorCodefrom .....account.events import CustomerEvents+from .....attribute.models import AssignedUserAttributeValuefrom .....giftcard.models import GiftCardfrom .....giftcard.search import update_gift_cards_search_vectorfrom ....core.enums import ErrorPolicyEnum@@ -1249,3 +1250,338 @@ def test_customer_update_existing_user_does_not_merge_with_existing_account(order.refresh_from_db(fields=("user", "user_email"))assert order.user == customer_user, "should have merged the gift card"assert order.user_email == existing_email, "shouldn't have changed the email"+++CUSTOMER_BULK_UPDATE_ATTRIBUTES_MUTATION = """+ mutation CustomerBulkUpdate($customers: [CustomerBulkUpdateInput!]!){+ customerBulkUpdate(customers: $customers){+ results{+ errors {+ path+ message+ code+ attributes+ }+ customer{+ id+ customerType {+ id+ }+ }+ }+ count+ }+ }+"""+++def test_customers_bulk_update_with_customer_type_and_attributes(+ staff_api_client,+ customer_users,+ permission_manage_users,+ customer_type_with_attributes,+ loyalty_customer_attribute,+ description_customer_attribute,+ default_customer_type,+):+ # given+ customer = customer_users[0]+ assert customer.customer_type != customer_type_with_attributes+ customer_type_id = graphene.Node.to_global_id(+ "CustomerType", customer_type_with_attributes.pk+ )+ value = loyalty_customer_attribute.values.get(slug="gold")+ description_text = "Bulk-updated customer."+ customers_input = [+ {+ "id": graphene.Node.to_global_id("User", customer.pk),+ "input": {+ "customerType": customer_type_id,+ "attributes": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ ),+ "dropdown": {+ "id": graphene.Node.to_global_id("AttributeValue", value.pk)+ },+ },+ {+ "id": graphene.Node.to_global_id(+ "Attribute", description_customer_attribute.pk+ ),+ "plainText": description_text,+ },+ ],+ },+ }+ ]+ variables = {"customers": customers_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_users)+ response = staff_api_client.post_graphql(+ CUSTOMER_BULK_UPDATE_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerBulkUpdate"]+ assert data["count"] == 1+ assert not data["results"][0]["errors"]+ assert data["results"][0]["customer"]["customerType"]["id"] == customer_type_id+ customer.refresh_from_db()+ assert customer.customer_type == customer_type_with_attributes+ assigned_values = AssignedUserAttributeValue.objects.filter(user=customer)+ assert assigned_values.count() == 2+ assert (+ assigned_values.get(value__attribute=loyalty_customer_attribute).value == value+ )+ description_value = assigned_values.get(+ value__attribute=description_customer_attribute+ ).value+ assert description_value.plain_text == description_text+++def test_customers_bulk_update_with_attribute_not_in_customer_type(+ staff_api_client,+ customer_users,+ permission_manage_users,+ customer_type,+ loyalty_customer_attribute,+ default_customer_type,+):+ # given: the attribute is not assigned to the customer type from the input+ customer = customer_users[0]+ assert not customer_type.customer_attributes.filter(+ pk=loyalty_customer_attribute.pk+ ).exists()+ customers_input = [+ {+ "id": graphene.Node.to_global_id("User", customer.pk),+ "input": {+ "customerType": graphene.Node.to_global_id(+ "CustomerType", customer_type.pk+ ),+ "attributes": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ ),+ "dropdown": {"value": "gold"},+ }+ ],+ },+ }+ ]+ variables = {"customers": customers_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_users)+ response = staff_api_client.post_graphql(+ CUSTOMER_BULK_UPDATE_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerBulkUpdate"]+ assert data["count"] == 0+ errors = data["results"][0]["errors"]+ assert len(errors) == 1+ assert errors[0]["path"] == "input.attributes"+ assert errors[0]["code"] == CustomerBulkUpdateErrorCode.NOT_FOUND.name+ assert not AssignedUserAttributeValue.objects.filter(user=customer).exists()+++def test_customers_bulk_update_with_required_attribute_value_not_provided(+ staff_api_client,+ customer_users,+ permission_manage_users,+ customer_type_with_attributes,+ loyalty_customer_attribute,+ default_customer_type,+):+ # given: a required attribute passed without any value+ loyalty_customer_attribute.value_required = True+ loyalty_customer_attribute.save(update_fields=["value_required"])+ customer = customer_users[0]+ attribute_id = graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ )+ customers_input = [+ {+ "id": graphene.Node.to_global_id("User", customer.pk),+ "input": {+ "customerType": graphene.Node.to_global_id(+ "CustomerType", customer_type_with_attributes.pk+ ),+ "attributes": [{"id": attribute_id}],+ },+ }+ ]+ variables = {"customers": customers_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_users)+ response = staff_api_client.post_graphql(+ CUSTOMER_BULK_UPDATE_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerBulkUpdate"]+ assert data["count"] == 0+ errors = data["results"][0]["errors"]+ assert len(errors) == 1+ assert errors[0]["path"] == "input.attributes"+ assert errors[0]["message"] == "Attribute expects a value but none were given."+ assert errors[0]["code"] == CustomerBulkUpdateErrorCode.REQUIRED.name+ assert errors[0]["attributes"] == [attribute_id]+ assert not AssignedUserAttributeValue.objects.filter(user=customer).exists()+++def test_customers_bulk_update_attributes_validated_against_default_customer_type(+ staff_api_client,+ customer_users,+ permission_manage_users,+ loyalty_customer_attribute,+ default_customer_type,+):+ # given: a typeless user and an attribute of the default customer type+ default_customer_type.customer_attributes.add(loyalty_customer_attribute)+ customer = customer_users[0]+ customer.customer_type = None+ customer.save(update_fields=["customer_type"])+ value = loyalty_customer_attribute.values.get(slug="gold")+ customers_input = [+ {+ "id": graphene.Node.to_global_id("User", customer.pk),+ "input": {+ "attributes": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ ),+ "dropdown": {+ "id": graphene.Node.to_global_id("AttributeValue", value.pk)+ },+ }+ ],+ },+ }+ ]+ variables = {"customers": customers_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_users)+ response = staff_api_client.post_graphql(+ CUSTOMER_BULK_UPDATE_ATTRIBUTES_MUTATION, variables+ )++ # then: the values are accepted and the user is left without a type+ content = get_graphql_content(response)+ data = content["data"]["customerBulkUpdate"]+ assert data["count"] == 1+ assert not data["results"][0]["errors"]+ assigned_value = AssignedUserAttributeValue.objects.get(user=customer)+ assert assigned_value.value == value+ customer.refresh_from_db()+ assert customer.customer_type_id is None+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+def test_customers_bulk_update_with_only_attributes_triggers_customer_updated(+ mocked_customer_updated,+ staff_api_client,+ customer_users,+ permission_manage_users,+ customer_type_with_attributes,+ loyalty_customer_attribute,+ default_customer_type,+):+ # given: input carrying only attributes, so no other change can+ # trigger the customer_updated webhook+ customer = customer_users[0]+ customer.customer_type = customer_type_with_attributes+ customer.save(update_fields=["customer_type"])+ value = loyalty_customer_attribute.values.get(slug="gold")+ customers_input = [+ {+ "id": graphene.Node.to_global_id("User", customer.pk),+ "input": {+ "attributes": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ ),+ "dropdown": {+ "id": graphene.Node.to_global_id("AttributeValue", value.pk)+ },+ }+ ],+ },+ }+ ]+ variables = {"customers": customers_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_users)+ response = staff_api_client.post_graphql(+ CUSTOMER_BULK_UPDATE_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerBulkUpdate"]+ assert data["count"] == 1+ assert not data["results"][0]["errors"]+ assigned_values = AssignedUserAttributeValue.objects.filter(user=customer)+ assert assigned_values.get().value == value+ mocked_customer_updated.assert_called_once_with(customer, webhooks=ANY)+++def test_customers_bulk_update_with_invalid_customer_type_id(+ staff_api_client,+ customer_users,+ permission_manage_users,+ default_customer_type,+):+ # given+ customer = customer_users[0]+ original_first_name = customer.first_name+ original_customer_type_id = customer.customer_type_id+ new_first_name = "BulkUpdatedName"+ assert original_first_name != new_first_name+ invalid_customer_type_id = graphene.Node.to_global_id("PageType", 1)+ customers_input = [+ {+ "id": graphene.Node.to_global_id("User", customer.pk),+ "input": {+ "firstName": new_first_name,+ "customerType": invalid_customer_type_id,+ },+ }+ ]+ variables = {"customers": customers_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_users)+ response = staff_api_client.post_graphql(+ CUSTOMER_BULK_UPDATE_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerBulkUpdate"]+ assert data["count"] == 0+ errors = data["results"][0]["errors"]+ assert len(errors) == 1+ assert errors[0]["path"] == "input.customerType"+ assert errors[0]["code"] == CustomerBulkUpdateErrorCode.GRAPHQL_ERROR.name+ assert errors[0]["message"] == (+ f"Invalid ID: {invalid_customer_type_id}. "+ "Expected: CustomerType, received: PageType."+ )+ customer.refresh_from_db()+ assert customer.first_name == original_first_name+ assert customer.customer_type_id == original_customer_type_iddiff --git a/saleor/graphql/account/tests/bulk_mutations/test_staff_bulk_delete.py b/saleor/graphql/account/tests/bulk_mutations/test_staff_bulk_delete.pyindex 0c2f3a2d0e..3bb03db11b 100644--- a/saleor/graphql/account/tests/bulk_mutations/test_staff_bulk_delete.py+++ b/saleor/graphql/account/tests/bulk_mutations/test_staff_bulk_delete.py@@ -5,6 +5,7 @@ from django.conf import settingsfrom .....account.error_codes import AccountErrorCodefrom .....account.models import Group, User+from .....attribute.models import AssignedUserAttributeValue, AttributeValuefrom .....permission.enums import AccountPermissions, OrderPermissionsfrom ....tests.utils import assert_no_permission, get_graphql_content@@ -387,3 +388,51 @@ def test_delete_staff_members_superuser_can_delete__out_of_scope_users(assert not User.objects.filter(id__in=[user.id for user in [staff_user1, staff_user2]]).exists()+++def test_deletes_unique_attribute_values_and_keeps_shared_choices(+ staff_api_client,+ permission_manage_staff,+ description_customer_attribute,+ loyalty_customer_attribute,+):+ # given: each staff user has a unique (plain text) value and a shared choice+ staff_users = [+ User.objects.create(email="[email protected]", is_staff=True),+ User.objects.create(email="[email protected]", is_staff=True),+ ]+ unique_values = []+ choice_value = loyalty_customer_attribute.values.get(slug="gold")+ for staff_user in staff_users:+ plain_text = f"Notes about staff member {staff_user.pk}"+ unique_value = AttributeValue.objects.create(+ attribute=description_customer_attribute,+ name=plain_text,+ slug=f"{staff_user.pk}_{description_customer_attribute.pk}",+ plain_text=plain_text,+ )+ unique_values.append(unique_value)+ AssignedUserAttributeValue.objects.create(user=staff_user, value=unique_value)+ AssignedUserAttributeValue.objects.create(user=staff_user, value=choice_value)+ variables = {+ "ids": [graphene.Node.to_global_id("User", user.pk) for user in staff_users]+ }++ # when+ response = staff_api_client.post_graphql(+ STAFF_BULK_DELETE_MUTATION, variables, permissions=[permission_manage_staff]+ )++ # then: the unique values are deleted with the users, the shared choice stays+ content = get_graphql_content(response)+ assert content["data"]["staffBulkDelete"]["count"] == len(staff_users)+ assert (+ User.objects.filter(pk__in=[user.pk for user in staff_users]).exists() is False+ )+ assert (+ AttributeValue.objects.filter(+ pk__in=[value.pk for value in unique_values]+ ).exists()+ is False+ )+ assert AttributeValue.objects.filter(pk=choice_value.pk).exists() is Truediff --git a/saleor/graphql/account/tests/mutations/account/test_account_delete.py b/saleor/graphql/account/tests/mutations/account/test_account_delete.pyindex d4b43ee254..7740cb57d1 100644--- a/saleor/graphql/account/tests/mutations/account/test_account_delete.py+++ b/saleor/graphql/account/tests/mutations/account/test_account_delete.py@@ -6,6 +6,7 @@ from django.utils import timezonefrom freezegun import freeze_timefrom ......account.models import User+from ......attribute.models import AssignedUserAttributeValue, AttributeValuefrom ......core.tokens import (account_delete_token_generator,legacy_account_delete_token_generator,@@ -225,3 +226,34 @@ def test_account_delete_webhook_event_triggered(assert not User.objects.filter(pk=user.id).exists()mocked_trigger_webhooks_async.assert_called()+++def test_deletes_unique_attribute_values_and_keeps_shared_choices(+ user_api_client,+ description_customer_attribute,+ loyalty_customer_attribute,+):+ # given: the user has a unique (plain text) value and a shared choice+ user = user_api_client.user+ plain_text = "Notes about the customer"+ unique_value = AttributeValue.objects.create(+ attribute=description_customer_attribute,+ name=plain_text,+ slug=f"{user.pk}_{description_customer_attribute.pk}",+ plain_text=plain_text,+ )+ choice_value = loyalty_customer_attribute.values.get(slug="gold")+ AssignedUserAttributeValue.objects.create(user=user, value=unique_value)+ AssignedUserAttributeValue.objects.create(user=user, value=choice_value)+ token = account_delete_token_generator.make_token(user)+ variables = {"token": token}++ # when+ response = user_api_client.post_graphql(ACCOUNT_DELETE_MUTATION, variables)++ # then: the unique value is deleted with the user, the shared choice stays+ content = get_graphql_content(response)+ assert content["data"]["accountDelete"]["errors"] == []+ assert User.objects.filter(pk=user.pk).exists() is False+ assert AttributeValue.objects.filter(pk=unique_value.pk).exists() is False+ assert AttributeValue.objects.filter(pk=choice_value.pk).exists() is Truediff --git a/saleor/graphql/account/tests/mutations/account/test_account_register.py b/saleor/graphql/account/tests/mutations/account/test_account_register.pyindex 1c6ffa8b87..38cab91db0 100644--- a/saleor/graphql/account/tests/mutations/account/test_account_register.py+++ b/saleor/graphql/account/tests/mutations/account/test_account_register.py@@ -584,3 +584,28 @@ def test_validates_password_length(],"user": None,}+++@override_settings(ALLOWED_CLIENT_HOSTS=["localhost"])+def test_register_assigns_default_customer_type(+ api_client, channel_PLN, default_customer_type+):+ # given+ email = "[email protected]"+ variables = {+ "input": {+ "email": email,+ "password": "Password",+ "redirectUrl": "http://localhost:3000",+ "channel": channel_PLN.slug,+ }+ }++ # when+ response = api_client.post_graphql(ACCOUNT_REGISTER_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["accountRegister"]["errors"]+ new_user = User.objects.get(email=email)+ assert new_user.customer_type == default_customer_typediff --git a/saleor/graphql/account/tests/mutations/customer_type/__init__.py b/saleor/graphql/account/tests/mutations/customer_type/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_assign_attributes.py b/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_assign_attributes.pynew file mode 100644index 0000000000..8851715191--- /dev/null+++ b/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_assign_attributes.py@@ -0,0 +1,383 @@+from unittest.mock import patch++import graphene++from ......account.error_codes import CustomerTypeAssignAttributesErrorCode+from ......attribute.models import AttributeCustomerType+from .....tests.utils import assert_no_permission, get_graphql_content++CUSTOMER_TYPE_ASSIGN_ATTRIBUTES_MUTATION = """+ mutation CustomerTypeAssignAttributes(+ $customerTypeId: ID!, $attributeIds: [ID!]!+ ) {+ customerTypeAssignAttributes(+ customerTypeId: $customerTypeId, attributeIds: $attributeIds+ ) {+ customerType {+ id+ attributes {+ id+ slug+ }+ }+ errors {+ field+ code+ message+ attributes+ }+ }+ }+"""+++def test_assign_by_staff(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ attribute_id = graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ )+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [attribute_id],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_ASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeAssignAttributes"]+ assert data["errors"] == []+ assert [attr["slug"] for attr in data["customerType"]["attributes"]] == [+ loyalty_customer_attribute.slug+ ]+ assert customer_type.customer_attributes.get() == loyalty_customer_attribute+++@patch("saleor.plugins.manager.PluginsManager.customer_type_updated")+def test_assign_triggers_customer_type_updated(+ mocked_customer_type_updated,+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [+ graphene.Node.to_global_id("Attribute", loyalty_customer_attribute.pk)+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_ASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["customerTypeAssignAttributes"]["errors"] == []+ mocked_customer_type_updated.assert_called_once_with(customer_type)+++def test_assign_by_app(+ app_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+):+ # given+ app_api_client.app.permissions.add(permission_manage_customer_types_and_attributes)+ attribute_id = graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ )+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [attribute_id],+ }++ # when+ response = app_api_client.post_graphql(+ CUSTOMER_TYPE_ASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeAssignAttributes"]+ assert data["errors"] == []+ assert customer_type.customer_attributes.get() == loyalty_customer_attribute+++def test_assign_by_staff_no_permission(+ staff_api_client, customer_type, loyalty_customer_attribute+):+ # given+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [+ graphene.Node.to_global_id("Attribute", loyalty_customer_attribute.pk)+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_ASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ assert_no_permission(response)+ assert customer_type.customer_attributes.count() == 0+++def test_assign_not_customer_attribute(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ size_page_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ attribute_id = graphene.Node.to_global_id("Attribute", size_page_attribute.pk)+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [attribute_id],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_ASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeAssignAttributes"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "attributeIds"+ assert error["code"] == CustomerTypeAssignAttributesErrorCode.INVALID.name+ assert error["message"] == "Only customer attributes can be assigned."+ assert error["attributes"] == [attribute_id]+ assert customer_type.customer_attributes.count() == 0+++def test_assign_attribute_already_assigned(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ attribute_id = graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ )+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [attribute_id],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_ASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeAssignAttributes"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "attributeIds"+ assert (+ error["code"]+ == CustomerTypeAssignAttributesErrorCode.ATTRIBUTE_ALREADY_ASSIGNED.name+ )+ assert error["attributes"] == [attribute_id]+++def test_assign_invalid_object_type_as_customer_type_id(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {+ "customerTypeId": graphene.Node.to_global_id("Order", customer_type.pk),+ "attributeIds": [+ graphene.Node.to_global_id("Attribute", loyalty_customer_attribute.pk)+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_ASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeAssignAttributes"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "customerTypeId"+ assert error["code"] == CustomerTypeAssignAttributesErrorCode.GRAPHQL_ERROR.name+++def test_assign_more_than_limit(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ attribute_ids = [+ graphene.Node.to_global_id("Attribute", index) for index in range(101)+ ]+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": attribute_ids,+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_ASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeAssignAttributes"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "attributeIds"+ assert error["code"] == CustomerTypeAssignAttributesErrorCode.INVALID.name+ assert (+ error["message"]+ == "Cannot assign more than 100 attributes in a single mutation."+ )+++def test_assign_sets_sort_order(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+ segment_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [+ graphene.Node.to_global_id("Attribute", loyalty_customer_attribute.pk),+ graphene.Node.to_global_id("Attribute", segment_customer_attribute.pk),+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_ASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeAssignAttributes"]+ assert data["errors"] == []+ assignments = AttributeCustomerType.objects.filter(customer_type=customer_type)+ assert assignments.count() == 2+ assert {assignment.attribute_id for assignment in assignments} == {+ loyalty_customer_attribute.pk,+ segment_customer_attribute.pk,+ }+++def test_assign_nonexistent_attribute(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ attribute_id = graphene.Node.to_global_id("Attribute", -1)+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [attribute_id],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_ASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeAssignAttributes"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "attributeIds"+ assert error["code"] == CustomerTypeAssignAttributesErrorCode.NOT_FOUND.name+ assert error["message"] == "Some of the attributes do not exist."+ assert error["attributes"] == [attribute_id]+ assert customer_type.customer_attributes.count() == 0+++def test_assign_nonexistent_attribute_does_not_assign_valid_ones(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ valid_attribute_id = graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ )+ missing_attribute_id = graphene.Node.to_global_id("Attribute", -1)+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [valid_attribute_id, missing_attribute_id],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_ASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeAssignAttributes"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "attributeIds"+ assert error["code"] == CustomerTypeAssignAttributesErrorCode.NOT_FOUND.name+ assert error["message"] == "Some of the attributes do not exist."+ assert error["attributes"] == [missing_attribute_id]+ assert customer_type.customer_attributes.count() == 0diff --git a/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_create.py b/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_create.pynew file mode 100644index 0000000000..9845b2b7e5--- /dev/null+++ b/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_create.py@@ -0,0 +1,221 @@+from unittest.mock import patch++from ......account.error_codes import CustomerTypeCreateErrorCode+from ......account.models import CustomerType+from .....tests.utils import assert_no_permission, get_graphql_content++CUSTOMER_TYPE_CREATE_MUTATION = """+ mutation CustomerTypeCreate($input: CustomerTypeCreateInput!) {+ customerTypeCreate(input: $input) {+ customerType {+ id+ name+ slug+ isDefault+ }+ errors {+ field+ code+ message+ }+ }+ }+"""+++def test_create_by_staff_with_permission(+ staff_api_client, permission_manage_customer_types_and_attributes+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ name = "Wholesale"+ variables = {"input": {"name": name}}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeCreate"]+ assert data["errors"] == []++ customer_type = CustomerType.objects.get(slug="wholesale")+ assert data["customerType"]["name"] == customer_type.name+ assert data["customerType"]["slug"] == customer_type.slug+ assert data["customerType"]["isDefault"] is False+ assert customer_type.name == name+ assert customer_type.is_default is False+++def test_create_with_explicit_slug(+ staff_api_client, permission_manage_customer_types_and_attributes+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ name = "Wholesale"+ slug = "custom-slug"+ variables = {"input": {"name": name, "slug": slug}}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeCreate"]+ assert data["errors"] == []++ customer_type = CustomerType.objects.get(slug=slug)+ assert customer_type.name == name+ assert data["customerType"]["slug"] == slug+++def test_create_as_default_transfers_default_flag(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ default_customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {"input": {"name": "Wholesale", "isDefault": True}}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeCreate"]+ assert data["errors"] == []+ assert data["customerType"]["isDefault"] is True++ default_customer_type.refresh_from_db()+ assert default_customer_type.is_default is False++ customer_type = CustomerType.objects.get(slug="wholesale")+ assert customer_type.is_default is True+ assert CustomerType.objects.filter(is_default=True).count() == 1+++@patch(+ "saleor.graphql.account.mutations.customer_type.customer_type_create"+ ".customer_type_qs_select_for_update"+)+def test_create_as_default_clears_default_row_invisible_to_locking_statement(+ mocked_lock_qs,+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ default_customer_type,+):+ # given: the locking statement does not return the default row - as+ # happens when a concurrent transaction inserted it while this one waited+ # for the lock (a blocked SELECT FOR UPDATE cannot see newly inserted+ # rows), the default-clearing update must still find and clear it+ mocked_lock_qs.return_value = CustomerType.objects.exclude(+ pk=default_customer_type.pk+ )+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {"input": {"name": "Wholesale", "isDefault": True}}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeCreate"]+ assert data["errors"] == []+ assert data["customerType"]["isDefault"] is True++ default_customer_type.refresh_from_db()+ assert default_customer_type.is_default is False+ customer_type = CustomerType.objects.get(slug="wholesale")+ assert customer_type.is_default is True+ assert CustomerType.objects.filter(is_default=True).count() == 1+++def test_create_with_duplicated_slug(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {"input": {"name": "Another", "slug": customer_type.slug}}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeCreate"]+ assert data["customerType"] is None+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "slug"+ assert error["code"] == CustomerTypeCreateErrorCode.UNIQUE.name+++def test_create_without_name(+ staff_api_client, permission_manage_customer_types_and_attributes+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {"input": {}}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeCreate"]+ assert data["customerType"] is None+ assert len(data["errors"]) == 2+ errors_by_field = {error["field"]: error for error in data["errors"]}+ assert errors_by_field.keys() == {"name", "slug"}+ assert errors_by_field["name"]["code"] == CustomerTypeCreateErrorCode.REQUIRED.name+ assert errors_by_field["slug"]["code"] == CustomerTypeCreateErrorCode.REQUIRED.name+++def test_create_by_staff_without_permission(staff_api_client):+ # given+ variables = {"input": {"name": "Wholesale"}}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_CREATE_MUTATION, variables)++ # then+ assert_no_permission(response)+ assert not CustomerType.objects.filter(slug="wholesale").exists()+++@patch("saleor.plugins.manager.PluginsManager.customer_type_created")+def test_create_triggers_webhook(+ mocked_customer_type_created,+ staff_api_client,+ permission_manage_customer_types_and_attributes,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {"input": {"name": "Wholesale"}}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["customerTypeCreate"]["errors"] == []++ customer_type = CustomerType.objects.get(slug="wholesale")+ mocked_customer_type_created.assert_called_once_with(customer_type)diff --git a/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_delete.py b/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_delete.pynew file mode 100644index 0000000000..52c247694b--- /dev/null+++ b/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_delete.py@@ -0,0 +1,134 @@+from unittest.mock import patch++import graphene++from ......account.error_codes import CustomerTypeDeleteErrorCode+from ......account.models import CustomerType+from .....tests.utils import assert_no_permission, get_graphql_content++CUSTOMER_TYPE_DELETE_MUTATION = """+ mutation CustomerTypeDelete($id: ID!) {+ customerTypeDelete(id: $id) {+ customerType {+ id+ name+ slug+ }+ errors {+ field+ code+ message+ }+ }+ }+"""+++def test_delete_by_staff_with_permission(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_DELETE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeDelete"]+ assert data["errors"] == []+ assert data["customerType"]["slug"] == customer_type.slug+ assert not CustomerType.objects.filter(pk=customer_type.pk).exists()+++def test_delete_reassigns_users_to_default(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ default_customer_type,+ customer_user,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ customer_user.customer_type = customer_type+ customer_user.save(update_fields=["customer_type"])+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_DELETE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeDelete"]+ assert data["errors"] == []+ assert not CustomerType.objects.filter(pk=customer_type.pk).exists()++ customer_user.refresh_from_db()+ assert customer_user.customer_type == default_customer_type+++def test_delete_default_type_is_forbidden(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ default_customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {+ "id": graphene.Node.to_global_id("CustomerType", default_customer_type.pk)+ }++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_DELETE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeDelete"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "id"+ assert error["code"] == CustomerTypeDeleteErrorCode.CANNOT_DELETE_DEFAULT.name+ assert CustomerType.objects.filter(pk=default_customer_type.pk).exists()+++def test_delete_by_staff_without_permission(staff_api_client, customer_type):+ # given+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_DELETE_MUTATION, variables)++ # then+ assert_no_permission(response)+ assert CustomerType.objects.filter(pk=customer_type.pk).exists()+++@patch("saleor.plugins.manager.PluginsManager.customer_type_deleted")+def test_delete_triggers_webhook(+ mocked_customer_type_deleted,+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_DELETE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["customerTypeDelete"]["errors"] == []+ mocked_customer_type_deleted.assert_called_once_with(customer_type)diff --git a/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_reorder_attributes.py b/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_reorder_attributes.pynew file mode 100644index 0000000000..cdeb560457--- /dev/null+++ b/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_reorder_attributes.py@@ -0,0 +1,229 @@+from unittest.mock import patch++import graphene++from ......account.error_codes import CustomerTypeReorderAttributesErrorCode+from ......attribute.models import AttributeCustomerType+from .....tests.utils import assert_no_permission, get_graphql_content++CUSTOMER_TYPE_REORDER_ATTRIBUTES_MUTATION = """+ mutation CustomerTypeReorderAttributes(+ $customerTypeId: ID!, $moves: [ReorderInput!]!+ ) {+ customerTypeReorderAttributes(+ customerTypeId: $customerTypeId, moves: $moves+ ) {+ customerType {+ id+ attributes {+ slug+ }+ }+ errors {+ field+ code+ message+ }+ }+ }+"""+++def test_reorder_by_staff(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+ segment_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ # Two separate calls to make the insertion order (and thus the initial+ # NULL-sort_order ordering, which falls back to pk) deterministic -+ # a single add() iterates an unordered set of target ids internally.+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ customer_type.customer_attributes.add(segment_customer_attribute)+ assigned_slugs = [+ assignment.attribute.slug+ for assignment in AttributeCustomerType.objects.filter(+ customer_type=customer_type+ )+ ]+ assert assigned_slugs == [+ loyalty_customer_attribute.slug,+ segment_customer_attribute.slug,+ ]+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "moves": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ ),+ "sortOrder": 1,+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_REORDER_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeReorderAttributes"]+ assert data["errors"] == []+ assert [attr["slug"] for attr in data["customerType"]["attributes"]] == [+ segment_customer_attribute.slug,+ loyalty_customer_attribute.slug,+ ]+++@patch("saleor.plugins.manager.PluginsManager.customer_type_updated")+def test_reorder_triggers_customer_type_updated(+ mocked_customer_type_updated,+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+ segment_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ customer_type.customer_attributes.add(segment_customer_attribute)+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "moves": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ ),+ "sortOrder": 1,+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_REORDER_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["customerTypeReorderAttributes"]["errors"] == []+ mocked_customer_type_updated.assert_called_once_with(customer_type)+++def test_reorder_by_staff_no_permission(+ staff_api_client,+ customer_type,+ loyalty_customer_attribute,+):+ # given+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "moves": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ ),+ "sortOrder": 1,+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_REORDER_ATTRIBUTES_MUTATION, variables+ )++ # then+ assert_no_permission(response)+ assignment = AttributeCustomerType.objects.get(customer_type=customer_type)+ assert assignment.sort_order is None+++def test_reorder_invalid_customer_type(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ loyalty_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ customer_type_id = graphene.Node.to_global_id("CustomerType", -1)+ variables = {+ "customerTypeId": customer_type_id,+ "moves": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ ),+ "sortOrder": 1,+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_REORDER_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeReorderAttributes"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "customerTypeId"+ assert error["code"] == CustomerTypeReorderAttributesErrorCode.NOT_FOUND.name+ assert (+ error["message"] == f"Couldn't resolve to a customer type: {customer_type_id}"+ )+++def test_reorder_invalid_attribute_id(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+ segment_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ # segment_customer_attribute is not assigned to the customer type+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "moves": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", segment_customer_attribute.pk+ ),+ "sortOrder": 1,+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_REORDER_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeReorderAttributes"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "moves"+ assert error["code"] == CustomerTypeReorderAttributesErrorCode.NOT_FOUND.name+ assert error["message"] == "Couldn't resolve to an attribute."diff --git a/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_unassign_attributes.py b/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_unassign_attributes.pynew file mode 100644index 0000000000..e80af371d7--- /dev/null+++ b/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_unassign_attributes.py@@ -0,0 +1,249 @@+from unittest.mock import patch++import graphene++from ......account.error_codes import CustomerTypeUnassignAttributesErrorCode+from .....tests.utils import assert_no_permission, get_graphql_content++CUSTOMER_TYPE_UNASSIGN_ATTRIBUTES_MUTATION = """+ mutation CustomerTypeUnassignAttributes(+ $customerTypeId: ID!, $attributeIds: [ID!]!+ ) {+ customerTypeUnassignAttributes(+ customerTypeId: $customerTypeId, attributeIds: $attributeIds+ ) {+ customerType {+ id+ attributes {+ slug+ }+ }+ errors {+ field+ code+ message+ }+ }+ }+"""+++def test_unassign_by_staff(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+ segment_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ customer_type.customer_attributes.add(+ loyalty_customer_attribute, segment_customer_attribute+ )+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [+ graphene.Node.to_global_id("Attribute", loyalty_customer_attribute.pk)+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_UNASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeUnassignAttributes"]+ assert data["errors"] == []+ assert [attr["slug"] for attr in data["customerType"]["attributes"]] == [+ segment_customer_attribute.slug+ ]+ assert customer_type.customer_attributes.get() == segment_customer_attribute+++@patch("saleor.plugins.manager.PluginsManager.customer_type_updated")+def test_unassign_triggers_customer_type_updated(+ mocked_customer_type_updated,+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [+ graphene.Node.to_global_id("Attribute", loyalty_customer_attribute.pk)+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_UNASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["customerTypeUnassignAttributes"]["errors"] == []+ mocked_customer_type_updated.assert_called_once_with(customer_type)+++def test_unassign_by_app(+ app_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+):+ # given+ app_api_client.app.permissions.add(permission_manage_customer_types_and_attributes)+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [+ graphene.Node.to_global_id("Attribute", loyalty_customer_attribute.pk)+ ],+ }++ # when+ response = app_api_client.post_graphql(+ CUSTOMER_TYPE_UNASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeUnassignAttributes"]+ assert data["errors"] == []+ assert customer_type.customer_attributes.count() == 0+++def test_unassign_by_staff_no_permission(+ staff_api_client, customer_type, loyalty_customer_attribute+):+ # given+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [+ graphene.Node.to_global_id("Attribute", loyalty_customer_attribute.pk)+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_UNASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ assert_no_permission(response)+ assert customer_type.customer_attributes.get() == loyalty_customer_attribute+++def test_unassign_keeps_attribute_values(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ values_count = loyalty_customer_attribute.values.count()+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [+ graphene.Node.to_global_id("Attribute", loyalty_customer_attribute.pk)+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_UNASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeUnassignAttributes"]+ assert data["errors"] == []+ loyalty_customer_attribute.refresh_from_db()+ assert loyalty_customer_attribute.values.count() == values_count+++def test_unassign_more_than_limit(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ attribute_ids = [+ graphene.Node.to_global_id("Attribute", loyalty_customer_attribute.pk)+ ] + [graphene.Node.to_global_id("Attribute", index) for index in range(100)]+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": attribute_ids,+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_UNASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeUnassignAttributes"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "attributeIds"+ assert error["code"] == CustomerTypeUnassignAttributesErrorCode.INVALID.name+ assert (+ error["message"]+ == "Cannot unassign more than 100 attributes in a single mutation."+ )+ assert customer_type.customer_attributes.get() == loyalty_customer_attribute+++def test_unassign_ignores_nonexistent_and_unassigned_attributes(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+ segment_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [+ graphene.Node.to_global_id("Attribute", loyalty_customer_attribute.pk),+ graphene.Node.to_global_id("Attribute", segment_customer_attribute.pk),+ graphene.Node.to_global_id("Attribute", -1),+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_UNASSIGN_ATTRIBUTES_MUTATION, variables+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeUnassignAttributes"]+ assert data["errors"] == []+ assert data["customerType"]["attributes"] == []+ assert customer_type.customer_attributes.exists() is Falsediff --git a/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_update.py b/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_update.pynew file mode 100644index 0000000000..18628a5eb5--- /dev/null+++ b/saleor/graphql/account/tests/mutations/customer_type/test_customer_type_update.py@@ -0,0 +1,296 @@+from unittest.mock import patch++import graphene++from ......account.error_codes import CustomerTypeUpdateErrorCode+from ......account.models import CustomerType+from .....tests.utils import assert_no_permission, get_graphql_content++CUSTOMER_TYPE_UPDATE_MUTATION = """+ mutation CustomerTypeUpdate($id: ID!, $input: CustomerTypeUpdateInput!) {+ customerTypeUpdate(id: $id, input: $input) {+ customerType {+ id+ name+ slug+ isDefault+ }+ errors {+ field+ code+ message+ }+ }+ }+"""+++def test_update_name_and_slug(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ new_name = "Business"+ new_slug = "business"+ variables = {+ "id": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "input": {"name": new_name, "slug": new_slug},+ }++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_UPDATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeUpdate"]+ assert data["errors"] == []++ customer_type.refresh_from_db()+ assert customer_type.name == new_name+ assert customer_type.slug == new_slug+ assert data["customerType"]["name"] == customer_type.name+ assert data["customerType"]["slug"] == customer_type.slug+++def test_update_name_keeps_slug(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ old_slug = customer_type.slug+ variables = {+ "id": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "input": {"name": "Renamed"},+ }++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_UPDATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeUpdate"]+ assert data["errors"] == []++ customer_type.refresh_from_db()+ assert customer_type.name == "Renamed"+ assert customer_type.slug == old_slug+++def test_update_default_type_is_renamable(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ default_customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ new_name = "Standard"+ variables = {+ "id": graphene.Node.to_global_id("CustomerType", default_customer_type.pk),+ "input": {"name": new_name},+ }++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_UPDATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeUpdate"]+ assert data["errors"] == []++ default_customer_type.refresh_from_db()+ assert default_customer_type.name == new_name+ assert default_customer_type.is_default is True+++def test_update_is_default_transfers_default_flag(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ default_customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {+ "id": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "input": {"isDefault": True},+ }++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_UPDATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeUpdate"]+ assert data["errors"] == []+ assert data["customerType"]["isDefault"] is True++ customer_type.refresh_from_db()+ default_customer_type.refresh_from_db()+ assert customer_type.is_default is True+ assert default_customer_type.is_default is False+ assert CustomerType.objects.filter(is_default=True).count() == 1+++def test_update_is_default_true_on_current_default_is_noop(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ default_customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {+ "id": graphene.Node.to_global_id("CustomerType", default_customer_type.pk),+ "input": {"isDefault": True},+ }++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_UPDATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeUpdate"]+ assert data["errors"] == []++ default_customer_type.refresh_from_db()+ assert default_customer_type.is_default is True+ assert CustomerType.objects.filter(is_default=True).count() == 1+++def test_update_cannot_unset_default(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ default_customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {+ "id": graphene.Node.to_global_id("CustomerType", default_customer_type.pk),+ "input": {"isDefault": False},+ }++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_UPDATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeUpdate"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "isDefault"+ assert error["code"] == CustomerTypeUpdateErrorCode.CANNOT_UNSET_DEFAULT.name++ default_customer_type.refresh_from_db()+ assert default_customer_type.is_default is True+++def test_update_is_default_false_on_non_default_is_noop(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ default_customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {+ "id": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "input": {"isDefault": False},+ }++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_UPDATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeUpdate"]+ assert data["errors"] == []++ customer_type.refresh_from_db()+ default_customer_type.refresh_from_db()+ assert customer_type.is_default is False+ assert default_customer_type.is_default is True+++def test_update_with_duplicated_slug(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ default_customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {+ "id": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "input": {"slug": default_customer_type.slug},+ }++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_UPDATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerTypeUpdate"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "slug"+ assert error["code"] == CustomerTypeUpdateErrorCode.UNIQUE.name+++def test_update_by_staff_without_permission(staff_api_client, customer_type):+ # given+ variables = {+ "id": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "input": {"name": "Renamed"},+ }++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_UPDATE_MUTATION, variables)++ # then+ assert_no_permission(response)+++@patch("saleor.plugins.manager.PluginsManager.customer_type_updated")+def test_update_triggers_webhook(+ mocked_customer_type_updated,+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {+ "id": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "input": {"name": "Renamed"},+ }++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_UPDATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["customerTypeUpdate"]["errors"] == []++ customer_type.refresh_from_db()+ mocked_customer_type_updated.assert_called_once_with(customer_type)diff --git a/saleor/graphql/account/tests/mutations/staff/test_customer_create.py b/saleor/graphql/account/tests/mutations/staff/test_customer_create.pyindex 9007fc4dc0..d20fada303 100644--- a/saleor/graphql/account/tests/mutations/staff/test_customer_create.py+++ b/saleor/graphql/account/tests/mutations/staff/test_customer_create.py@@ -1,10 +1,13 @@from unittest.mock import ANY, patchfrom urllib.parse import urlencode+import graphene+from ......account import events as account_eventsfrom ......account.error_codes import AccountErrorCodefrom ......account.models import Address, Userfrom ......account.notifications import get_default_user_payload+from ......attribute.models import AssignedUserAttributeValuefrom ......core.notify import NotifyEventTypefrom ......core.tests.utils import get_site_context_payloadfrom ......core.utils.url import prepare_url@@ -596,3 +599,277 @@ def test_customer_create_race_condition(# make sure that addresses were not saved.assert not Address.objects.exclude(id=address.id).exists()+++def test_create_assigns_default_customer_type(+ staff_api_client, permission_manage_users, default_customer_type+):+ # given+ email = "[email protected]"+ variables = {"email": email}++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_CREATE_MUTATION, variables, permissions=[permission_manage_users]+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["customerCreate"]["errors"]+ new_user = User.objects.get(email=email)+ assert new_user.customer_type == default_customer_type+++CUSTOMER_CREATE_WITH_ATTRIBUTES_MUTATION = """+ mutation CreateCustomer(+ $email: String, $customerType: ID, $attributes: [AttributeValueInput!]+ ) {+ customerCreate(input: {+ email: $email,+ customerType: $customerType,+ attributes: $attributes+ }) {+ errors {+ field+ code+ message+ attributes+ }+ user {+ id+ customerType {+ id+ }+ }+ }+ }+"""+++def test_create_with_customer_type_and_attributes(+ staff_api_client,+ permission_manage_users,+ customer_type_with_attributes,+ loyalty_customer_attribute,+ description_customer_attribute,+ default_customer_type,+):+ # given+ email = "[email protected]"+ value = loyalty_customer_attribute.values.get(slug="gold")+ description_text = "A very important customer."+ variables = {+ "email": email,+ "customerType": graphene.Node.to_global_id(+ "CustomerType", customer_type_with_attributes.pk+ ),+ "attributes": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ ),+ "dropdown": {+ "id": graphene.Node.to_global_id("AttributeValue", value.pk)+ },+ },+ {+ "id": graphene.Node.to_global_id(+ "Attribute", description_customer_attribute.pk+ ),+ "plainText": description_text,+ },+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_CREATE_WITH_ATTRIBUTES_MUTATION,+ variables,+ permissions=[permission_manage_users],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerCreate"]+ assert not data["errors"]+ new_user = User.objects.get(email=email)+ assert new_user.customer_type == customer_type_with_attributes+ assert data["user"]["customerType"]["id"] == graphene.Node.to_global_id(+ "CustomerType", customer_type_with_attributes.pk+ )+ assigned_values = AssignedUserAttributeValue.objects.filter(user=new_user)+ assert assigned_values.count() == 2+ assert (+ assigned_values.get(value__attribute=loyalty_customer_attribute).value == value+ )+ description_value = assigned_values.get(+ value__attribute=description_customer_attribute+ ).value+ assert description_value.plain_text == description_text+++def test_create_with_attributes_of_default_customer_type(+ staff_api_client,+ permission_manage_users,+ default_customer_type,+ loyalty_customer_attribute,+):+ # given+ default_customer_type.customer_attributes.add(loyalty_customer_attribute)+ email = "[email protected]"+ value = loyalty_customer_attribute.values.get(slug="silver")+ variables = {+ "email": email,+ "attributes": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ ),+ "dropdown": {+ "id": graphene.Node.to_global_id("AttributeValue", value.pk)+ },+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_CREATE_WITH_ATTRIBUTES_MUTATION,+ variables,+ permissions=[permission_manage_users],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerCreate"]+ assert not data["errors"]+ new_user = User.objects.get(email=email)+ assert new_user.customer_type == default_customer_type+ assigned_values = AssignedUserAttributeValue.objects.filter(user=new_user)+ assert assigned_values.count() == 1+ assert assigned_values.first().value == value+++def test_create_with_attribute_not_in_customer_type(+ staff_api_client,+ permission_manage_users,+ customer_type,+ loyalty_customer_attribute,+ default_customer_type,+):+ # given: the attribute is not assigned to the given customer type+ assert not customer_type.customer_attributes.filter(+ pk=loyalty_customer_attribute.pk+ ).exists()+ email = "[email protected]"+ attribute_id = graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ )+ variables = {+ "email": email,+ "customerType": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributes": [{"id": attribute_id, "dropdown": {"value": "gold"}}],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_CREATE_WITH_ATTRIBUTES_MUTATION,+ variables,+ permissions=[permission_manage_users],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerCreate"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "attributes"+ assert error["code"] == AccountErrorCode.NOT_FOUND.name+ assert f"Could not resolve attributes: ID: {attribute_id}." == error["message"]+ assert not User.objects.filter(email=email).exists()+++def test_create_with_missing_required_attribute(+ staff_api_client,+ permission_manage_users,+ customer_type_with_attributes,+ loyalty_customer_attribute,+ description_customer_attribute,+ segment_customer_attribute,+ default_customer_type,+):+ # given+ loyalty_customer_attribute.value_required = True+ loyalty_customer_attribute.save(update_fields=["value_required"])+ customer_type_with_attributes.customer_attributes.add(segment_customer_attribute)++ email = "[email protected]"+ variables = {+ "email": email,+ "customerType": graphene.Node.to_global_id(+ "CustomerType", customer_type_with_attributes.pk+ ),+ "attributes": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", segment_customer_attribute.pk+ ),+ "dropdown": {"value": "Retail"},+ },+ {+ "id": graphene.Node.to_global_id(+ "Attribute", description_customer_attribute.pk+ ),+ "plainText": "Provided, but the required attribute is not.",+ },+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_CREATE_WITH_ATTRIBUTES_MUTATION,+ variables,+ permissions=[permission_manage_users],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerCreate"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "attributes"+ assert error["code"] == AccountErrorCode.REQUIRED.name+ assert error["attributes"] == [+ graphene.Node.to_global_id("Attribute", loyalty_customer_attribute.pk)+ ]+ assert not User.objects.filter(email=email).exists()+++def test_create_with_invalid_customer_type_id(+ staff_api_client,+ permission_manage_users,+ default_customer_type,+):+ # given: an ID of a different type passed as customerType+ email = "[email protected]"+ variables = {+ "email": email,+ "customerType": graphene.Node.to_global_id("PageType", 1),+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_CREATE_WITH_ATTRIBUTES_MUTATION,+ variables,+ permissions=[permission_manage_users],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerCreate"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "customerType"+ assert error["code"] == AccountErrorCode.GRAPHQL_ERROR.name+ assert not User.objects.filter(email=email).exists()diff --git a/saleor/graphql/account/tests/mutations/staff/test_customer_delete.py b/saleor/graphql/account/tests/mutations/staff/test_customer_delete.pyindex fdbb3d39cb..49ac180650 100644--- a/saleor/graphql/account/tests/mutations/staff/test_customer_delete.py+++ b/saleor/graphql/account/tests/mutations/staff/test_customer_delete.py@@ -7,6 +7,9 @@ from django.core.exceptions import ValidationErrorfrom django.utils.functional import SimpleLazyObjectfrom freezegun import freeze_time+from ......account.models import User+from ......attribute.models import AssignedUserAttributeValue, AttributeValue+from ......page.models import Pagefrom ......webhook.event_types import WebhookEventAsyncTypefrom .....tests.utils import get_graphql_contentfrom ....mutations.staff import CustomerDelete@@ -215,3 +218,142 @@ def test_delete_customer_by_external_reference_not_existing(# thenerrors = content["data"]["customerDelete"]["errors"]assert errors[0]["message"] == f"Couldn't resolve to a node: {ext_ref}"+++def test_deletes_unique_attribute_values_and_keeps_shared_choices(+ staff_api_client,+ customer_user,+ customer_user2,+ permission_manage_users,+ description_customer_attribute,+ loyalty_customer_attribute,+):+ # given: the customer has a unique (plain text) value and a shared choice,+ # and another customer holds their own unique value on the same attribute+ plain_text = "Notes about the customer"+ unique_value = AttributeValue.objects.create(+ attribute=description_customer_attribute,+ name=plain_text,+ slug=f"{customer_user.pk}_{description_customer_attribute.pk}",+ plain_text=plain_text,+ )+ other_user_plain_text = "Notes about the other customer"+ other_user_value = AttributeValue.objects.create(+ attribute=description_customer_attribute,+ name=other_user_plain_text,+ slug=f"{customer_user2.pk}_{description_customer_attribute.pk}",+ plain_text=other_user_plain_text,+ )+ choice_value = loyalty_customer_attribute.values.get(slug="gold")+ AssignedUserAttributeValue.objects.create(user=customer_user, value=unique_value)+ AssignedUserAttributeValue.objects.create(user=customer_user, value=choice_value)+ AssignedUserAttributeValue.objects.create(+ user=customer_user2, value=other_user_value+ )+ variables = {"id": graphene.Node.to_global_id("User", customer_user.pk)}++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_DELETE_MUTATION, variables, permissions=[permission_manage_users]+ )++ # then: the unique value is deleted with the user, the shared choice and+ # the other customer's value stay+ content = get_graphql_content(response)+ assert content["data"]["customerDelete"]["errors"] == []+ assert User.objects.filter(pk=customer_user.pk).exists() is False+ assert AttributeValue.objects.filter(pk=unique_value.pk).exists() is False+ assert AttributeValue.objects.filter(pk=choice_value.pk).exists() is True+ assert AttributeValue.objects.filter(pk=other_user_value.pk).exists() is True+ assert AssignedUserAttributeValue.objects.get(user=customer_user2).value == (+ other_user_value+ )+++def test_deletes_single_reference_attribute_values(+ staff_api_client,+ customer_user,+ permission_manage_users,+ customer_type_page_single_reference_attribute,+ page,+):+ # given: the customer holds a per-user single-reference value+ reference_value = AttributeValue.objects.create(+ attribute=customer_type_page_single_reference_attribute,+ name=page.title,+ slug=f"{customer_user.pk}_{page.pk}",+ reference_page=page,+ )+ AssignedUserAttributeValue.objects.create(user=customer_user, value=reference_value)+ variables = {"id": graphene.Node.to_global_id("User", customer_user.pk)}++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_DELETE_MUTATION, variables, permissions=[permission_manage_users]+ )++ # then: the per-user value is deleted with the user, the referenced page stays+ content = get_graphql_content(response)+ assert content["data"]["customerDelete"]["errors"] == []+ assert User.objects.filter(pk=customer_user.pk).exists() is False+ assert AttributeValue.objects.filter(pk=reference_value.pk).exists() is False+ assert Page.objects.filter(pk=page.pk).exists() is True+++def test_deleting_user_keeps_other_users_single_reference_values(+ staff_api_client,+ customer_user,+ customer_user2,+ permission_manage_users,+ customer_type_page_single_reference_attribute,+ default_customer_type,+ page,+):+ # given: both users reference the same page through the same attribute,+ # assigned via the real mutation path so the per-user value creation+ # (not a hand-built slug) is what is under test+ default_customer_type.customer_attributes.add(+ customer_type_page_single_reference_attribute+ )+ attribute_id = graphene.Node.to_global_id(+ "Attribute", customer_type_page_single_reference_attribute.pk+ )+ page_id = graphene.Node.to_global_id("Page", page.pk)+ staff_api_client.user.user_permissions.add(permission_manage_users)+ update_mutation = """+ mutation CustomerUpdate($id: ID!, $input: CustomerInput!) {+ customerUpdate(id: $id, input: $input) {+ errors {+ field+ message+ }+ }+ }+ """+ for user in [customer_user, customer_user2]:+ variables = {+ "id": graphene.Node.to_global_id("User", user.pk),+ "input": {"attributes": [{"id": attribute_id, "reference": page_id}]},+ }+ response = staff_api_client.post_graphql(update_mutation, variables)+ content = get_graphql_content(response)+ assert content["data"]["customerUpdate"]["errors"] == []+ # the same reference produced one value row per user - rows are not shared+ values = AttributeValue.objects.filter(+ attribute=customer_type_page_single_reference_attribute+ )+ assert values.count() == 2++ # when: one of the users is deleted+ variables = {"id": graphene.Node.to_global_id("User", customer_user.pk)}+ response = staff_api_client.post_graphql(CUSTOMER_DELETE_MUTATION, variables)++ # then: only the deleted user's value is gone+ content = get_graphql_content(response)+ assert content["data"]["customerDelete"]["errors"] == []+ assert User.objects.filter(pk=customer_user.pk).exists() is False+ remaining_value = AttributeValue.objects.get(+ attribute=customer_type_page_single_reference_attribute+ )+ assert remaining_value.uservalueassignment.get().user == customer_user2+ assert remaining_value.reference_page == pagediff --git a/saleor/graphql/account/tests/mutations/staff/test_customer_update.py b/saleor/graphql/account/tests/mutations/staff/test_customer_update.pyindex 4fe7d25773..8c97131dba 100644--- a/saleor/graphql/account/tests/mutations/staff/test_customer_update.py+++ b/saleor/graphql/account/tests/mutations/staff/test_customer_update.py@@ -6,6 +6,7 @@ import pytestfrom ......account import events as account_eventsfrom ......account import modelsfrom ......account.error_codes import AccountErrorCode+from ......attribute.models import AssignedUserAttributeValuefrom ......giftcard.models import GiftCardfrom ......giftcard.search import update_gift_cards_search_vectorfrom .....tests.utils import get_graphql_content@@ -911,3 +912,260 @@ def test_customer_confirm_assign_gift_cards_and_orders(order.refresh_from_db()assert order.user == customer_user+++CUSTOMER_UPDATE_ATTRIBUTES_MUTATION = """+ mutation UpdateCustomer(+ $id: ID!, $customerType: ID, $attributes: [AttributeValueInput!]+ ) {+ customerUpdate(id: $id, input: {+ customerType: $customerType,+ attributes: $attributes+ }) {+ errors {+ field+ code+ message+ }+ user {+ id+ customerType {+ id+ }+ }+ }+ }+"""+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+def test_update_with_attributes_assigns_values(+ mocked_customer_updated,+ staff_api_client,+ permission_manage_users,+ customer_user,+ customer_type_with_attributes,+ loyalty_customer_attribute,+ description_customer_attribute,+ default_customer_type,+):+ # given+ customer_user.customer_type = customer_type_with_attributes+ customer_user.save(update_fields=["customer_type"])+ value = loyalty_customer_attribute.values.get(slug="gold")+ description_text = "Long-time customer."+ variables = {+ "id": graphene.Node.to_global_id("User", customer_user.id),+ "attributes": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ ),+ "dropdown": {+ "id": graphene.Node.to_global_id("AttributeValue", value.pk)+ },+ },+ {+ "id": graphene.Node.to_global_id(+ "Attribute", description_customer_attribute.pk+ ),+ "plainText": description_text,+ },+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_UPDATE_ATTRIBUTES_MUTATION,+ variables,+ permissions=[permission_manage_users],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerUpdate"]+ assert not data["errors"]+ assigned_values = AssignedUserAttributeValue.objects.filter(user=customer_user)+ assert assigned_values.count() == 2+ assert (+ assigned_values.get(value__attribute=loyalty_customer_attribute).value == value+ )+ description_value = assigned_values.get(+ value__attribute=description_customer_attribute+ ).value+ assert description_value.plain_text == description_text+ mocked_customer_updated.assert_called_once_with(customer_user)+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+def test_update_changes_customer_type(+ mocked_customer_updated,+ staff_api_client,+ permission_manage_users,+ customer_user,+ customer_type,+ default_customer_type,+):+ # given+ customer_user.customer_type = default_customer_type+ customer_user.save(update_fields=["customer_type"])+ customer_type_id = graphene.Node.to_global_id("CustomerType", customer_type.pk)+ variables = {+ "id": graphene.Node.to_global_id("User", customer_user.id),+ "customerType": customer_type_id,+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_UPDATE_ATTRIBUTES_MUTATION,+ variables,+ permissions=[permission_manage_users],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerUpdate"]+ assert not data["errors"]+ assert data["user"]["customerType"]["id"] == customer_type_id+ customer_user.refresh_from_db()+ assert customer_user.customer_type == customer_type+ mocked_customer_updated.assert_called_once_with(customer_user)+++def test_update_attributes_validated_against_new_customer_type(+ staff_api_client,+ permission_manage_users,+ customer_user,+ customer_type,+ customer_type_with_attributes,+ loyalty_customer_attribute,+ description_customer_attribute,+ default_customer_type,+):+ # given: the user's current type has the attributes, but the new type+ # from the input does not+ customer_user.customer_type = customer_type_with_attributes+ customer_user.save(update_fields=["customer_type"])+ new_customer_type = default_customer_type+ assert not new_customer_type.customer_attributes.filter(+ pk__in=[loyalty_customer_attribute.pk, description_customer_attribute.pk]+ ).exists()+ attribute_id = graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ )+ variables = {+ "id": graphene.Node.to_global_id("User", customer_user.id),+ "customerType": graphene.Node.to_global_id(+ "CustomerType", new_customer_type.pk+ ),+ "attributes": [+ {"id": attribute_id, "dropdown": {"value": "gold"}},+ {+ "id": graphene.Node.to_global_id(+ "Attribute", description_customer_attribute.pk+ ),+ "plainText": "A very important customer.",+ },+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_UPDATE_ATTRIBUTES_MUTATION,+ variables,+ permissions=[permission_manage_users],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerUpdate"]+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "attributes"+ assert error["code"] == AccountErrorCode.NOT_FOUND.name+ customer_user.refresh_from_db()+ assert customer_user.customer_type == customer_type_with_attributes+++def test_update_customer_type_change_keeps_attribute_values(+ staff_api_client,+ permission_manage_users,+ customer_user,+ customer_type,+ customer_type_with_attributes,+ loyalty_customer_attribute,+ default_customer_type,+):+ # given: the user has a value assigned for an attribute of the current type+ customer_user.customer_type = customer_type_with_attributes+ customer_user.save(update_fields=["customer_type"])+ value = loyalty_customer_attribute.values.get(slug="gold")+ AssignedUserAttributeValue.objects.create(user=customer_user, value=value)++ # when: the type changes to one without that attribute+ variables = {+ "id": graphene.Node.to_global_id("User", customer_user.id),+ "customerType": graphene.Node.to_global_id(+ "CustomerType", default_customer_type.pk+ ),+ }+ response = staff_api_client.post_graphql(+ CUSTOMER_UPDATE_ATTRIBUTES_MUTATION,+ variables,+ permissions=[permission_manage_users],+ )++ # then: the value persists in the database+ content = get_graphql_content(response)+ assert not content["data"]["customerUpdate"]["errors"]+ customer_user.refresh_from_db()+ assert customer_user.customer_type == default_customer_type+ assigned_values = AssignedUserAttributeValue.objects.filter(user=customer_user)+ assert assigned_values.count() == 1+ assert assigned_values.first().value == value+++def test_update_with_attributes_replaces_existing_value(+ staff_api_client,+ permission_manage_users,+ customer_user,+ customer_type_with_attributes,+ loyalty_customer_attribute,+ default_customer_type,+):+ # given: the user already has a value assigned for the attribute+ customer_user.customer_type = customer_type_with_attributes+ customer_user.save(update_fields=["customer_type"])+ old_value = loyalty_customer_attribute.values.get(slug="gold")+ new_value = loyalty_customer_attribute.values.get(slug="silver")+ AssignedUserAttributeValue.objects.create(user=customer_user, value=old_value)+ variables = {+ "id": graphene.Node.to_global_id("User", customer_user.id),+ "attributes": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ ),+ "dropdown": {+ "id": graphene.Node.to_global_id("AttributeValue", new_value.pk)+ },+ },+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_UPDATE_ATTRIBUTES_MUTATION,+ variables,+ permissions=[permission_manage_users],+ )++ # then: the assignment is replaced, not appended to+ content = get_graphql_content(response)+ assert not content["data"]["customerUpdate"]["errors"]+ assigned_value = AssignedUserAttributeValue.objects.get(+ user=customer_user, value__attribute=loyalty_customer_attribute+ )+ assert assigned_value.value == new_value+ # the old value remains a choice of the attribute+ assert loyalty_customer_attribute.values.filter(pk=old_value.pk).exists()diff --git a/saleor/graphql/account/tests/mutations/staff/test_staff_create.py b/saleor/graphql/account/tests/mutations/staff/test_staff_create.pyindex 74fd0c8744..25949e09be 100644--- a/saleor/graphql/account/tests/mutations/staff/test_staff_create.py+++ b/saleor/graphql/account/tests/mutations/staff/test_staff_create.py@@ -509,3 +509,22 @@ def test_staff_create_with_upper_case_email(data = content["data"]["staffCreate"]assert not data["errors"]assert data["user"]["email"] == email.lower()+++def test_create_assigns_default_customer_type(+ staff_api_client, permission_manage_staff, default_customer_type+):+ # given+ email = "[email protected]"+ variables = {"input": {"email": email}}++ # when+ response = staff_api_client.post_graphql(+ STAFF_CREATE_MUTATION, variables, permissions=[permission_manage_staff]+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["staffCreate"]["errors"]+ new_user = User.objects.get(email=email)+ assert new_user.customer_type == default_customer_typediff --git a/saleor/graphql/account/tests/mutations/staff/test_staff_delete.py b/saleor/graphql/account/tests/mutations/staff/test_staff_delete.pyindex cd570dbc60..3d218331dc 100644--- a/saleor/graphql/account/tests/mutations/staff/test_staff_delete.py+++ b/saleor/graphql/account/tests/mutations/staff/test_staff_delete.py@@ -10,6 +10,7 @@ from freezegun import freeze_timefrom ......account.error_codes import AccountErrorCodefrom ......account.models import Group, User+from ......attribute.models import AssignedUserAttributeValue, AttributeValuefrom ......core.utils.json_serializer import CustomJsonEncoderfrom ......permission.enums import AccountPermissions, OrderPermissionsfrom ......webhook.event_types import WebhookEventAsyncType@@ -344,3 +345,36 @@ def test_staff_update_errors(staff_user, customer_user, admin_user):# should not raise any errorsStaffUpdate.clean_is_active(input, customer_user, staff_user, errors)assert not errors["is_active"]+++def test_deletes_unique_attribute_values_and_keeps_shared_choices(+ staff_api_client,+ permission_manage_staff,+ description_customer_attribute,+ loyalty_customer_attribute,+):+ # given: the staff user has a unique (plain text) value and a shared choice+ staff_user = User.objects.create(email="[email protected]", is_staff=True)+ plain_text = "Notes about the staff member"+ unique_value = AttributeValue.objects.create(+ attribute=description_customer_attribute,+ name=plain_text,+ slug=f"{staff_user.pk}_{description_customer_attribute.pk}",+ plain_text=plain_text,+ )+ choice_value = loyalty_customer_attribute.values.get(slug="gold")+ AssignedUserAttributeValue.objects.create(user=staff_user, value=unique_value)+ AssignedUserAttributeValue.objects.create(user=staff_user, value=choice_value)+ variables = {"id": graphene.Node.to_global_id("User", staff_user.pk)}++ # when+ response = staff_api_client.post_graphql(+ STAFF_DELETE_MUTATION, variables, permissions=[permission_manage_staff]+ )++ # then: the unique value is deleted with the user, the shared choice stays+ content = get_graphql_content(response)+ assert content["data"]["staffDelete"]["errors"] == []+ assert User.objects.filter(pk=staff_user.pk).exists() is False+ assert AttributeValue.objects.filter(pk=unique_value.pk).exists() is False+ assert AttributeValue.objects.filter(pk=choice_value.pk).exists() is Truediff --git a/saleor/graphql/account/tests/queries/test_customer_type_attributes.py b/saleor/graphql/account/tests/queries/test_customer_type_attributes.pynew file mode 100644index 0000000000..44b5782c91--- /dev/null+++ b/saleor/graphql/account/tests/queries/test_customer_type_attributes.py@@ -0,0 +1,238 @@+import graphene++from ....tests.utils import assert_no_permission, get_graphql_content++CUSTOMER_TYPE_ATTRIBUTES_QUERY = """+ query CustomerType($id: ID!) {+ customerType(id: $id) {+ id+ attributes {+ slug+ }+ }+ }+"""++CUSTOMER_TYPE_AVAILABLE_ATTRIBUTES_QUERY = """+ query CustomerType(+ $id: ID!, $where: AttributeWhereInput, $search: String+ ) {+ customerType(id: $id) {+ id+ availableAttributes(first: 10, where: $where, search: $search) {+ edges {+ node {+ slug+ }+ }+ totalCount+ }+ }+ }+"""+++def test_attributes_with_manage_permission_includes_hidden(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+ hidden_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ customer_type.customer_attributes.add(+ loyalty_customer_attribute, hidden_customer_attribute+ )+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_ATTRIBUTES_QUERY, variables)++ # then+ content = get_graphql_content(response)+ attributes = content["data"]["customerType"]["attributes"]+ assert {attr["slug"] for attr in attributes} == {+ loyalty_customer_attribute.slug,+ hidden_customer_attribute.slug,+ }+++def test_attributes_without_manage_permission_hides_storefront_invisible(+ staff_api_client,+ customer_type,+ loyalty_customer_attribute,+ hidden_customer_attribute,+):+ # given+ customer_type.customer_attributes.add(+ loyalty_customer_attribute, hidden_customer_attribute+ )+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_ATTRIBUTES_QUERY, variables)++ # then+ content = get_graphql_content(response)+ attributes = content["data"]["customerType"]["attributes"]+ assert [attr["slug"] for attr in attributes] == [loyalty_customer_attribute.slug]+++def test_available_attributes_returns_unassigned_customer_attributes(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+ segment_customer_attribute,+ hidden_customer_attribute,+ size_page_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_AVAILABLE_ATTRIBUTES_QUERY, variables+ )++ # then+ content = get_graphql_content(response)+ available = content["data"]["customerType"]["availableAttributes"]+ assert available["totalCount"] == 2+ assert {edge["node"]["slug"] for edge in available["edges"]} == {+ segment_customer_attribute.slug,+ hidden_customer_attribute.slug,+ }+++def test_available_attributes_by_staff_without_permission(+ staff_api_client, customer_type, segment_customer_attribute+):+ # given+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_AVAILABLE_ATTRIBUTES_QUERY, variables+ )++ # then+ assert_no_permission(response)+++def test_available_attributes_search(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+ segment_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {+ "id": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "search": segment_customer_attribute.name,+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_AVAILABLE_ATTRIBUTES_QUERY, variables+ )++ # then+ content = get_graphql_content(response)+ available = content["data"]["customerType"]["availableAttributes"]+ assert available["totalCount"] == 1+ assert available["edges"][0]["node"]["slug"] == segment_customer_attribute.slug+++def test_available_attributes_where_slug(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ customer_type,+ loyalty_customer_attribute,+ segment_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ variables = {+ "id": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "where": {"slug": {"eq": loyalty_customer_attribute.slug}},+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_AVAILABLE_ATTRIBUTES_QUERY, variables+ )++ # then+ content = get_graphql_content(response)+ available = content["data"]["customerType"]["availableAttributes"]+ assert available["totalCount"] == 1+ assert available["edges"][0]["node"]["slug"] == loyalty_customer_attribute.slug+++def test_attributes_with_manage_users_permission_includes_hidden(+ staff_api_client,+ permission_manage_users,+ customer_type,+ loyalty_customer_attribute,+ hidden_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(permission_manage_users)+ customer_type.customer_attributes.add(+ loyalty_customer_attribute, hidden_customer_attribute+ )+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_ATTRIBUTES_QUERY, variables)++ # then+ content = get_graphql_content(response)+ attributes = content["data"]["customerType"]["attributes"]+ assert {attr["slug"] for attr in attributes} == {+ loyalty_customer_attribute.slug,+ hidden_customer_attribute.slug,+ }+++def test_available_attributes_with_manage_users_permission(+ staff_api_client,+ permission_manage_users,+ customer_type,+ loyalty_customer_attribute,+ segment_customer_attribute,+ hidden_customer_attribute,+ size_page_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(permission_manage_users)+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_TYPE_AVAILABLE_ATTRIBUTES_QUERY, variables+ )++ # then+ content = get_graphql_content(response)+ available = content["data"]["customerType"]["availableAttributes"]+ assert available["totalCount"] == 2+ assert {edge["node"]["slug"] for edge in available["edges"]} == {+ segment_customer_attribute.slug,+ hidden_customer_attribute.slug,+ }diff --git a/saleor/graphql/account/tests/queries/test_customer_types.py b/saleor/graphql/account/tests/queries/test_customer_types.pynew file mode 100644index 0000000000..25055ea697--- /dev/null+++ b/saleor/graphql/account/tests/queries/test_customer_types.py@@ -0,0 +1,200 @@+import graphene++from ....core.enums import OrderDirection+from ....tests.utils import assert_no_permission, get_graphql_content+from ...sorters import CustomerTypeSortField++CUSTOMER_TYPE_QUERY = """+ query CustomerType($id: ID!) {+ customerType(id: $id) {+ id+ name+ slug+ isDefault+ }+ }+"""++CUSTOMER_TYPES_QUERY = """+ query CustomerTypes(+ $where: CustomerTypeWhereInput,+ $search: String,+ $sortBy: CustomerTypeSortingInput+ ) {+ customerTypes(first: 10, where: $where, search: $search, sortBy: $sortBy) {+ edges {+ node {+ id+ name+ slug+ isDefault+ }+ }+ totalCount+ }+ }+"""+++def test_customer_type_query_by_staff_without_permissions(+ staff_api_client, customer_type+):+ # given+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ customer_type_data = content["data"]["customerType"]+ assert customer_type_data["name"] == customer_type.name+ assert customer_type_data["slug"] == customer_type.slug+ assert customer_type_data["isDefault"] == customer_type.is_default+++def test_customer_type_query_by_app(app_api_client, customer_type):+ # given+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}++ # when+ response = app_api_client.post_graphql(CUSTOMER_TYPE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ customer_type_data = content["data"]["customerType"]+ assert customer_type_data["slug"] == customer_type.slug+++def test_customer_type_query_by_customer_no_permission(user_api_client, customer_type):+ # given+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}++ # when+ response = user_api_client.post_graphql(CUSTOMER_TYPE_QUERY, variables)++ # then+ assert_no_permission(response)+++def test_customer_type_query_by_anonymous_no_permission(api_client, customer_type):+ # given+ variables = {"id": graphene.Node.to_global_id("CustomerType", customer_type.pk)}++ # when+ response = api_client.post_graphql(CUSTOMER_TYPE_QUERY, variables)++ # then+ assert_no_permission(response)+++def test_customer_types_query_by_staff(+ staff_api_client, customer_type, default_customer_type+):+ # given++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPES_QUERY, {})++ # then+ content = get_graphql_content(response)+ customer_types_data = content["data"]["customerTypes"]+ assert customer_types_data["totalCount"] == 2+ slugs = {edge["node"]["slug"] for edge in customer_types_data["edges"]}+ assert slugs == {customer_type.slug, default_customer_type.slug}+++def test_customer_types_query_by_customer_no_permission(user_api_client, customer_type):+ # when+ response = user_api_client.post_graphql(CUSTOMER_TYPES_QUERY, {})++ # then+ assert_no_permission(response)+++def test_customer_types_query_search(+ staff_api_client, customer_type, default_customer_type+):+ # given+ variables = {"search": customer_type.name}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPES_QUERY, variables)++ # then+ content = get_graphql_content(response)+ customer_types_data = content["data"]["customerTypes"]+ assert customer_types_data["totalCount"] == 1+ assert customer_types_data["edges"][0]["node"]["slug"] == customer_type.slug+++def test_customer_types_query_where_slug_one_of(+ staff_api_client, customer_type, default_customer_type+):+ # given+ variables = {"where": {"slug": {"oneOf": [default_customer_type.slug]}}}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPES_QUERY, variables)++ # then+ content = get_graphql_content(response)+ customer_types_data = content["data"]["customerTypes"]+ assert customer_types_data["totalCount"] == 1+ assert customer_types_data["edges"][0]["node"]["slug"] == default_customer_type.slug+++def test_customer_types_query_where_ids(+ staff_api_client, customer_type, default_customer_type+):+ # given+ customer_type_id = graphene.Node.to_global_id("CustomerType", customer_type.pk)+ variables = {"where": {"ids": [customer_type_id]}}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPES_QUERY, variables)++ # then+ content = get_graphql_content(response)+ customer_types_data = content["data"]["customerTypes"]+ assert customer_types_data["totalCount"] == 1+ assert customer_types_data["edges"][0]["node"]["id"] == customer_type_id+++def test_customer_types_query_where_is_default(+ staff_api_client, customer_type, default_customer_type+):+ # given+ variables = {"where": {"isDefault": True}}++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPES_QUERY, variables)++ # then+ content = get_graphql_content(response)+ customer_types_data = content["data"]["customerTypes"]+ assert customer_types_data["totalCount"] == 1+ assert customer_types_data["edges"][0]["node"]["slug"] == default_customer_type.slug+++def test_customer_types_query_sort_by_name_desc(+ staff_api_client, customer_type, default_customer_type+):+ # given+ variables = {+ "sortBy": {+ "field": CustomerTypeSortField.NAME.name,+ "direction": OrderDirection.DESC.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(CUSTOMER_TYPES_QUERY, variables)++ # then+ content = get_graphql_content(response)+ customer_types_data = content["data"]["customerTypes"]+ names = [edge["node"]["name"] for edge in customer_types_data["edges"]]+ assert names == sorted(+ [customer_type.name, default_customer_type.name], reverse=True+ )diff --git a/saleor/graphql/account/tests/queries/test_customers_where_attributes.py b/saleor/graphql/account/tests/queries/test_customers_where_attributes.pynew file mode 100644index 0000000000..152dd23a68--- /dev/null+++ b/saleor/graphql/account/tests/queries/test_customers_where_attributes.py@@ -0,0 +1,578 @@+import graphene+import pytest++from .....attribute import AttributeEntityType, AttributeInputType, AttributeType+from .....attribute.models import Attribute, AttributeValue+from .....attribute.utils import associate_attribute_values_to_instance+from .....page.models import Page+from ....tests.utils import get_graphql_content++QUERY_CUSTOMERS_WITH_WHERE = """+ query ($where: CustomerWhereInput!) {+ customers(first: 10, where: $where) {+ totalCount+ edges {+ node {+ id+ }+ }+ }+ }+"""++CUSTOMER_ATTRIBUTE_UNASSIGN_MUTATION = """+ mutation CustomerTypeUnassignAttributes(+ $customerTypeId: ID!, $attributeIds: [ID!]!+ ) {+ customerTypeUnassignAttributes(+ customerTypeId: $customerTypeId, attributeIds: $attributeIds+ ) {+ errors {+ field+ code+ message+ }+ }+ }+"""+++def test_filter_by_attribute_slug(+ staff_api_client,+ permission_group_manage_users,+ customer_users,+ customer_type_with_attributes,+ loyalty_customer_attribute,+):+ # given+ permission_group_manage_users.user_set.add(staff_api_client.user)+ customer = customer_users[0]+ customer.customer_type = customer_type_with_attributes+ customer.save(update_fields=["customer_type"])+ value = loyalty_customer_attribute.values.get(slug="gold")+ associate_attribute_values_to_instance(+ customer, {loyalty_customer_attribute.pk: [value]}+ )+ variables = {"where": {"attributes": [{"slug": loyalty_customer_attribute.slug}]}}++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ assert len(customers) == 1+ assert customers[0]["node"]["email"] == customer.email+ assert customers[0]["node"]["id"] == graphene.Node.to_global_id("User", customer.pk)++[email protected]("with_attr_slug", [True, False])+ "value_filter",+ [+ {"slug": {"eq": "gold"}},+ {"slug": {"oneOf": ["gold", "bronze"]}},+ {"name": {"eq": "Gold"}},+ {"name": {"oneOf": ["Gold", "Bronze"]}},+ ],+)+def test_filter_by_attribute_value_slug_or_name(+ value_filter,+ with_attr_slug,+ staff_api_client,+ permission_group_manage_users,+ customer_users,+ customer_type_with_attributes,+ loyalty_customer_attribute,+):+ # given: one customer with the matching value, another with a different+ # value of the same attribute+ permission_group_manage_users.user_set.add(staff_api_client.user)+ customer_with_gold = customer_users[0]+ customer_with_silver = customer_users[1]+ for customer in [customer_with_gold, customer_with_silver]:+ customer.customer_type = customer_type_with_attributes+ customer.save(update_fields=["customer_type"])+ gold_value = loyalty_customer_attribute.values.get(slug="gold")+ silver_value = loyalty_customer_attribute.values.get(slug="silver")+ associate_attribute_values_to_instance(+ customer_with_gold, {loyalty_customer_attribute.pk: [gold_value]}+ )+ associate_attribute_values_to_instance(+ customer_with_silver, {loyalty_customer_attribute.pk: [silver_value]}+ )+ attribute_filter = {"value": value_filter}+ if with_attr_slug:+ attribute_filter["slug"] = loyalty_customer_attribute.slug+ variables = {"where": {"attributes": [attribute_filter]}}++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ assert len(customers) == 1+ assert customers[0]["node"]["email"] == customer_with_gold.email+++def test_filter_by_boolean_attribute_value(+ staff_api_client,+ permission_group_manage_users,+ customer_users,+ customer_type,+):+ # given+ permission_group_manage_users.user_set.add(staff_api_client.user)+ newsletter_attribute = Attribute.objects.create(+ slug="newsletter",+ name="Newsletter",+ type=AttributeType.CUSTOMER_TYPE,+ input_type=AttributeInputType.BOOLEAN,+ )+ true_value = AttributeValue.objects.create(+ attribute=newsletter_attribute,+ name="Newsletter: Yes",+ slug=f"{newsletter_attribute.pk}_true",+ boolean=True,+ )+ false_value = AttributeValue.objects.create(+ attribute=newsletter_attribute,+ name="Newsletter: No",+ slug=f"{newsletter_attribute.pk}_false",+ boolean=False,+ )+ customer_type.customer_attributes.add(newsletter_attribute)+ subscribed_customer = customer_users[0]+ unsubscribed_customer = customer_users[1]+ for customer in [subscribed_customer, unsubscribed_customer]:+ customer.customer_type = customer_type+ customer.save(update_fields=["customer_type"])+ associate_attribute_values_to_instance(+ subscribed_customer, {newsletter_attribute.pk: [true_value]}+ )+ associate_attribute_values_to_instance(+ unsubscribed_customer, {newsletter_attribute.pk: [false_value]}+ )+ variables = {+ "where": {+ "attributes": [+ {"slug": newsletter_attribute.slug, "value": {"boolean": True}}+ ]+ }+ }++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ assert len(customers) == 1+ assert customers[0]["node"]["email"] == subscribed_customer.email+++ ("numeric_filter", "expected_match"),+ [+ ({"eq": 10}, True),+ ({"oneOf": [10, 20]}, True),+ ({"range": {"gte": 5, "lte": 15}}, True),+ ({"eq": 20}, False),+ ({"range": {"gte": 15}}, False),+ ],+)+def test_filter_by_numeric_attribute_value(+ numeric_filter,+ expected_match,+ staff_api_client,+ permission_group_manage_users,+ customer_users,+ customer_type,+):+ # given+ permission_group_manage_users.user_set.add(staff_api_client.user)+ orders_count_attribute = Attribute.objects.create(+ slug="yearly-orders",+ name="Yearly orders",+ type=AttributeType.CUSTOMER_TYPE,+ input_type=AttributeInputType.NUMERIC,+ )+ value = AttributeValue.objects.create(+ attribute=orders_count_attribute, name="10", slug="10", numeric=10+ )+ customer_type.customer_attributes.add(orders_count_attribute)+ customer = customer_users[0]+ customer.customer_type = customer_type+ customer.save(update_fields=["customer_type"])+ associate_attribute_values_to_instance(+ customer, {orders_count_attribute.pk: [value]}+ )+ variables = {+ "where": {+ "attributes": [+ {+ "slug": orders_count_attribute.slug,+ "value": {"numeric": numeric_filter},+ }+ ]+ }+ }++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ if expected_match:+ assert len(customers) == 1+ assert customers[0]["node"]["email"] == customer.email+ else:+ assert customers == []++[email protected]("filter_type", ["containsAny", "containsAll"])+def test_filter_by_page_reference_attribute_value(+ filter_type,+ staff_api_client,+ permission_group_manage_users,+ customer_users,+ customer_type,+ page_type,+):+ # given: one customer referencing both pages, another referencing only+ # the second one+ permission_group_manage_users.user_set.add(staff_api_client.user)+ page_reference_attribute = Attribute.objects.create(+ slug="customer-page-reference",+ name="Page reference",+ type=AttributeType.CUSTOMER_TYPE,+ input_type=AttributeInputType.REFERENCE,+ entity_type=AttributeEntityType.PAGE,+ )+ customer_type.customer_attributes.add(page_reference_attribute)+ referenced_page_1, referenced_page_2 = Page.objects.bulk_create(+ [+ Page(+ title="Referenced Page 1",+ slug="referenced-page-1",+ page_type=page_type,+ is_published=True,+ ),+ Page(+ title="Referenced Page 2",+ slug="referenced-page-2",+ page_type=page_type,+ is_published=True,+ ),+ ]+ )+ value_1, value_2 = AttributeValue.objects.bulk_create(+ [+ AttributeValue(+ attribute=page_reference_attribute,+ name=f"Page {referenced_page_1.pk}",+ slug=f"page-{referenced_page_1.pk}",+ reference_page=referenced_page_1,+ ),+ AttributeValue(+ attribute=page_reference_attribute,+ name=f"Page {referenced_page_2.pk}",+ slug=f"page-{referenced_page_2.pk}",+ reference_page=referenced_page_2,+ ),+ ]+ )+ customer_with_both_references = customer_users[0]+ customer_with_single_reference = customer_users[1]+ for customer in [customer_with_both_references, customer_with_single_reference]:+ customer.customer_type = customer_type+ customer.save(update_fields=["customer_type"])+ associate_attribute_values_to_instance(+ customer_with_both_references,+ {page_reference_attribute.pk: [value_1, value_2]},+ )+ associate_attribute_values_to_instance(+ customer_with_single_reference,+ {page_reference_attribute.pk: [value_2]},+ )+ variables = {+ "where": {+ "attributes": [+ {+ "slug": page_reference_attribute.slug,+ "value": {+ "reference": {+ "pageSlugs": {+ filter_type: [+ referenced_page_1.slug,+ referenced_page_2.slug,+ ]+ }+ }+ },+ }+ ]+ }+ }++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ emails = {customer["node"]["email"] for customer in customers}+ if filter_type == "containsAny":+ assert emails == {+ customer_with_both_references.email,+ customer_with_single_reference.email,+ }+ else:+ assert emails == {customer_with_both_references.email}+++def test_filter_by_nonexistent_attribute_slug(+ staff_api_client,+ permission_group_manage_users,+ customer_users,+):+ # given+ permission_group_manage_users.user_set.add(staff_api_client.user)+ variables = {"where": {"attributes": [{"slug": "non-existent-attribute"}]}}++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["customers"]["edges"] == []+ assert content["data"]["customers"]["totalCount"] == 0+++def test_filter_by_duplicated_attribute_slugs_returns_error(+ staff_api_client,+ permission_group_manage_users,+ loyalty_customer_attribute,+):+ # given+ permission_group_manage_users.user_set.add(staff_api_client.user)+ variables = {+ "where": {+ "attributes": [+ {"slug": loyalty_customer_attribute.slug},+ {"slug": loyalty_customer_attribute.slug},+ ]+ }+ }++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response, ignore_errors=True)+ assert len(content["errors"]) == 1+ assert content["errors"][0]["message"] == (+ "Duplicated attribute slugs in attribute 'where' input are not allowed."+ )+ assert content["data"]["customers"] is None+++ "filter_variant", ["slug_only", "slug_and_value", "value_only"]+)+def test_customer_not_filterable_by_attribute_after_unassign(+ filter_variant,+ staff_api_client,+ permission_group_manage_users,+ permission_manage_customer_types_and_attributes,+ customer_users,+ customer_type,+ loyalty_customer_attribute,+):+ # given: a customer type has the attribute assigned and the customer has+ # an attribute value assigned+ permission_group_manage_users.user_set.add(staff_api_client.user)+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ customer = customer_users[0]+ customer.customer_type = customer_type+ customer.save(update_fields=["customer_type"])+ value = loyalty_customer_attribute.values.get(slug="gold")+ associate_attribute_values_to_instance(+ customer, {loyalty_customer_attribute.pk: [value]}+ )++ attribute_filter = {}+ if filter_variant != "value_only":+ attribute_filter["slug"] = loyalty_customer_attribute.slug+ if filter_variant != "slug_only":+ attribute_filter["value"] = {"slug": {"eq": value.slug}}+ where_variables = {"where": {"attributes": [attribute_filter]}}++ response = staff_api_client.post_graphql(+ QUERY_CUSTOMERS_WITH_WHERE, where_variables+ )+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ assert len(customers) == 1+ assert customers[0]["node"]["email"] == customer.email++ # unassign the attribute from the customer type+ unassign_variables = {+ "customerTypeId": graphene.Node.to_global_id("CustomerType", customer_type.pk),+ "attributeIds": [+ graphene.Node.to_global_id("Attribute", loyalty_customer_attribute.pk)+ ],+ }+ response = staff_api_client.post_graphql(+ CUSTOMER_ATTRIBUTE_UNASSIGN_MUTATION, unassign_variables+ )+ content = get_graphql_content(response)+ assert content["data"]["customerTypeUnassignAttributes"]["errors"] == []++ # when+ response = staff_api_client.post_graphql(+ QUERY_CUSTOMERS_WITH_WHERE, where_variables+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["customers"]["edges"] == []+++ "filter_variant", ["slug_only", "slug_and_value", "value_only"]+)+def test_customer_not_filterable_by_attribute_after_customer_type_change(+ filter_variant,+ staff_api_client,+ permission_group_manage_users,+ customer_users,+ customer_type_with_attributes,+ default_customer_type,+ loyalty_customer_attribute,+):+ # given: the customer has an attribute value assigned via their customer+ # type+ permission_group_manage_users.user_set.add(staff_api_client.user)+ customer = customer_users[0]+ customer.customer_type = customer_type_with_attributes+ customer.save(update_fields=["customer_type"])+ value = loyalty_customer_attribute.values.get(slug="gold")+ associate_attribute_values_to_instance(+ customer, {loyalty_customer_attribute.pk: [value]}+ )++ attribute_filter = {}+ if filter_variant != "value_only":+ attribute_filter["slug"] = loyalty_customer_attribute.slug+ if filter_variant != "slug_only":+ attribute_filter["value"] = {"slug": {"eq": value.slug}}+ where_variables = {"where": {"attributes": [attribute_filter]}}++ response = staff_api_client.post_graphql(+ QUERY_CUSTOMERS_WITH_WHERE, where_variables+ )+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ assert len(customers) == 1+ assert customers[0]["node"]["email"] == customer.email++ # switch the customer to a type without the attribute; the value stays in+ # the database but is hidden from the API+ assert not default_customer_type.customer_attributes.filter(+ pk=loyalty_customer_attribute.pk+ ).exists()+ customer.customer_type = default_customer_type+ customer.save(update_fields=["customer_type"])+ assert customer.attributevalues.filter(value=value).exists()++ # when+ response = staff_api_client.post_graphql(+ QUERY_CUSTOMERS_WITH_WHERE, where_variables+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["customers"]["edges"] == []++[email protected]("with_explicit_default_type", [True, False])+def test_does_not_match_default_type_users_for_non_default_type_attribute(+ with_explicit_default_type,+ staff_api_client,+ permission_group_manage_users,+ customer_users,+ customer_type,+ default_customer_type,+ loyalty_customer_attribute,+):+ # given: the attribute belongs to a non-default customer type only, and+ # the customer with an assigned value belongs to the default type -+ # either explicitly or implicitly via no customer type assigned+ permission_group_manage_users.user_set.add(staff_api_client.user)+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ assert not default_customer_type.customer_attributes.filter(+ pk=loyalty_customer_attribute.pk+ ).exists()+ customer = customer_users[0]+ customer.customer_type = (+ default_customer_type if with_explicit_default_type else None+ )+ customer.save(update_fields=["customer_type"])+ value = loyalty_customer_attribute.values.get(slug="gold")+ associate_attribute_values_to_instance(+ customer, {loyalty_customer_attribute.pk: [value]}+ )+ variables = {"where": {"attributes": [{"slug": loyalty_customer_attribute.slug}]}}++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["customers"]["edges"] == []+++def test_filter_matches_users_without_customer_type_via_default_type(+ staff_api_client,+ permission_group_manage_users,+ customer_users,+ default_customer_type,+ loyalty_customer_attribute,+):+ # given: the attribute belongs to the default customer type and the+ # customer has no customer type explicitly assigned+ permission_group_manage_users.user_set.add(staff_api_client.user)+ default_customer_type.customer_attributes.add(loyalty_customer_attribute)+ customer = customer_users[0]+ customer.customer_type = None+ customer.save(update_fields=["customer_type"])+ value = loyalty_customer_attribute.values.get(slug="gold")+ associate_attribute_values_to_instance(+ customer, {loyalty_customer_attribute.pk: [value]}+ )+ variables = {+ "where": {+ "attributes": [+ {+ "slug": loyalty_customer_attribute.slug,+ "value": {"slug": {"eq": value.slug}},+ }+ ]+ }+ }++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ assert len(customers) == 1+ assert customers[0]["node"]["email"] == customer.emaildiff --git a/saleor/graphql/account/tests/queries/test_customers_where_filtering.py b/saleor/graphql/account/tests/queries/test_customers_where_filtering.pyindex 7dbc40ce9a..6f07a1b0b9 100644--- a/saleor/graphql/account/tests/queries/test_customers_where_filtering.py+++ b/saleor/graphql/account/tests/queries/test_customers_where_filtering.py@@ -5,7 +5,7 @@ import pytestfrom django.utils import timezonefrom freezegun import freeze_time-from .....account.models import Address, User+from .....account.models import Address, CustomerType, Userfrom .....account.tests.fixtures.user import dangerously_create_test_userfrom .....order import OrderOriginfrom ....tests.utils import get_graphql_content@@ -609,3 +609,159 @@ def test_customers_filter_by_last_name(assert len(customers) == len(expected_indexes)emails = {node["node"]["email"] for node in customers}assert emails == {customer_users[i].email for i in expected_indexes}+++def test_customers_filter_by_customer_type(+ staff_api_client,+ permission_group_manage_users,+ customer_users,+ customer_type,+ default_customer_type,+):+ # given+ permission_group_manage_users.user_set.add(staff_api_client.user)+ customer_with_type = customer_users[0]+ customer_with_type.customer_type = customer_type+ customer_with_default_type = customer_users[1]+ customer_with_default_type.customer_type = default_customer_type+ User.objects.bulk_update(+ [customer_with_type, customer_with_default_type], ["customer_type"]+ )+ variables = {+ "where": {+ "customerType": {+ "eq": graphene.Node.to_global_id("CustomerType", customer_type.pk)+ }+ }+ }++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ assert len(customers) == 1+ assert customers[0]["node"]["email"] == customer_with_type.email+++def test_customers_filter_by_customer_type_one_of(+ staff_api_client,+ permission_group_manage_users,+ customer_users,+ customer_type,+ default_customer_type,+):+ # given+ permission_group_manage_users.user_set.add(staff_api_client.user)+ second_customer_type = CustomerType.objects.create(name="B2C", slug="b2c")+ customer_users[0].customer_type = customer_type+ customer_users[1].customer_type = second_customer_type+ customer_users[2].customer_type = default_customer_type+ User.objects.bulk_update(customer_users, ["customer_type"])+ variables = {+ "where": {+ "customerType": {+ "oneOf": [+ graphene.Node.to_global_id("CustomerType", customer_type.pk),+ graphene.Node.to_global_id("CustomerType", second_customer_type.pk),+ ]+ }+ }+ }++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ assert len(customers) == 2+ emails = {node["node"]["email"] for node in customers}+ assert emails == {customer_users[0].email, customer_users[1].email}+++def test_customers_filter_by_customer_type_one_of_with_default_includes_users_without_type(+ staff_api_client,+ permission_group_manage_users,+ customer_users,+ customer_type,+ default_customer_type,+):+ # given: one user with a type from the filter, one without any type, one+ # with a type outside the filter+ permission_group_manage_users.user_set.add(staff_api_client.user)+ other_customer_type = CustomerType.objects.create(name="B2C", slug="b2c")+ customer_with_type = customer_users[0]+ customer_with_type.customer_type = customer_type+ customer_with_other_type = customer_users[1]+ customer_with_other_type.customer_type = other_customer_type+ User.objects.bulk_update(+ [customer_with_type, customer_with_other_type], ["customer_type"]+ )+ customer_without_type = customer_users[2]+ customer_without_type.customer_type = None+ customer_without_type.save(update_fields=["customer_type"])+ variables = {+ "where": {+ "customerType": {+ "oneOf": [+ graphene.Node.to_global_id("CustomerType", customer_type.pk),+ graphene.Node.to_global_id(+ "CustomerType", default_customer_type.pk+ ),+ ]+ }+ }+ }++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ assert len(customers) == 2+ emails = {node["node"]["email"] for node in customers}+ assert emails == {customer_with_type.email, customer_without_type.email}+++def test_customers_filter_by_default_customer_type_includes_users_without_type(+ staff_api_client,+ permission_group_manage_users,+ customer_users,+ customer_type,+ default_customer_type,+):+ # given: one user with the default type, one without any type, one with+ # a different type+ permission_group_manage_users.user_set.add(staff_api_client.user)+ customer_with_default_type = customer_users[0]+ customer_with_default_type.customer_type = default_customer_type+ customer_with_other_type = customer_users[1]+ customer_with_other_type.customer_type = customer_type+ User.objects.bulk_update(+ [customer_with_default_type, customer_with_other_type], ["customer_type"]+ )+ customer_without_type = customer_users[2]+ customer_without_type.customer_type = None+ customer_without_type.save(update_fields=["customer_type"])+ variables = {+ "where": {+ "customerType": {+ "eq": graphene.Node.to_global_id(+ "CustomerType", default_customer_type.pk+ )+ }+ }+ }++ # when+ response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_WHERE, variables)++ # then+ content = get_graphql_content(response)+ customers = content["data"]["customers"]["edges"]+ assert len(customers) == 2+ emails = {node["node"]["email"] for node in customers}+ assert emails == {customer_with_default_type.email, customer_without_type.email}diff --git a/saleor/graphql/account/tests/queries/test_user_assigned_attributes.py b/saleor/graphql/account/tests/queries/test_user_assigned_attributes.pynew file mode 100644index 0000000000..f8e962aa7a--- /dev/null+++ b/saleor/graphql/account/tests/queries/test_user_assigned_attributes.py@@ -0,0 +1,498 @@+import graphene++from .....attribute.models import AssignedUserAttributeValue+from ....tests.utils import assert_no_permission, get_graphql_content++USER_ASSIGNED_ATTRIBUTES_QUERY = """+ query User($id: ID!) {+ user(id: $id) {+ assignedAttributes {+ attribute {+ slug+ }+ ... on AssignedSingleChoiceAttribute {+ value {+ slug+ }+ }+ }+ }+ }+"""++ME_ASSIGNED_ATTRIBUTES_QUERY = """+ query Me {+ me {+ assignedAttributes {+ attribute {+ slug+ }+ ... on AssignedSingleChoiceAttribute {+ value {+ slug+ }+ }+ }+ }+ }+"""++USER_ASSIGNED_ATTRIBUTE_BY_SLUG_QUERY = """+ query User($id: ID!, $slug: String!) {+ user(id: $id) {+ assignedAttribute(slug: $slug) {+ attribute {+ slug+ }+ ... on AssignedSingleChoiceAttribute {+ value {+ slug+ }+ }+ }+ }+ }+"""+++def test_assigned_attributes_by_staff_with_manage_users(+ staff_api_client,+ permission_manage_users,+ customer_user,+ customer_type_with_attributes,+ loyalty_customer_attribute,+ description_customer_attribute,+ hidden_customer_attribute,+):+ # given+ customer_user.customer_type = customer_type_with_attributes+ customer_user.save(update_fields=["customer_type"])+ value = loyalty_customer_attribute.values.get(slug="gold")+ AssignedUserAttributeValue.objects.create(user=customer_user, value=value)+ variables = {"id": graphene.Node.to_global_id("User", customer_user.pk)}++ # when+ response = staff_api_client.post_graphql(+ USER_ASSIGNED_ATTRIBUTES_QUERY,+ variables,+ permissions=[permission_manage_users],+ )++ # then+ content = get_graphql_content(response)+ assigned_attributes = content["data"]["user"]["assignedAttributes"]+ slugs = {entry["attribute"]["slug"] for entry in assigned_attributes}+ assert slugs == {+ loyalty_customer_attribute.slug,+ description_customer_attribute.slug,+ hidden_customer_attribute.slug,+ }+ loyalty_entry = next(+ entry+ for entry in assigned_attributes+ if entry["attribute"]["slug"] == loyalty_customer_attribute.slug+ )+ assert loyalty_entry["value"]["slug"] == value.slug+++def test_assigned_attributes_by_owner_hides_storefront_invisible(+ user_api_client,+ customer_type_with_attributes,+ loyalty_customer_attribute,+ description_customer_attribute,+ hidden_customer_attribute,+):+ # given+ user = user_api_client.user+ user.customer_type = customer_type_with_attributes+ user.save(update_fields=["customer_type"])+ value = loyalty_customer_attribute.values.get(slug="silver")+ AssignedUserAttributeValue.objects.create(user=user, value=value)++ # when+ response = user_api_client.post_graphql(ME_ASSIGNED_ATTRIBUTES_QUERY)++ # then+ content = get_graphql_content(response)+ assigned_attributes = content["data"]["me"]["assignedAttributes"]+ slugs = {entry["attribute"]["slug"] for entry in assigned_attributes}+ assert slugs == {+ loyalty_customer_attribute.slug,+ description_customer_attribute.slug,+ }+ loyalty_entry = next(+ entry+ for entry in assigned_attributes+ if entry["attribute"]["slug"] == loyalty_customer_attribute.slug+ )+ assert loyalty_entry["value"]["slug"] == value.slug+++def test_assigned_attributes_by_staff_without_manage_users(+ staff_api_client,+ permission_manage_staff,+ admin_user,+):+ # given: a staff user queries another user without MANAGE_USERS+ variables = {"id": graphene.Node.to_global_id("User", admin_user.pk)}++ # when+ response = staff_api_client.post_graphql(+ USER_ASSIGNED_ATTRIBUTES_QUERY,+ variables,+ permissions=[permission_manage_staff],+ )++ # then+ assert_no_permission(response)+++def test_assigned_attributes_fall_back_to_default_customer_type(+ staff_api_client,+ permission_manage_users,+ customer_user,+ default_customer_type,+ segment_customer_attribute,+):+ # given: the user has no customer type assigned yet+ default_customer_type.customer_attributes.add(segment_customer_attribute)+ customer_user.customer_type = None+ customer_user.save(update_fields=["customer_type"])+ variables = {"id": graphene.Node.to_global_id("User", customer_user.pk)}++ # when+ response = staff_api_client.post_graphql(+ USER_ASSIGNED_ATTRIBUTES_QUERY,+ variables,+ permissions=[permission_manage_users],+ )++ # then+ content = get_graphql_content(response)+ assigned_attributes = content["data"]["user"]["assignedAttributes"]+ slugs = {entry["attribute"]["slug"] for entry in assigned_attributes}+ assert slugs == {segment_customer_attribute.slug}+++def test_assigned_attribute_by_slug_by_staff(+ staff_api_client,+ permission_manage_users,+ customer_user,+ customer_type_with_attributes,+ loyalty_customer_attribute,+):+ # given+ customer_user.customer_type = customer_type_with_attributes+ customer_user.save(update_fields=["customer_type"])+ value = loyalty_customer_attribute.values.get(slug="gold")+ AssignedUserAttributeValue.objects.create(user=customer_user, value=value)+ variables = {+ "id": graphene.Node.to_global_id("User", customer_user.pk),+ "slug": loyalty_customer_attribute.slug,+ }++ # when+ response = staff_api_client.post_graphql(+ USER_ASSIGNED_ATTRIBUTE_BY_SLUG_QUERY,+ variables,+ permissions=[permission_manage_users],+ )++ # then+ content = get_graphql_content(response)+ assigned_attribute = content["data"]["user"]["assignedAttribute"]+ assert assigned_attribute["attribute"]["slug"] == loyalty_customer_attribute.slug+ assert assigned_attribute["value"]["slug"] == value.slug+++def test_assigned_attribute_by_slug_hidden_attribute_by_staff(+ staff_api_client,+ permission_manage_users,+ customer_user,+ customer_type_with_attributes,+ hidden_customer_attribute,+):+ # given+ customer_user.customer_type = customer_type_with_attributes+ customer_user.save(update_fields=["customer_type"])+ variables = {+ "id": graphene.Node.to_global_id("User", customer_user.pk),+ "slug": hidden_customer_attribute.slug,+ }++ # when+ response = staff_api_client.post_graphql(+ USER_ASSIGNED_ATTRIBUTE_BY_SLUG_QUERY,+ variables,+ permissions=[permission_manage_users],+ )++ # then+ content = get_graphql_content(response)+ assigned_attribute = content["data"]["user"]["assignedAttribute"]+ assert assigned_attribute["attribute"]["slug"] == hidden_customer_attribute.slug+++def test_assigned_attributes_kept_after_switch_to_type_sharing_the_attribute(+ staff_api_client,+ permission_manage_users,+ customer_user,+ customer_type,+ default_customer_type,+ loyalty_customer_attribute,+):+ # given: the attribute belongs to two customer types and the value was+ # assigned while the user belonged to the first one+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ default_customer_type.customer_attributes.add(loyalty_customer_attribute)+ customer_user.customer_type = customer_type+ customer_user.save(update_fields=["customer_type"])+ value = loyalty_customer_attribute.values.get(slug="gold")+ AssignedUserAttributeValue.objects.create(user=customer_user, value=value)+ user_id = graphene.Node.to_global_id("User", customer_user.pk)+ variables = {"id": user_id}++ response = staff_api_client.post_graphql(+ USER_ASSIGNED_ATTRIBUTES_QUERY,+ variables,+ permissions=[permission_manage_users],+ )+ content = get_graphql_content(response)+ assigned_attributes = content["data"]["user"]["assignedAttributes"]+ assert len(assigned_attributes) == 1+ assert (+ assigned_attributes[0]["attribute"]["slug"] == loyalty_customer_attribute.slug+ )+ assert assigned_attributes[0]["value"]["slug"] == value.slug++ # when: the user switches to the other type sharing the attribute+ mutation = """+ mutation CustomerUpdate($id: ID!, $input: CustomerInput!) {+ customerUpdate(id: $id, input: $input) {+ user {+ customerType {+ id+ }+ }+ errors {+ field+ code+ message+ }+ }+ }+ """+ default_customer_type_id = graphene.Node.to_global_id(+ "CustomerType", default_customer_type.pk+ )+ mutation_variables = {+ "id": user_id,+ "input": {"customerType": default_customer_type_id},+ }+ response = staff_api_client.post_graphql(mutation, mutation_variables)+ content = get_graphql_content(response)+ data = content["data"]["customerUpdate"]+ assert data["errors"] == []+ assert data["user"]["customerType"]["id"] == default_customer_type_id++ # then: the value stays visible because the new type also has the attribute+ response = staff_api_client.post_graphql(USER_ASSIGNED_ATTRIBUTES_QUERY, variables)+ content = get_graphql_content(response)+ assigned_attributes = content["data"]["user"]["assignedAttributes"]+ assert len(assigned_attributes) == 1+ assert (+ assigned_attributes[0]["attribute"]["slug"] == loyalty_customer_attribute.slug+ )+ assert assigned_attributes[0]["value"]["slug"] == value.slug+++USER_ASSIGNED_MULTISELECT_VALUE_LIMIT_QUERY = """+ query User($id: ID!) {+ user(id: $id) {+ assignedAttributes {+ attribute {+ slug+ }+ ... on AssignedMultiChoiceAttribute {+ value(limit: 2) {+ slug+ }+ }+ }+ }+ }+"""+++def test_assigned_multiselect_value_limit_truncates(+ staff_api_client,+ permission_manage_users,+ customer_user,+ customer_type,+ interests_customer_attribute,+):+ # given: three values assigned, a limit of two+ customer_type.customer_attributes.add(interests_customer_attribute)+ customer_user.customer_type = customer_type+ customer_user.save(update_fields=["customer_type"])+ sports = interests_customer_attribute.values.get(slug="sports")+ music = interests_customer_attribute.values.get(slug="music")+ travel = interests_customer_attribute.values.get(slug="travel")+ for value in [sports, music, travel]:+ AssignedUserAttributeValue.objects.create(user=customer_user, value=value)+ variables = {"id": graphene.Node.to_global_id("User", customer_user.pk)}++ # when+ response = staff_api_client.post_graphql(+ USER_ASSIGNED_MULTISELECT_VALUE_LIMIT_QUERY,+ variables,+ permissions=[permission_manage_users],+ )++ # then: only the first two values in assignment order are returned+ content = get_graphql_content(response)+ assigned_attributes = content["data"]["user"]["assignedAttributes"]+ assert assigned_attributes == [+ {+ "attribute": {"slug": interests_customer_attribute.slug},+ "value": [{"slug": sports.slug}, {"slug": music.slug}],+ }+ ]+++def test_assigned_attributes_limit_caps_attribute_count(+ staff_api_client,+ permission_manage_users,+ customer_user,+ customer_type,+ loyalty_customer_attribute,+ description_customer_attribute,+ hidden_customer_attribute,+):+ # given: the customer type holds three attributes, a limit of one.+ # Separate add() calls per attribute - a single call iterates an+ # unordered set of ids, making the insertion (and thus fallback pk)+ # ordering nondeterministic.+ customer_type.customer_attributes.add(loyalty_customer_attribute)+ customer_type.customer_attributes.add(description_customer_attribute)+ customer_type.customer_attributes.add(hidden_customer_attribute)+ customer_user.customer_type = customer_type+ customer_user.save(update_fields=["customer_type"])+ query = """+ query User($id: ID!) {+ user(id: $id) {+ assignedAttributes(limit: 1) {+ attribute {+ slug+ }+ }+ }+ }+ """+ variables = {"id": graphene.Node.to_global_id("User", customer_user.pk)}++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[permission_manage_users],+ )++ # then: only the first attribute of the customer type is returned+ content = get_graphql_content(response)+ assigned_attributes = content["data"]["user"]["assignedAttributes"]+ assert assigned_attributes == [+ {"attribute": {"slug": loyalty_customer_attribute.slug}}+ ]+++def test_assigned_multiselect_value_limit_partitions_per_user(+ staff_api_client,+ permission_manage_users,+ customer_users,+ customer_type,+ interests_customer_attribute,+):+ # given: two users with the same values assigned in opposite orders+ customer_type.customer_attributes.add(interests_customer_attribute)+ first_user, second_user = customer_users[:2]+ for user in [first_user, second_user]:+ user.customer_type = customer_type+ user.save(update_fields=["customer_type"])+ sports = interests_customer_attribute.values.get(slug="sports")+ music = interests_customer_attribute.values.get(slug="music")+ travel = interests_customer_attribute.values.get(slug="travel")+ for value in [sports, music, travel]:+ AssignedUserAttributeValue.objects.create(user=first_user, value=value)+ for value in [travel, music, sports]:+ AssignedUserAttributeValue.objects.create(user=second_user, value=value)+ query = """+ query Users($firstId: ID!, $secondId: ID!) {+ firstUser: user(id: $firstId) {+ assignedAttributes {+ ... on AssignedMultiChoiceAttribute {+ value(limit: 2) {+ slug+ }+ }+ }+ }+ secondUser: user(id: $secondId) {+ assignedAttributes {+ ... on AssignedMultiChoiceAttribute {+ value(limit: 2) {+ slug+ }+ }+ }+ }+ }+ """+ variables = {+ "firstId": graphene.Node.to_global_id("User", first_user.pk),+ "secondId": graphene.Node.to_global_id("User", second_user.pk),+ }++ # when: both users are resolved in a single request+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[permission_manage_users],+ )++ # then: each user gets their own first two values in their own order+ content = get_graphql_content(response)+ first_values = content["data"]["firstUser"]["assignedAttributes"][0]["value"]+ second_values = content["data"]["secondUser"]["assignedAttributes"][0]["value"]+ assert first_values == [{"slug": sports.slug}, {"slug": music.slug}]+ assert second_values == [{"slug": travel.slug}, {"slug": music.slug}]+++def test_assigned_attribute_by_slug_hidden_attribute_by_owner(+ user_api_client,+ customer_type_with_attributes,+ hidden_customer_attribute,+):+ # given+ user = user_api_client.user+ user.customer_type = customer_type_with_attributes+ user.save(update_fields=["customer_type"])+ query = """+ query Me($slug: String!) {+ me {+ assignedAttribute(slug: $slug) {+ attribute {+ slug+ }+ }+ }+ }+ """+ variables = {"slug": hidden_customer_attribute.slug}++ # when+ response = user_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["me"]["assignedAttribute"] is Nonediff --git a/saleor/graphql/account/tests/queries/test_user_customer_type.py b/saleor/graphql/account/tests/queries/test_user_customer_type.pynew file mode 100644index 0000000000..b92547215d--- /dev/null+++ b/saleor/graphql/account/tests/queries/test_user_customer_type.py@@ -0,0 +1,97 @@+import graphene++from ....tests.utils import assert_no_permission, get_graphql_content++USER_CUSTOMER_TYPE_QUERY = """+ query User($id: ID!) {+ user(id: $id) {+ id+ customerType {+ id+ name+ slug+ isDefault+ }+ }+ }+"""++ME_CUSTOMER_TYPE_QUERY = """+ query Me {+ me {+ id+ customerType {+ id+ name+ slug+ }+ }+ }+"""+++def test_customer_type_visible_to_staff_with_manage_users(+ staff_api_client, permission_manage_users, customer_user, customer_type+):+ # given+ staff_api_client.user.user_permissions.add(permission_manage_users)+ customer_user.customer_type = customer_type+ customer_user.save(update_fields=["customer_type"])+ variables = {"id": graphene.Node.to_global_id("User", customer_user.pk)}++ # when+ response = staff_api_client.post_graphql(USER_CUSTOMER_TYPE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ customer_type_data = content["data"]["user"]["customerType"]+ assert customer_type_data["name"] == customer_type.name+ assert customer_type_data["slug"] == customer_type.slug+ assert customer_type_data["isDefault"] == customer_type.is_default+++def test_customer_type_visible_to_owner(user_api_client, customer_user, customer_type):+ # given+ customer_user.customer_type = customer_type+ customer_user.save(update_fields=["customer_type"])++ # when+ response = user_api_client.post_graphql(ME_CUSTOMER_TYPE_QUERY)++ # then+ content = get_graphql_content(response)+ customer_type_data = content["data"]["me"]["customerType"]+ assert customer_type_data["slug"] == customer_type.slug+++def test_customer_type_not_visible_to_staff_without_permission(+ staff_api_client, permission_manage_orders, customer_user, customer_type+):+ # given the customers query is reachable with MANAGE_ORDERS, but the+ # customerType field requires MANAGE_USERS or ownership+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ customer_user.customer_type = customer_type+ customer_user.save(update_fields=["customer_type"])+ variables = {"id": graphene.Node.to_global_id("User", customer_user.pk)}++ # when+ response = staff_api_client.post_graphql(USER_CUSTOMER_TYPE_QUERY, variables)++ # then+ assert_no_permission(response)+++def test_customer_type_falls_back_to_default_when_not_assigned(+ user_api_client, customer_user, default_customer_type+):+ # given a user created before the backfill finished+ customer_user.customer_type = None+ customer_user.save(update_fields=["customer_type"])++ # when+ response = user_api_client.post_graphql(ME_CUSTOMER_TYPE_QUERY)++ # then+ content = get_graphql_content(response)+ customer_type_data = content["data"]["me"]["customerType"]+ assert customer_type_data["slug"] == default_customer_type.slugdiff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.pyindex feaa75cccf..230f6a78f7 100644--- a/saleor/graphql/account/types.py+++ b/saleor/graphql/account/types.py@@ -7,13 +7,20 @@ from graphene import relayfrom promise import Promisefrom ...account import models+from ...attribute import models as attribute_modelsfrom ...checkout.utils import get_user_checkoutfrom ...core.exceptions import PermissionDeniedfrom ...graphql.meta.inputs import MetadataInput, MetadataInputDescriptionfrom ...order import OrderStatusfrom ...payment.interface import ListStoredPaymentMethodsRequestDatafrom ...permission.auth_filters import AuthorizationFilters-from ...permission.enums import AccountPermissions, AppPermission, OrderPermissions+from ...permission.enums import (+ AccountPermissions,+ AppPermission,+ CustomerTypePermissions,+ OrderPermissions,+)+from ...permission.utils import one_of_permissions_or_auth_filter_requiredfrom ...plugins.manager import PluginsManagerfrom ...thumbnail.utils import (get_image_or_proxy_url,@@ -23,6 +30,13 @@ from ...thumbnail.utils import (from ..account.utils import check_is_owner_or_has_one_of_permsfrom ..app.dataloaders import AppByIdLoader, get_app_promisefrom ..app.types import App+from ..attribute.filters import AttributeWhereInput, filter_attribute_search+from ..attribute.types import (+ Attribute,+ AttributeCountableConnection,+ ObjectWithAttributes,+)+from ..attribute.utils.shared import AssignedAttributeDatafrom ..channel.dataloaders.by_self import ChannelBySlugLoaderfrom ..channel.types import Channelfrom ..checkout.dataloaders import CheckoutByUserAndChannelLoader, CheckoutByUserLoader@@ -34,9 +48,16 @@ from ..core.connection import (create_connection_slice_for_sync_webhook_control_context,filter_connection_queryset,)-from ..core.context import SyncWebhookControlContext, get_database_connection_name+from ..core.const import DEFAULT_NESTED_LIST_LIMIT+from ..core.context import (+ ChannelContext,+ ChannelQsContext,+ SyncWebhookControlContext,+ get_database_connection_name,+)from ..core.descriptions import (ADDED_IN_322,+ ADDED_IN_323,DEPRECATED_LEGACY_PAYMENTS,PREVIEW_FEATURE,)@@ -44,7 +65,7 @@ from ..core.doc_category import DOC_CATEGORY_USERSfrom ..core.enums import LanguageCodeEnumfrom ..core.federation import federated_entity, resolve_federation_referencesfrom ..core.fields import ConnectionField, FilterConnectionField, PermissionsField-from ..core.scalars import UUID, DateTime+from ..core.scalars import UUID, DateTime, PositiveIntfrom ..core.tracing import traced_resolverfrom ..core.types import (BaseInputObjectType,@@ -66,10 +87,16 @@ from ..payment.types import StoredPaymentMethodfrom ..plugins.dataloaders import get_plugin_manager_promisefrom ..utils import format_permissions_for_display, get_user_or_app_from_contextfrom .dataloaders import (+ DEFAULT_CUSTOMER_TYPE_LOADER_KEY,AccessibleChannelsByGroupIdLoader,AccessibleChannelsByUserIdLoader,AddressByIdLoader,+ BaseCustomerAttributesByCustomerTypeIdLoader,+ CustomerAttributesAllByCustomerTypeIdLoader,+ CustomerAttributesVisibleInStorefrontByCustomerTypeIdLoader,CustomerEventsByUserLoader,+ CustomerTypeByIdLoader,+ DefaultCustomerTypeLoader,RestrictedChannelAccessByUserIdLoader,ThumbnailByUserIdSizeAndFormatLoader,)@@ -314,6 +341,94 @@ class UserPermission(Permission):return groups+class CustomerType(ModelObjectType[models.CustomerType]):+ id = graphene.GlobalID(required=True, description="The ID of the customer type.")+ name = graphene.String(required=True, description="Name of the customer type.")+ slug = graphene.String(required=True, description="Slug of the customer type.")+ is_default = graphene.Boolean(+ required=True,+ description=(+ "Whether this is the default customer type. The default customer type "+ "is assigned to every newly created user and cannot be deleted."+ ),+ )+ attributes = NonNullList(+ Attribute,+ description=(+ "Customer attributes assigned to this customer type. Attributes that "+ "are not visible in the storefront require one of the following "+ "permissions to be included: "+ f"{AccountPermissions.MANAGE_USERS.name}, "+ f"{CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.name}."+ ),+ )+ available_attributes = FilterConnectionField(+ AttributeCountableConnection,+ where=AttributeWhereInput(+ description="Where filtering options for attributes."+ ),+ search=graphene.String(description="Search attributes."),+ description="Customer attributes that can be assigned to the customer type.",+ permissions=[+ AccountPermissions.MANAGE_USERS,+ CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES,+ ],+ )++ class Meta:+ description = (+ "Represents a type of customer. It allows to segment users and defines "+ "what attributes are available to users of this type." + ADDED_IN_323+ )+ interfaces = [relay.Node, ObjectWithMetadata]+ model = models.CustomerType+ doc_category = DOC_CATEGORY_USERS++ @staticmethod+ def resolve_attributes(root: models.CustomerType, info: ResolveInfo):+ def wrap_with_channel_context(attributes):+ return [ChannelContext(attribute, None) for attribute in attributes]++ if one_of_permissions_or_auth_filter_required(+ info.context,+ [+ AccountPermissions.MANAGE_USERS,+ CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES,+ ],+ ):+ return (+ CustomerAttributesAllByCustomerTypeIdLoader(info.context)+ .load(root.pk)+ .then(wrap_with_channel_context)+ )+ return (+ CustomerAttributesVisibleInStorefrontByCustomerTypeIdLoader(info.context)+ .load(root.pk)+ .then(wrap_with_channel_context)+ )++ @staticmethod+ def resolve_available_attributes(+ root: models.CustomerType, info: ResolveInfo, search=None, **kwargs+ ):+ qs = attribute_models.Attribute.objects.get_unassigned_customer_type_attributes(+ root.pk+ ).using(get_database_connection_name(info.context))+ qs = filter_connection_queryset(+ qs, kwargs, info.context, allow_replica=info.context.allow_replica+ )+ if search:+ qs = filter_attribute_search(qs, None, search)+ qs = ChannelQsContext(qs=qs, channel_slug=None)+ return create_connection_slice(qs, info, kwargs, AttributeCountableConnection)+++class CustomerTypeCountableConnection(CountableConnection):+ class Meta:+ doc_category = DOC_CATEGORY_USERS+ node = CustomerType++def is_newly_created_user(user: models.User,):@@ -461,6 +576,48 @@ class User(ModelObjectType[models.User]):external_reference = graphene.String(description="External ID of this user.", required=False)+ customer_type = graphene.Field(+ CustomerType,+ description=(+ "The customer type assigned to the user. Requires one of the following "+ f"permissions: {AccountPermissions.MANAGE_USERS.name}, "+ f"{AuthorizationFilters.OWNER.name}." + ADDED_IN_323+ ),+ )+ assigned_attribute = graphene.Field(+ "saleor.graphql.attribute.types.AssignedAttribute",+ slug=graphene.Argument(+ graphene.String,+ description="Slug of the attribute",+ required=True,+ ),+ description=(+ "Get a single attribute assigned to the user by attribute slug. "+ "The attribute is looked up among the attributes of the user's "+ "customer type. Requires one of the following permissions: "+ f"{AccountPermissions.MANAGE_USERS.name}, "+ f"{AuthorizationFilters.OWNER.name}. The owner can access only "+ "attributes that are visible in the storefront." + ADDED_IN_323+ ),+ )+ assigned_attributes = NonNullList(+ "saleor.graphql.attribute.types.AssignedAttribute",+ required=True,+ description=(+ "List of attributes assigned to the user through the user's "+ "customer type. Requires one of the following permissions: "+ f"{AccountPermissions.MANAGE_USERS.name}, "+ f"{AuthorizationFilters.OWNER.name}. The owner can access only "+ "attributes that are visible in the storefront." + ADDED_IN_323+ ),+ limit=PositiveInt(+ description=(+ "Maximum number of attributes to return. "+ f"Default is {DEFAULT_NESTED_LIST_LIMIT}."+ ),+ default_value=DEFAULT_NESTED_LIST_LIMIT,+ ),+ )last_login = DateTime(description="The date when the user last time log in to the system."@@ -488,7 +645,7 @@ class User(ModelObjectType[models.User]):class Meta:description = "Represents user data."- interfaces = [relay.Node, ObjectWithMetadata]+ interfaces = [relay.Node, ObjectWithMetadata, ObjectWithAttributes]model = get_user_model()doc_category = DOC_CATEGORY_USERS@@ -856,6 +1013,96 @@ class User(ModelObjectType[models.User]):)return None+ @staticmethod+ def resolve_customer_type(root: models.User, info: ResolveInfo):+ requestor = get_user_or_app_from_context(info.context)+ check_is_owner_or_has_one_of_perms(+ requestor, root, AccountPermissions.MANAGE_USERS+ )+ if root.customer_type_id:+ return CustomerTypeByIdLoader(info.context).load(root.customer_type_id)+ # Users created before the customer type backfill finishes may still have+ # no type assigned - present them as having the default one.+ return DefaultCustomerTypeLoader(info.context).load(+ DEFAULT_CUSTOMER_TYPE_LOADER_KEY+ )++ @staticmethod+ def _load_customer_type_attributes(root: models.User, info: ResolveInfo, loader):+ """Load the attributes of the user's customer type.++ Users created before the customer type backfill finishes may still have+ no type assigned - fall back to the default type's attributes.+ """+ if root.customer_type_id:+ return loader.load(root.customer_type_id)+ return (+ DefaultCustomerTypeLoader(info.context)+ .load(DEFAULT_CUSTOMER_TYPE_LOADER_KEY)+ .then(lambda customer_type: loader.load(customer_type.pk))+ )++ @classmethod+ def resolve_assigned_attributes(+ cls,+ root: models.User,+ info: ResolveInfo,+ limit: int = DEFAULT_NESTED_LIST_LIMIT,+ ):+ requestor = get_user_or_app_from_context(info.context)+ check_is_owner_or_has_one_of_perms(+ requestor, root, AccountPermissions.MANAGE_USERS+ )++ def with_attributes(attributes: list[attribute_models.Attribute]):+ return [+ AssignedAttributeData(+ attribute=attribute, channel_slug=None, user_id=root.pk+ )+ for attribute in attributes[:limit]+ ]++ loader: BaseCustomerAttributesByCustomerTypeIdLoader+ if one_of_permissions_or_auth_filter_required(+ info.context, [AccountPermissions.MANAGE_USERS]+ ):+ loader = CustomerAttributesAllByCustomerTypeIdLoader(info.context)+ else:+ loader = CustomerAttributesVisibleInStorefrontByCustomerTypeIdLoader(+ info.context+ )+ return cls._load_customer_type_attributes(root, info, loader).then(+ with_attributes+ )++ @classmethod+ def resolve_assigned_attribute(+ cls, root: models.User, info: ResolveInfo, slug: str+ ):+ requestor = get_user_or_app_from_context(info.context)+ check_is_owner_or_has_one_of_perms(+ requestor, root, AccountPermissions.MANAGE_USERS+ )+ has_manage_users = one_of_permissions_or_auth_filter_required(+ info.context, [AccountPermissions.MANAGE_USERS]+ )++ def with_attributes(attributes: list[attribute_models.Attribute]):+ for attribute in attributes:+ if attribute.slug != slug:+ continue+ if not has_manage_users and not attribute.visible_in_storefront:+ return None+ return AssignedAttributeData(+ attribute=attribute, channel_slug=None, user_id=root.pk+ )+ return None++ loader = CustomerAttributesAllByCustomerTypeIdLoader(info.context)+ return cls._load_customer_type_attributes(root, info, loader).then(+ with_attributes+ )+class UserCountableConnection(CountableConnection):class Meta:diff --git a/saleor/graphql/attribute/bulk_mutations.py b/saleor/graphql/attribute/bulk_mutations.pyindex 0894dcaea5..62580a6c22 100644--- a/saleor/graphql/attribute/bulk_mutations.py+++ b/saleor/graphql/attribute/bulk_mutations.py@@ -40,7 +40,8 @@ class AttributeBulkDelete(ModelBulkDeleteMutation):"Deletes attributes.\n\nRequires one of the following permissions, ""depending on the type of each attribute: ""MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, "- "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes."+ "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, "+ "MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.")model = models.Attributeobject_type = Attribute@@ -126,7 +127,8 @@ class AttributeValueBulkDelete(ModelBulkDeleteMutation):"Deletes values of attributes.\n\nRequires one of the following ""permissions, depending on the type of each value's attribute: ""MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, "- "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes."+ "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, "+ "MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.")model = models.AttributeValueobject_type = AttributeValuediff --git a/saleor/graphql/attribute/dataloaders/assigned_attributes.py b/saleor/graphql/attribute/dataloaders/assigned_attributes.pyindex 4ed899bd7f..b112b525d5 100644--- a/saleor/graphql/attribute/dataloaders/assigned_attributes.py+++ b/saleor/graphql/attribute/dataloaders/assigned_attributes.py@@ -7,6 +7,7 @@ from django.db.models.query import QuerySetfrom promise import Promisefrom ....attribute.models import Attribute, AttributeValue+from ....attribute.models.customer import AssignedUserAttributeValuefrom ....attribute.models.page import AssignedPageAttributeValue, AttributePagefrom ....attribute.models.product import AssignedProductAttributeValue, AttributeProductfrom ....attribute.models.product_variant import (@@ -30,6 +31,7 @@ type PRODUCT_ID = inttype PRODUCT_TYPE_ID = inttype PAGE_ID = inttype VARIANT_ID = int+type USER_ID = inttype ATTRIBUTE_ID = inttype ATTRIBUTE_SLUG = strtype LIMIT = int | None@@ -654,6 +656,73 @@ class AttributeValuesByPageIdAndAttributeIdAndLimitLoader()+class AttributeValuesByUserIdAndAttributeIdAndLimitLoader(+ DataLoader[tuple[USER_ID, ATTRIBUTE_ID, LIMIT], list[AttributeValue]]+):+ context_key = "attribute_values_by_user_and_attribute"++ def batch_load(self, keys: Iterable[tuple[USER_ID, ATTRIBUTE_ID, LIMIT]]):+ limit_map = defaultdict(list)+ for user_id, attribute_id, limit in keys:+ limit_map[limit].append((user_id, attribute_id))++ attribute_value_id_to_fetch_map: dict[+ tuple[USER_ID, ATTRIBUTE_ID, LIMIT], list[int]+ ] = defaultdict(list)++ for limit, values in limit_map.items():+ user_ids = [val[0] for val in values]+ attribute_ids = [val[1] for val in values]++ assigned_attribute_values = AssignedUserAttributeValue.objects.using(+ self.database_connection_name+ ).annotate(attribute_id=F("value__attribute_id"))+ if limit is not None:+ assigned_attribute_values = assigned_attribute_values.annotate(+ row_num=Window(+ expression=RowNumber(),+ partition_by=[F("attribute_id"), F("user_id")],+ order_by=["sort_order", "pk"],+ )+ ).filter(row_num__lte=limit)+ assigned_attribute_values = assigned_attribute_values.filter(+ attribute_id__in=attribute_ids,+ user_id__in=user_ids,+ ).values_list("user_id", "value_id", "attribute_id")++ for user_id, value_id, attribute_id in assigned_attribute_values:+ attribute_value_id_to_fetch_map[(user_id, attribute_id, limit)].append(+ value_id+ )++ attribute_value_ids_to_fetch = set()+ for id_list in attribute_value_id_to_fetch_map.values():+ attribute_value_ids_to_fetch.update(id_list)++ def with_attribute_values(attribute_values: list[AttributeValue]):+ attribute_value_map = {av.id: av for av in attribute_values}+ response_data: defaultdict[+ tuple[USER_ID, ATTRIBUTE_ID, LIMIT], list[AttributeValue]+ ] = defaultdict(list)+ for (+ user_id,+ attribute_id,+ limit,+ ), value_ids in attribute_value_id_to_fetch_map.items():+ for value_id in value_ids:+ attr_val = attribute_value_map.get(value_id)+ if not attr_val:+ continue+ response_data[(user_id, attribute_id, limit)].append(attr_val)+ return [response_data.get(key, []) for key in keys]++ return (+ AttributeValueByIdLoader(self.context)+ .load_many(attribute_value_ids_to_fetch)+ .then(with_attribute_values)+ )++class AttributeValuesByVariantIdAndAttributeIdAndLimitLoader(DataLoader[tuple[VARIANT_ID, ATTRIBUTE_ID, LIMIT], list[AttributeValue]]):diff --git a/saleor/graphql/attribute/mutations/attribute_delete.py b/saleor/graphql/attribute/mutations/attribute_delete.pyindex ba248726ad..96b0392156 100644--- a/saleor/graphql/attribute/mutations/attribute_delete.py+++ b/saleor/graphql/attribute/mutations/attribute_delete.py@@ -39,7 +39,8 @@ class AttributeDelete(ModelDeleteMutation, ModelWithExtRefMutation):"Deletes an attribute.\n\nRequires one of the following permissions, ""depending on the attribute type: ""MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, "- "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes."+ "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, "+ "MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.")error_type_class = AttributeErrorerror_type_field = "attribute_errors"diff --git a/saleor/graphql/attribute/mutations/attribute_reorder_values.py b/saleor/graphql/attribute/mutations/attribute_reorder_values.pyindex c840b90068..785028d4d7 100644--- a/saleor/graphql/attribute/mutations/attribute_reorder_values.py+++ b/saleor/graphql/attribute/mutations/attribute_reorder_values.py@@ -31,7 +31,8 @@ class AttributeReorderValues(BaseMutation):"Reorder the values of an attribute.\n\nRequires one of the following ""permissions, depending on the attribute type: ""MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, "- "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes."+ "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, "+ "MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.")doc_category = DOC_CATEGORY_ATTRIBUTESerror_type_class = AttributeErrordiff --git a/saleor/graphql/attribute/mutations/attribute_update.py b/saleor/graphql/attribute/mutations/attribute_update.pyindex 4f40bdc300..456d4d2d74 100644--- a/saleor/graphql/attribute/mutations/attribute_update.py+++ b/saleor/graphql/attribute/mutations/attribute_update.py@@ -128,7 +128,8 @@ class AttributeUpdate(AttributeMixin, ModelWithExtRefMutation):"Updates attribute.\n\nRequires one of the following permissions, ""depending on the attribute type: ""MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, "- "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes."+ "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, "+ "MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.")error_type_class = AttributeErrorerror_type_field = "attribute_errors"diff --git a/saleor/graphql/attribute/mutations/attribute_value_create.py b/saleor/graphql/attribute/mutations/attribute_value_create.pyindex 1c825edd27..c65b43d5da 100644--- a/saleor/graphql/attribute/mutations/attribute_value_create.py+++ b/saleor/graphql/attribute/mutations/attribute_value_create.py@@ -44,7 +44,8 @@ class AttributeValueCreate(AttributeMixin, DeprecatedModelMutation):"Creates a value for an attribute.\n\nRequires one of the following ""permissions, depending on the attribute type: ""MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, "- "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes."+ "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, "+ "MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.")error_type_class = AttributeErrorerror_type_field = "attribute_errors"diff --git a/saleor/graphql/attribute/mutations/attribute_value_delete.py b/saleor/graphql/attribute/mutations/attribute_value_delete.pyindex f6340593de..01e570f612 100644--- a/saleor/graphql/attribute/mutations/attribute_value_delete.py+++ b/saleor/graphql/attribute/mutations/attribute_value_delete.py@@ -42,7 +42,8 @@ class AttributeValueDelete(ModelDeleteMutation, ModelWithExtRefMutation):"Deletes a value of an attribute.\n\nRequires one of the following ""permissions, depending on the type of the value's attribute: ""MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, "- "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes."+ "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, "+ "MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.")error_type_class = AttributeErrorerror_type_field = "attribute_errors"diff --git a/saleor/graphql/attribute/mutations/attribute_value_update.py b/saleor/graphql/attribute/mutations/attribute_value_update.pyindex 104af63e56..2e33c62cd9 100644--- a/saleor/graphql/attribute/mutations/attribute_value_update.py+++ b/saleor/graphql/attribute/mutations/attribute_value_update.py@@ -46,7 +46,8 @@ class AttributeValueUpdate(AttributeValueCreate, ModelWithExtRefMutation):"Updates value of an attribute.\n\nRequires one of the following ""permissions, depending on the type of the value's attribute: ""MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, "- "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes."+ "MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, "+ "MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.")error_type_class = AttributeErrorerror_type_field = "attribute_errors"diff --git a/saleor/graphql/attribute/mutations/permissions.py b/saleor/graphql/attribute/mutations/permissions.pyindex 39c940afd8..c829432483 100644--- a/saleor/graphql/attribute/mutations/permissions.py+++ b/saleor/graphql/attribute/mutations/permissions.py@@ -4,6 +4,7 @@ from ....attribute import AttributeTypefrom ....core.exceptions import PermissionDeniedfrom ....permission.enums import (BasePermissionEnum,+ CustomerTypePermissions,PageTypePermissions,ProductTypePermissions,)@@ -14,6 +15,9 @@ ATTRIBUTE_TYPE_PERMISSION_MAP: dict[str, BasePermissionEnum] = {ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES),AttributeType.PAGE_TYPE: PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,+ AttributeType.CUSTOMER_TYPE: (+ CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES+ ),}diff --git a/saleor/graphql/attribute/shared_filters.py b/saleor/graphql/attribute/shared_filters.pyindex 4377bf96ef..348f0511d0 100644--- a/saleor/graphql/attribute/shared_filters.py+++ b/saleor/graphql/attribute/shared_filters.py@@ -1,7 +1,8 @@+from collections.abc import Callablefrom typing import Literal, TypedDict, castimport graphene-from django.db.models import Exists, OuterRef, QuerySet+from django.db.models import Exists, OuterRef, Q, QuerySetfrom graphql import GraphQLErrorfrom ...attribute import AttributeInputType@@ -566,3 +567,339 @@ def validate_attribute_value_input(attributes: list[dict], db_connection_name: s"Provided 'value' do not match the attribute input type."))+++# Builds an expression matching objects of the filtered queryset that have+# any of the given attribute values assigned. This is the only entity-specific+# part of the attribute `where` filtering - each entity provides its own+# implementation that joins its assigned-value model (and applies the+# type-membership guard skipping values of attributes that are no longer+# assigned to the object's type).+GetAssignedAttributeExpression = Callable[[QuerySet[AttributeValue], str], Q]+++def filter_by_slug_or_name(+ attr_id: int | None,+ attr_value: dict,+ db_connection_name: str,+ get_assigned_attribute_expression: GetAssignedAttributeExpression,+):+ attribute_values = get_attribute_values_by_slug_or_name_value(+ attr_id=attr_id,+ attr_value=attr_value,+ db_connection_name=db_connection_name,+ )+ return get_assigned_attribute_expression(attribute_values, db_connection_name)+++def filter_by_numeric_attribute(+ attr_id: int | None,+ numeric_value: dict[str, Number | list[Number] | dict[str, Number]],+ db_connection_name: str,+ get_assigned_attribute_expression: GetAssignedAttributeExpression,+):+ attribute_values = get_attribute_values_by_numeric_value(+ attr_id=attr_id,+ numeric_value=numeric_value,+ db_connection_name=db_connection_name,+ )+ return get_assigned_attribute_expression(attribute_values, db_connection_name)+++def filter_by_boolean_attribute(+ attr_id: int | None,+ boolean_value: bool,+ db_connection_name: str,+ get_assigned_attribute_expression: GetAssignedAttributeExpression,+):+ attribute_values = get_attribute_values_by_boolean_value(+ attr_id=attr_id,+ boolean_value=boolean_value,+ db_connection_name=db_connection_name,+ )+ return get_assigned_attribute_expression(attribute_values, db_connection_name)+++def filter_by_date_attribute(+ attr_id: int | None,+ date_value: dict[str, str],+ db_connection_name: str,+ get_assigned_attribute_expression: GetAssignedAttributeExpression,+):+ attribute_values = get_attribute_values_by_date_value(+ attr_id=attr_id,+ date_value=date_value,+ db_connection_name=db_connection_name,+ )+ return get_assigned_attribute_expression(attribute_values, db_connection_name)+++def filter_by_date_time_attribute(+ attr_id: int | None,+ date_value: dict[str, str],+ db_connection_name: str,+ get_assigned_attribute_expression: GetAssignedAttributeExpression,+):+ attribute_values = get_attribute_values_by_date_time_value(+ attr_id=attr_id,+ date_value=date_value,+ db_connection_name=db_connection_name,+ )+ return get_assigned_attribute_expression(attribute_values, db_connection_name)+++def _filter_contains_single_expression(+ attr_id: int | None,+ db_connection_name: str,+ referenced_attr_values: QuerySet[AttributeValue],+ get_assigned_attribute_expression: GetAssignedAttributeExpression,+):+ if attr_id:+ referenced_attr_values = referenced_attr_values.filter(+ attribute_id=attr_id,+ )+ return get_assigned_attribute_expression(referenced_attr_values, db_connection_name)+++def _filter_by_contains_referenced_identifiers(+ attr_id: int | None,+ attr_value: CONTAINS_TYPING,+ db_connection_name: str,+ get_referenced_attr_values: Callable[[list[str], str], QuerySet[AttributeValue]],+ get_assigned_attribute_expression: GetAssignedAttributeExpression,+):+ """Build an expression filtering objects by referenced-object identifiers.++ - If `contains_all` is provided, only objects that reference all of the+ specified referenced objects will match.+ - If `contains_any` is provided, objects that reference at least one of+ the specified referenced objects will match.+ """+ contains_all = attr_value.get("contains_all")+ contains_any = attr_value.get("contains_any")++ if contains_all:+ expression = Q()+ for identifier in contains_all:+ referenced_attr_values = get_referenced_attr_values(+ [identifier], db_connection_name+ )+ expression &= _filter_contains_single_expression(+ attr_id=attr_id,+ db_connection_name=db_connection_name,+ referenced_attr_values=referenced_attr_values,+ get_assigned_attribute_expression=get_assigned_attribute_expression,+ )+ return expression++ if contains_any:+ referenced_attr_values = get_referenced_attr_values(+ contains_any, db_connection_name+ )+ return _filter_contains_single_expression(+ attr_id=attr_id,+ db_connection_name=db_connection_name,+ referenced_attr_values=referenced_attr_values,+ get_assigned_attribute_expression=get_assigned_attribute_expression,+ )+ return Q()+++_REFERENCED_ID_LOOKUP_MAP: dict[+ str, Callable[[list[int], str], QuerySet[AttributeValue]]+] = {+ "Page": get_attribute_values_by_referenced_page_ids,+ "Product": get_attribute_values_by_referenced_product_ids,+ "ProductVariant": get_attribute_values_by_referenced_variant_ids,+ "Category": get_attribute_values_by_referenced_category_ids,+ "Collection": get_attribute_values_by_referenced_collection_ids,+}+++def filter_by_contains_referenced_object_ids(+ attr_id: int | None,+ attr_value: CONTAINS_TYPING,+ db_connection_name: str,+ get_assigned_attribute_expression: GetAssignedAttributeExpression,+) -> Q:+ contains_all = attr_value.get("contains_all")+ contains_any = attr_value.get("contains_any")++ grouped_ids = clean_up_referenced_global_ids(contains_any or contains_all or [])++ expression = Q()+ if contains_all:+ for type_name, get_referenced_attr_values in _REFERENCED_ID_LOOKUP_MAP.items():+ for object_id in grouped_ids[type_name]:+ referenced_attr_values = get_referenced_attr_values(+ [object_id], db_connection_name+ )+ expression &= _filter_contains_single_expression(+ attr_id=attr_id,+ db_connection_name=db_connection_name,+ referenced_attr_values=referenced_attr_values,+ get_assigned_attribute_expression=(+ get_assigned_attribute_expression+ ),+ )+ return expression+ if contains_any:+ for type_name, get_referenced_attr_values in _REFERENCED_ID_LOOKUP_MAP.items():+ if object_ids := grouped_ids[type_name]:+ referenced_attr_values = get_referenced_attr_values(+ list(object_ids), db_connection_name+ )+ expression |= _filter_contains_single_expression(+ attr_id=attr_id,+ db_connection_name=db_connection_name,+ referenced_attr_values=referenced_attr_values,+ get_assigned_attribute_expression=(+ get_assigned_attribute_expression+ ),+ )+ return expression+ return Q()+++_REFERENCED_SLUG_LOOKUP_MAP: dict[+ Literal[+ "page_slugs",+ "product_slugs",+ "product_variant_skus",+ "category_slugs",+ "collection_slugs",+ ],+ Callable[[list[str], str], QuerySet[AttributeValue]],+] = {+ "page_slugs": get_attribute_values_by_referenced_page_slugs,+ "product_slugs": get_attribute_values_by_referenced_product_slugs,+ "product_variant_skus": get_attribute_values_by_referenced_variant_skus,+ "category_slugs": get_attribute_values_by_referenced_category_slugs,+ "collection_slugs": get_attribute_values_by_referenced_collection_slugs,+}+++def filter_objects_by_reference_attributes(+ attr_id: int | None,+ attr_value: dict[+ Literal[+ "referenced_ids",+ "page_slugs",+ "product_slugs",+ "product_variant_skus",+ "category_slugs",+ "collection_slugs",+ ],+ CONTAINS_TYPING,+ ],+ db_connection_name: str,+ get_assigned_attribute_expression: GetAssignedAttributeExpression,+):+ filter_expression = Q()++ if "referenced_ids" in attr_value:+ filter_expression &= filter_by_contains_referenced_object_ids(+ attr_id,+ attr_value["referenced_ids"],+ db_connection_name,+ get_assigned_attribute_expression,+ )+ for key, get_referenced_attr_values in _REFERENCED_SLUG_LOOKUP_MAP.items():+ if key in attr_value:+ filter_expression &= _filter_by_contains_referenced_identifiers(+ attr_id,+ attr_value[key],+ db_connection_name,+ get_referenced_attr_values,+ get_assigned_attribute_expression,+ )+ return filter_expression+++def filter_objects_by_attributes(+ qs,+ value,+ get_assigned_attribute_expression: GetAssignedAttributeExpression,+):+ attribute_slugs = {+ attr_filter["slug"] for attr_filter in value if "slug" in attr_filter+ }+ attributes_map = {+ attr.slug: attr+ for attr in Attribute.objects.using(qs.db).filter(slug__in=attribute_slugs)+ }+ if len(attribute_slugs) != len(attributes_map.keys()):+ # Filter over non existing attribute+ return qs.none()++ attr_filter_expression = Q()++ attr_without_values_input = []+ for attr_filter in value:+ if "slug" in attr_filter and "value" not in attr_filter:+ attr_without_values_input.append(attributes_map[attr_filter["slug"]])++ if attr_without_values_input:+ atr_value_qs = AttributeValue.objects.using(qs.db).filter(+ attribute_id__in=[attr.id for attr in attr_without_values_input]+ )+ attr_filter_expression = get_assigned_attribute_expression(atr_value_qs, qs.db)++ for attr_filter in value:+ attr_value = attr_filter.get("value")+ if not attr_value:+ # attrs without value input are handled separately+ continue++ attr_id = None+ if attr_slug := attr_filter.get("slug"):+ attr = attributes_map[attr_slug]+ attr_id = attr.id++ attr_value = attr_filter["value"]++ if "slug" in attr_value or "name" in attr_value:+ attr_filter_expression &= filter_by_slug_or_name(+ attr_id,+ attr_value,+ qs.db,+ get_assigned_attribute_expression,+ )+ elif "numeric" in attr_value:+ attr_filter_expression &= filter_by_numeric_attribute(+ attr_id,+ attr_value["numeric"],+ qs.db,+ get_assigned_attribute_expression,+ )+ elif "boolean" in attr_value:+ attr_filter_expression &= filter_by_boolean_attribute(+ attr_id,+ attr_value["boolean"],+ qs.db,+ get_assigned_attribute_expression,+ )+ elif "date" in attr_value:+ attr_filter_expression &= filter_by_date_attribute(+ attr_id,+ attr_value["date"],+ qs.db,+ get_assigned_attribute_expression,+ )+ elif "date_time" in attr_value:+ attr_filter_expression &= filter_by_date_time_attribute(+ attr_id,+ attr_value["date_time"],+ qs.db,+ get_assigned_attribute_expression,+ )+ elif "reference" in attr_value:+ attr_filter_expression &= filter_objects_by_reference_attributes(+ attr_id,+ attr_value["reference"],+ qs.db,+ get_assigned_attribute_expression,+ )+ if attr_filter_expression != Q():+ return qs.filter(attr_filter_expression)+ return qs.none()diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_create.pyindex 74766fd734..f7daec1e25 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_create.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_create.py@@ -2,6 +2,7 @@ from unittest.mock import patchimport graphene+from .....attribute import AttributeTypefrom .....attribute.error_codes import AttributeBulkCreateErrorCodefrom .....attribute.models import Attribute, AttributeValuefrom ....core.enums import ErrorPolicyEnum@@ -853,3 +854,61 @@ def test_attribute_type_without_mapped_permission_returns_error(f"{AttributeTypeEnum.PRODUCT_TYPE.value}.")assert Attribute.objects.filter(name=attribute_name).exists() is False+++def test_attribute_bulk_create_customer_attribute(+ staff_api_client, permission_manage_customer_types_and_attributes+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ attribute_name = "Loyalty level"+ attributes = [+ {"name": attribute_name, "type": AttributeTypeEnum.CUSTOMER_TYPE.name}+ ]++ # when+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_CREATE_MUTATION,+ {"attributes": attributes},+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkCreate"]+ assert data["count"] == 1+ assert data["results"][0]["attribute"]["name"] == attribute_name++ attribute = Attribute.objects.get(slug="loyalty-level")+ assert attribute.type == AttributeType.CUSTOMER_TYPE+++def test_attribute_bulk_create_customer_attribute_without_permission(+ staff_api_client,+ permission_manage_page_types_and_attributes,+ permission_manage_product_types_and_attributes,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_page_types_and_attributes,+ permission_manage_product_types_and_attributes,+ )+ attributes = [+ {"name": "Loyalty level", "type": AttributeTypeEnum.CUSTOMER_TYPE.name}+ ]++ # when+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_CREATE_MUTATION,+ {"attributes": attributes},+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkCreate"]+ assert data["count"] == 0+ errors = data["results"][0]["errors"]+ assert len(errors) == 1+ assert errors[0]["code"] == AttributeBulkCreateErrorCode.REQUIRED.name+ assert Attribute.objects.filter(slug="loyalty-level").exists() is Falsediff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.pyindex 219bbe0894..6efa4e38f8 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.py@@ -1198,3 +1198,75 @@ def test_attribute_type_without_mapped_permission_returns_error()color_attribute.refresh_from_db(fields=("name",))assert color_attribute.name == original_name+++def test_attribute_bulk_update_customer_attribute(+ staff_api_client,+ permission_manage_customer_types_and_attributes,+ loyalty_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_customer_types_and_attributes+ )+ new_name = "Membership tier"+ attributes = [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ ),+ "fields": {"name": new_name},+ }+ ]++ # when+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]+ assert data["count"] == 1+ assert data["results"][0]["attribute"]["name"] == new_name+ loyalty_customer_attribute.refresh_from_db()+ assert loyalty_customer_attribute.name == new_name+++def test_attribute_bulk_update_customer_attribute_without_permission(+ staff_api_client,+ permission_manage_page_types_and_attributes,+ permission_manage_product_types_and_attributes,+ loyalty_customer_attribute,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_page_types_and_attributes,+ permission_manage_product_types_and_attributes,+ )+ old_name = loyalty_customer_attribute.name+ attributes = [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", loyalty_customer_attribute.pk+ ),+ "fields": {"name": "Membership tier"},+ }+ ]++ # when+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_UPDATE_MUTATION,+ {"attributes": attributes},+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeBulkUpdate"]+ assert data["count"] == 0+ errors = data["results"][0]["errors"]+ assert len(errors) == 1+ assert errors[0]["code"] == AttributeBulkUpdateErrorCode.REQUIRED.name+ loyalty_customer_attribute.refresh_from_db()+ assert loyalty_customer_attribute.name == old_namediff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_create.pyindex 212791733e..159801433f 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py@@ -7,13 +7,14 @@ from django.utils.functional import SimpleLazyObjectfrom django.utils.text import slugifyfrom freezegun import freeze_time+from .....attribute import AttributeTypefrom .....attribute.error_codes import AttributeErrorCodefrom .....attribute.models import Attributefrom .....core.utils.json_serializer import CustomJsonEncoderfrom .....webhook.event_types import WebhookEventAsyncTypefrom .....webhook.payloads import generate_meta, generate_requestorfrom ....core.enums import MeasurementUnitsEnum-from ....tests.utils import get_graphql_content+from ....tests.utils import assert_no_permission, get_graphql_contentfrom ...enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnumCREATE_ATTRIBUTE_MUTATION = """@@ -1864,3 +1865,67 @@ def test_create_attribute_with_reference_types_product_types_provided_for_page_rassert len(errors) == 1assert errors[0]["field"] == "referenceTypes"assert errors[0]["code"] == AttributeErrorCode.INVALID.name+++def test_create_customer_attribute(+ staff_api_client, permission_manage_customer_types_and_attributes+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ attribute_name = "Loyalty level"+ variables = {+ "input": {+ "name": attribute_name,+ "type": AttributeTypeEnum.CUSTOMER_TYPE.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[permission_manage_customer_types_and_attributes],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeCreate"]+ assert data["errors"] == []+ assert data["attribute"]["name"] == attribute_name+ assert data["attribute"]["slug"] == slugify(attribute_name)+ assert data["attribute"]["type"] == AttributeTypeEnum.CUSTOMER_TYPE.name++ attribute = Attribute.objects.get(slug=slugify(attribute_name))+ assert attribute.type == AttributeType.CUSTOMER_TYPE+++def test_create_customer_attribute_without_customer_type_permission(+ staff_api_client,+ permission_manage_page_types_and_attributes,+ permission_manage_product_types_and_attributes,+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ attribute_name = "Loyalty level"+ variables = {+ "input": {+ "name": attribute_name,+ "type": AttributeTypeEnum.CUSTOMER_TYPE.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[+ permission_manage_page_types_and_attributes,+ permission_manage_product_types_and_attributes,+ ],+ )++ # then+ assert_no_permission(response)+ assert not Attribute.objects.filter(slug=slugify(attribute_name)).exists()diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py b/saleor/graphql/attribute/tests/mutations/test_attribute_delete.pyindex 81d5173524..4b2817a667 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py@@ -359,3 +359,72 @@ def test_attribute_type_without_mapped_permission_is_denied(color_attribute._meta.model.objects.filter(pk=color_attribute.pk).exists()is True)+++def test_delete_customer_attribute_with_customer_type_permission(+ staff_api_client,+ loyalty_customer_attribute,+ permission_manage_customer_types_and_attributes,+):+ # given+ attribute = loyalty_customer_attribute+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)+ variables = {"id": node_id}++ # when+ response = staff_api_client.post_graphql(+ ATTRIBUTE_DELETE_MUTATION,+ variables,+ permissions=[permission_manage_customer_types_and_attributes],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeDelete"]+ assert data["attribute"]["id"] == variables["id"]+ with pytest.raises(attribute._meta.model.DoesNotExist):+ attribute.refresh_from_db()+++def test_delete_customer_attribute_without_customer_type_permission(+ staff_api_client,+ loyalty_customer_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ attribute = loyalty_customer_attribute+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)+ variables = {"id": node_id}++ # when+ response = staff_api_client.post_graphql(+ ATTRIBUTE_DELETE_MUTATION,+ variables,+ permissions=[permission_manage_product_types_and_attributes],+ )++ # then+ assert_no_permission(response)+ assert attribute._meta.model.objects.filter(pk=attribute.pk).exists()+++def test_delete_product_attribute_with_only_customer_type_permission(+ staff_api_client,+ color_attribute,+ permission_manage_customer_types_and_attributes,+):+ # given+ attribute = color_attribute+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)+ variables = {"id": node_id}++ # when+ response = staff_api_client.post_graphql(+ ATTRIBUTE_DELETE_MUTATION,+ variables,+ permissions=[permission_manage_customer_types_and_attributes],+ )++ # then+ assert_no_permission(response)+ assert attribute._meta.model.objects.filter(pk=attribute.pk).exists()diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.py b/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.pyindex f01171b950..102fe628ba 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.py@@ -311,6 +311,34 @@ def test_sort_values_trigger_webhook("permission_manage_page_types_and_attributes",True,),+ (+ "Customer attribute w/ customer permission should be allowed",+ "staff_api_client",+ "loyalty_customer_attribute",+ "permission_manage_customer_types_and_attributes",+ True,+ ),+ (+ "Customer attribute w/ legacy product permission should be rejected",+ "staff_api_client",+ "loyalty_customer_attribute",+ "permission_manage_product_types_and_attributes",+ False,+ ),+ (+ "Customer attribute w/ page permission should be rejected",+ "staff_api_client",+ "loyalty_customer_attribute",+ "permission_manage_page_types_and_attributes",+ False,+ ),+ (+ "Product attribute w/ customer permission should be rejected",+ "staff_api_client",+ "color_attribute",+ "permission_manage_customer_types_and_attributes",+ False,+ ),],)def test_authorization(diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_update.pyindex 6c44bd7881..2c3b3537a9 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py@@ -1345,3 +1345,78 @@ def test_update_product_attribute_without_product_type_permission(# thenassert_no_permission(response)+++def test_update_customer_attribute_with_customer_type_permission(+ staff_api_client,+ loyalty_customer_attribute,+ permission_manage_customer_types_and_attributes,+):+ # given+ attribute = loyalty_customer_attribute+ name = "Updated customer attribute name"+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)+ variables = {"id": node_id, "input": {"name": name}}++ # when+ response = staff_api_client.post_graphql(+ UPDATE_ATTRIBUTE_MUTATION,+ variables,+ permissions=[permission_manage_customer_types_and_attributes],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeUpdate"]+ assert not data["errors"]+ attribute.refresh_from_db()+ assert data["attribute"]["name"] == name+ assert attribute.name == name+++def test_update_customer_attribute_without_customer_type_permission(+ staff_api_client,+ loyalty_customer_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ attribute = loyalty_customer_attribute+ original_name = attribute.name+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)+ variables = {"id": node_id, "input": {"name": "Updated customer attribute name"}}++ # when+ response = staff_api_client.post_graphql(+ UPDATE_ATTRIBUTE_MUTATION,+ variables,+ permissions=[permission_manage_product_types_and_attributes],+ )++ # then+ assert_no_permission(response)+ attribute.refresh_from_db()+ assert attribute.name == original_name+++def test_update_product_attribute_with_only_customer_type_permission(+ staff_api_client,+ color_attribute,+ permission_manage_customer_types_and_attributes,+):+ # given+ attribute = color_attribute+ original_name = attribute.name+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)+ variables = {"id": node_id, "input": {"name": "Updated product attribute name"}}++ # when+ response = staff_api_client.post_graphql(+ UPDATE_ATTRIBUTE_MUTATION,+ variables,+ permissions=[permission_manage_customer_types_and_attributes],+ )++ # then+ assert_no_permission(response)+ attribute.refresh_from_db()+ assert attribute.name == original_namediff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.pyindex 5ecf85d0c3..1464572081 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.py@@ -502,6 +502,35 @@ def test_create_attribute_value_with_non_unique_external_reference("permission_manage_page_types_and_attributes",True,),+ (+ "Customer attribute w/ customer permission should be allowed",+ "staff_api_client",+ "loyalty_customer_attribute",+ "permission_manage_customer_types_and_attributes",+ True,+ ),+ (+ "Customer attribute w/ product permission should be rejected",+ "staff_api_client",+ "loyalty_customer_attribute",+ "permission_manage_product_types_and_attributes",+ False,+ ),+ (+ "Customer attribute w/ legacy manage products permission "+ "should be rejected",+ "staff_api_client",+ "loyalty_customer_attribute",+ "permission_manage_products",+ False,+ ),+ (+ "Product attribute w/ customer permission should be rejected",+ "staff_api_client",+ "color_attribute",+ "permission_manage_customer_types_and_attributes",+ False,+ ),],)def test_authorization(diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.pyindex 1ee3f88a5b..4e3c69cb3e 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py@@ -399,6 +399,34 @@ def test_delete_attribute_value_by_external_reference_not_existing("permission_manage_page_types_and_attributes",True,),+ (+ "Customer attribute value w/ customer permission should be allowed",+ "staff_api_client",+ "loyalty_customer_attribute",+ "permission_manage_customer_types_and_attributes",+ True,+ ),+ (+ "Customer attribute value w/ legacy product permission should be rejected",+ "staff_api_client",+ "loyalty_customer_attribute",+ "permission_manage_product_types_and_attributes",+ False,+ ),+ (+ "Customer attribute value w/ page permission should be rejected",+ "staff_api_client",+ "loyalty_customer_attribute",+ "permission_manage_page_types_and_attributes",+ False,+ ),+ (+ "Product attribute value w/ customer permission should be rejected",+ "staff_api_client",+ "color_attribute",+ "permission_manage_customer_types_and_attributes",+ False,+ ),],)def test_authorization(diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.pyindex ce38518dd3..aaa936be1c 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py@@ -706,6 +706,34 @@ def test_update_attribute_value_with_non_unique_external_reference("permission_manage_page_types_and_attributes",True,),+ (+ "Customer attribute value w/ customer permission should be allowed",+ "staff_api_client",+ "loyalty_customer_attribute",+ "permission_manage_customer_types_and_attributes",+ True,+ ),+ (+ "Customer attribute value w/ legacy product permission should be rejected",+ "staff_api_client",+ "loyalty_customer_attribute",+ "permission_manage_product_types_and_attributes",+ False,+ ),+ (+ "Customer attribute value w/ page permission should be rejected",+ "staff_api_client",+ "loyalty_customer_attribute",+ "permission_manage_page_types_and_attributes",+ False,+ ),+ (+ "Product attribute value w/ customer permission should be rejected",+ "staff_api_client",+ "color_attribute",+ "permission_manage_customer_types_and_attributes",+ False,+ ),],)def test_authorization(diff --git a/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py b/saleor/graphql/attribute/tests/mutations/test_bulk_delete.pyindex d1987e8beb..e485b55a3d 100644--- a/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py@@ -363,6 +363,72 @@ def test_delete_attribute_values_search_document_updated(],True,),+ (+ "Customer attributes w/ customer permission should be allowed",+ "staff_api_client",+ ["customer_type_attribute_list"],+ ["permission_manage_customer_types_and_attributes"],+ True,+ ),+ (+ "Customer attributes w/ product permission should be rejected",+ "staff_api_client",+ ["customer_type_attribute_list"],+ ["permission_manage_product_types_and_attributes"],+ False,+ ),+ (+ "Customer attributes w/ legacy page permission should be rejected",+ "staff_api_client",+ ["customer_type_attribute_list"],+ ["permission_manage_page_types_and_attributes"],+ False,+ ),+ (+ "Product attributes w/ customer permission should be rejected",+ "staff_api_client",+ ["product_type_attribute_list"],+ ["permission_manage_customer_types_and_attributes"],+ False,+ ),+ (+ "Mixed attributes w/ legacy page permission only should be rejected "+ "when customer attributes are included",+ "staff_api_client",+ ["product_type_attribute_list", "customer_type_attribute_list"],+ ["permission_manage_page_types_and_attributes"],+ False,+ ),+ (+ "Mixed attributes w/ page and customer permissions should be rejected "+ "when product attributes are included",+ "staff_api_client",+ [+ "product_type_attribute_list",+ "page_type_attribute_list",+ "customer_type_attribute_list",+ ],+ [+ "permission_manage_page_types_and_attributes",+ "permission_manage_customer_types_and_attributes",+ ],+ False,+ ),+ (+ "Mixed attributes w/ every matching permission should be allowed",+ "staff_api_client",+ [+ "product_type_attribute_list",+ "page_type_attribute_list",+ "customer_type_attribute_list",+ ],+ [+ "permission_manage_product_types_and_attributes",+ "permission_manage_page_types_and_attributes",+ "permission_manage_customer_types_and_attributes",+ ],+ True,+ ),],)def test_delete_attributes_authorization(@@ -489,6 +555,64 @@ def test_delete_attributes_authorization(],True,),+ (+ "Customer attribute values w/ customer permission should be allowed",+ "staff_api_client",+ ["loyalty_customer_attribute"],+ ["permission_manage_customer_types_and_attributes"],+ True,+ ),+ (+ "Customer attribute values w/ product permission should be rejected",+ "staff_api_client",+ ["loyalty_customer_attribute"],+ ["permission_manage_product_types_and_attributes"],+ False,+ ),+ (+ "Customer attribute values w/ legacy page permission should be rejected",+ "staff_api_client",+ ["loyalty_customer_attribute"],+ ["permission_manage_page_types_and_attributes"],+ False,+ ),+ (+ "Product attribute values w/ customer permission should be rejected",+ "staff_api_client",+ ["color_attribute"],+ ["permission_manage_customer_types_and_attributes"],+ False,+ ),+ (+ "Mixed attribute values w/ legacy page permission only should be "+ "rejected when customer attribute values are included",+ "staff_api_client",+ ["color_attribute", "loyalty_customer_attribute"],+ ["permission_manage_page_types_and_attributes"],+ False,+ ),+ (+ "Mixed attribute values w/ page and customer permissions should be "+ "rejected when product attribute values are included",+ "staff_api_client",+ ["color_attribute", "size_page_attribute", "loyalty_customer_attribute"],+ [+ "permission_manage_page_types_and_attributes",+ "permission_manage_customer_types_and_attributes",+ ],+ False,+ ),+ (+ "Mixed attribute values w/ every matching permission should be allowed",+ "staff_api_client",+ ["color_attribute", "size_page_attribute", "loyalty_customer_attribute"],+ [+ "permission_manage_product_types_and_attributes",+ "permission_manage_page_types_and_attributes",+ "permission_manage_customer_types_and_attributes",+ ],+ True,+ ),],)def test_delete_attribute_values_authorization(diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_where.py b/saleor/graphql/attribute/tests/queries/test_attribute_where.pyindex 0ffc9dee03..14cbe0af7a 100644--- a/saleor/graphql/attribute/tests/queries/test_attribute_where.py+++ b/saleor/graphql/attribute/tests/queries/test_attribute_where.py@@ -2140,3 +2140,19 @@ def test_attributes_filter_by_choices_search(assert len(choices) == len(indexes)returned_choices = {node["node"]["name"] for node in choices}assert returned_choices == {values[index].name for index in indexes}+++def test_attributes_filter_by_customer_type(+ api_client, color_attribute, loyalty_customer_attribute+):+ # given+ variables = {"where": {"type": {"eq": AttributeTypeEnum.CUSTOMER_TYPE.name}}}++ # when+ response = api_client.post_graphql(ATTRIBUTES_WHERE_QUERY, variables)++ # then+ data = get_graphql_content(response)+ nodes = data["data"]["attributes"]["edges"]+ assert len(nodes) == 1+ assert nodes[0]["node"]["slug"] == loyalty_customer_attribute.slugdiff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.pyindex 7b75a263cf..af20a3077a 100644--- a/saleor/graphql/attribute/tests/test_utils.py+++ b/saleor/graphql/attribute/tests/test_utils.py@@ -10,6 +10,7 @@ from graphql import GraphQLErrorfrom ....attribute import AttributeInputTypefrom ....attribute.models import AttributeValuefrom ....attribute.utils import associate_attribute_values_to_instance+from ....page.error_codes import PageErrorCodefrom ....product.error_codes import ProductErrorCodefrom ..enums import AttributeValueBulkActionEnumfrom ..shared_filters import validate_attribute_value_input@@ -55,7 +56,6 @@ def test_clean_input_for_product(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -87,7 +87,6 @@ def test_clean_attribute_input_for_product_no_values_given(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -132,7 +131,6 @@ def test_clean_attribute_input_for_product_too_many_values_given(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -176,7 +174,6 @@ def test_clean_attribute_input_for_product_empty_values_given(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -214,7 +211,6 @@ def test_clean_attribute_input_for_product_lack_of_required_attribute(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=True,)@@ -258,7 +254,6 @@ def test_clean_attribute_input_for_product_creation_multiple_errors(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -307,7 +302,7 @@ def test_clean_attribute_input_for_page(AttributeAssignmentMixin.clean_input(input_data,page_type.page_attributes.all(),- is_page_attributes=True,+ error_class=PageErrorCode,creation=creation,)@@ -339,7 +334,7 @@ def test_clean_attribute_input_for_page_no_values_given(AttributeAssignmentMixin.clean_input(input_data,page_type.page_attributes.all(),- is_page_attributes=True,+ error_class=PageErrorCode,creation=creation,)@@ -384,7 +379,7 @@ def test_clean_attribute_input_for_page_too_many_values_given(AttributeAssignmentMixin.clean_input(input_data,page_type.page_attributes.all(),- is_page_attributes=True,+ error_class=PageErrorCode,creation=creation,)@@ -428,7 +423,7 @@ def test_clean_attribute_input_for_page_empty_values_given(AttributeAssignmentMixin.clean_input(input_data,page_type.page_attributes.all(),- is_page_attributes=True,+ error_class=PageErrorCode,creation=creation,)@@ -466,7 +461,7 @@ def test_clean_attribute_input_for_page_lack_of_required_attribute(# whenwith pytest.raises(ValidationError) as exc_info:AttributeAssignmentMixin.clean_input(- input_data, page_attributes, is_page_attributes=True, creation=True+ input_data, page_attributes, error_class=PageErrorCode, creation=True)# then@@ -507,7 +502,7 @@ def test_clean_attribute_input_for_page_multiple_errors(AttributeAssignmentMixin.clean_input(input_data,page_type.page_attributes.all(),- is_page_attributes=True,+ error_class=PageErrorCode,creation=True,)@@ -556,7 +551,6 @@ def test_clean_variant_attribute_input(AttributeAssignmentMixin.clean_input(input_data,product_type.variant_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -588,7 +582,6 @@ def test_clean_variant_attribute_input_no_values_given(AttributeAssignmentMixin.clean_input(input_data,product_type.variant_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -633,7 +626,6 @@ def test_clean_variant_attribute_duplicated_values_given(AttributeAssignmentMixin.clean_input(input_data,product_type.variant_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -676,7 +668,6 @@ def test_clean_variant_attribute_input_empty_values_given(AttributeAssignmentMixin.clean_input(input_data,product_type.variant_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -710,7 +701,6 @@ def test_clean_variant_attribute_too_many_values_given(AttributeAssignmentMixin.clean_input(input_data,product_type.variant_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -752,7 +742,6 @@ def test_clean_variant_attribute_empty_values_given(AttributeAssignmentMixin.clean_input(input_data,product_type.variant_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -796,7 +785,6 @@ def test_clean_variant_attribute_input_multiple_errors(AttributeAssignmentMixin.clean_input(input_data,product_type.variant_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -846,7 +834,6 @@ def test_clean_attributes_with_file_input_type_for_product(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -879,7 +866,6 @@ def test_clean_attributes_with_file_input_type_for_product_no_file_given(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -920,7 +906,6 @@ def test_clean_not_required_attrs_with_file_input_type_for_product_no_file_givenAttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -954,7 +939,6 @@ def test_clean_attributes_with_file_input_type_for_product_empty_file_value(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -989,7 +973,6 @@ def test_clean_numeric_attributes_input_for_product(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1017,7 +1000,6 @@ def test_clean_numeric_attributes_input_for_product_not_numeric_value_given(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1052,7 +1034,6 @@ def test_validate_numeric_attributes_input_for_product_blank_value(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1086,7 +1067,6 @@ def test_validate_numeric_attributes_input_none_as_values(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1121,7 +1101,6 @@ def test_validate_numeric_attributes_input_for_product_more_than_one_value_givenAttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1168,7 +1147,6 @@ def test_validate_selectable_attributes_by_value(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1207,7 +1185,6 @@ def test_validate_selectable_attributes_by_id(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1241,7 +1218,6 @@ def test_clean_selectable_attributes_pass_null_value(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1272,7 +1248,6 @@ def test_clean_selectable_attribute_by_id_and_value(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1311,7 +1286,6 @@ def test_clean_selectable_attribute_by_external_reference(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1342,7 +1316,6 @@ def test_clean_selectable_attribute_by_id_and_external_reference(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1381,7 +1354,6 @@ def test_clean_selectable_attribute_by_value_and_external_reference(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1412,7 +1384,6 @@ def test_clean_multiselect_attribute_by_id_and_value(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1452,7 +1423,6 @@ def test_clean_multiselect_attribute_duplicated_values(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1492,7 +1462,6 @@ def test_clean_multiselect_attribute_duplicated_ids(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1532,7 +1501,6 @@ def test_clean_multiselect_attribute_duplicated_external_refs(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1569,7 +1537,6 @@ def test_clean_selectable_attribute_max_length_exceeded(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1606,7 +1573,6 @@ def test_clean_selectable_attribute_value_required(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1640,7 +1606,6 @@ def test_validate_numeric_attributes(creation, value, numeric_attribute, productAttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1668,7 +1633,6 @@ def test_validate_numeric_attributes_invalid_number(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1699,7 +1663,6 @@ def test_clean_numeric_attributes_pass_null_value(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1725,7 +1688,6 @@ def test_clean_numeric_attributes_value_required(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1776,7 +1738,6 @@ def test_validate_rich_text_attributes_input_for_product_only_embed_block(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)@@ -1818,7 +1779,6 @@ def test_clean_rich_text_attributes_input_for_product_only_image_block(AttributeAssignmentMixin.clean_input(input_data,product_type.product_attributes.all(),- is_page_attributes=False,creation=creation,)diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.pyindex 687c8c9c80..6ae2167d8f 100644--- a/saleor/graphql/attribute/types.py+++ b/saleor/graphql/attribute/types.py@@ -63,6 +63,7 @@ from ..translations.types import AttributeTranslation, AttributeValueTranslationfrom .dataloaders.assigned_attributes import (AttributeValuesByPageIdAndAttributeIdAndLimitLoader,AttributeValuesByProductIdAndAttributeIdAndLimitLoader,+ AttributeValuesByUserIdAndAttributeIdAndLimitLoader,AttributeValuesByVariantIdAndAttributeIdAndLimitLoader,)from .dataloaders.attributes import (@@ -714,6 +715,10 @@ def get_attribute_values(return AttributeValuesByPageIdAndAttributeIdAndLimitLoader(info.context).load((root.page_id, root.attribute.id, limit))+ if root.user_id:+ return AttributeValuesByUserIdAndAttributeIdAndLimitLoader(info.context).load(+ (root.user_id, root.attribute.id, limit)+ )return Promise.resolve([])diff --git a/saleor/graphql/attribute/utils/attribute_assignment.py b/saleor/graphql/attribute/utils/attribute_assignment.pyindex 8fe052da16..8b2957a0c4 100644--- a/saleor/graphql/attribute/utils/attribute_assignment.py+++ b/saleor/graphql/attribute/utils/attribute_assignment.py@@ -12,7 +12,6 @@ from ....attribute import models as attribute_modelsfrom ....attribute.models import AttributeValuefrom ....attribute.utils import associate_attribute_values_to_instancefrom ....page import models as page_models-from ....page.error_codes import PageErrorCodefrom ....product import models as product_modelsfrom ....product.error_codes import ProductErrorCodefrom ...core.utils import from_global_id_or_error@@ -125,11 +124,9 @@ class AttributeAssignmentMixin:raw_input: list[dict],attributes_qs: "QuerySet",creation: bool = True,- is_page_attributes: bool = False,+ error_class=ProductErrorCode,) -> T_INPUT_MAP:"""Resolve, validate, and prepare attribute input."""- error_class = PageErrorCode if is_page_attributes else ProductErrorCode-id_to_values_input_map, ext_ref_to_values_input_map = (cls._prepare_attribute_input_maps(raw_input, error_class))@@ -233,7 +230,9 @@ class AttributeAssignmentMixin:)if creation:- cls._validate_required_attributes(attributes_qs, cleaned_input, errors)+ cls._validate_required_attributes(+ attributes_qs, cleaned_input, errors, error_class+ )if errors:raise ValidationError(errors)@@ -278,6 +277,7 @@ class AttributeAssignmentMixin:attributes_qs: "QuerySet[attribute_models.Attribute]",cleaned_input: T_INPUT_MAP,errors: list[ValidationError],+ error_class,):"""Validate that all required attributes are provided."""supplied_pks = {attr.pk for attr, _ in cleaned_input}@@ -291,7 +291,7 @@ class AttributeAssignmentMixin:]error = ValidationError("All attributes flagged as having a value required must be supplied.",- code=ProductErrorCode.REQUIRED.value,+ code=error_class.REQUIRED.value,params={"attributes": missing_ids},)errors.append(error)diff --git a/saleor/graphql/attribute/utils/shared.py b/saleor/graphql/attribute/utils/shared.pyindex 0bd7943d3b..572322881c 100644--- a/saleor/graphql/attribute/utils/shared.py+++ b/saleor/graphql/attribute/utils/shared.py@@ -7,6 +7,7 @@ import orjsonfrom django.db.models import Modelfrom django.db.models.expressions import Exists, OuterRef+from ....account import models as account_modelsfrom ....attribute import AttributeEntityType, AttributeInputTypefrom ....attribute import models as attribute_modelsfrom ....page import models as page_models@@ -16,7 +17,12 @@ from ..enums import AttributeValueBulkActionEnumif TYPE_CHECKING:from ....attribute.models import Attribute-T_INSTANCE = product_models.Product | product_models.ProductVariant | page_models.Page+T_INSTANCE = (+ product_models.Product+ | product_models.ProductVariant+ | page_models.Page+ | account_models.User+)T_ERROR_DICT = dict[tuple[str, str], list]T_REFERENCE = (product_models.Product@@ -34,6 +40,7 @@ class AssignedAttributeData:product_id: int | None = Nonepage_id: int | None = Nonevariant_id: int | None = None+ user_id: int | None = None@dataclass@@ -96,6 +103,8 @@ def get_assignment_model_and_fk(instance: T_INSTANCE):return attribute_models.AssignedPageAttributeValue, "page_id"if isinstance(instance, product_models.Product):return attribute_models.AssignedProductAttributeValue, "product_id"+ if isinstance(instance, account_models.User):+ return attribute_models.AssignedUserAttributeValue, "user_id"raise NotImplementedError(f"Assignment for {type(instance).__name__} not implemented.")diff --git a/saleor/graphql/core/doc_category.py b/saleor/graphql/core/doc_category.pyindex d08755406a..f300663ce3 100644--- a/saleor/graphql/core/doc_category.py+++ b/saleor/graphql/core/doc_category.py@@ -21,6 +21,7 @@ DOC_CATEGORY_WEBHOOKS = "Webhooks"# Map models to category names in doc directive.DOC_CATEGORY_MAP = {"account.Address": DOC_CATEGORY_USERS,+ "account.CustomerType": DOC_CATEGORY_USERS,"account.CustomerEvent": DOC_CATEGORY_USERS,"account.Group": DOC_CATEGORY_USERS,"account.StaffNotificationRecipient": DOC_CATEGORY_USERS,diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.pyindex 33ee17eb1e..219d88721c 100644--- a/saleor/graphql/core/enums.py+++ b/saleor/graphql/core/enums.py@@ -233,6 +233,36 @@ CustomerBulkUpdateErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum()CustomerBulkUpdateErrorCode.doc_category = DOC_CATEGORY_USERS+CustomerTypeAssignAttributesErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(+ account_error_codes.CustomerTypeAssignAttributesErrorCode+)+CustomerTypeAssignAttributesErrorCode.doc_category = DOC_CATEGORY_USERS++CustomerTypeUnassignAttributesErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(+ account_error_codes.CustomerTypeUnassignAttributesErrorCode+)+CustomerTypeUnassignAttributesErrorCode.doc_category = DOC_CATEGORY_USERS++CustomerTypeCreateErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(+ account_error_codes.CustomerTypeCreateErrorCode+)+CustomerTypeCreateErrorCode.doc_category = DOC_CATEGORY_USERS++CustomerTypeUpdateErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(+ account_error_codes.CustomerTypeUpdateErrorCode+)+CustomerTypeUpdateErrorCode.doc_category = DOC_CATEGORY_USERS++CustomerTypeDeleteErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(+ account_error_codes.CustomerTypeDeleteErrorCode+)+CustomerTypeDeleteErrorCode.doc_category = DOC_CATEGORY_USERS++CustomerTypeReorderAttributesErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(+ account_error_codes.CustomerTypeReorderAttributesErrorCode+)+CustomerTypeReorderAttributesErrorCode.doc_category = DOC_CATEGORY_USERS+ExternalNotificationTriggerErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(external_notifications_error_codes.ExternalNotificationErrorCodes)diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.pyindex 28496759a5..001a820849 100644--- a/saleor/graphql/core/types/common.py+++ b/saleor/graphql/core/types/common.py@@ -26,6 +26,7 @@ from ...core.doc_category import (DOC_CATEGORY_WEBHOOKS,)from ...core.scalars import DateTime, Decimal+from ..descriptions import ADDED_IN_323from ..enums import (AccountErrorCode,AppErrorCode,@@ -186,6 +187,11 @@ class AccountError(Error):address_type = AddressTypeEnum(description="A type of address that causes the error.", required=False)+ attributes = NonNullList(+ graphene.ID,+ description="List of attributes IDs which causes the error." + ADDED_IN_323,+ required=False,+ )class Meta:description = "Represents errors in account mutations."@@ -278,6 +284,11 @@ class CheckoutError(Error):class CustomerBulkUpdateError(BulkError):code = CustomerBulkUpdateErrorCode(description="The error code.", required=True)+ attributes = NonNullList(+ graphene.ID,+ description="List of attributes IDs which causes the error." + ADDED_IN_323,+ required=False,+ )class Meta:doc_category = DOC_CATEGORY_USERSdiff --git a/saleor/graphql/decorators.py b/saleor/graphql/decorators.pyindex bfb4de0d6a..3128e73baa 100644--- a/saleor/graphql/decorators.py+++ b/saleor/graphql/decorators.py@@ -9,7 +9,9 @@ from ..attribute.models import Attributefrom ..core.exceptions import PermissionDeniedfrom ..permission.auth_filters import is_app, is_staff_userfrom ..permission.enums import (+ AccountPermissions,BasePermissionEnum,+ CustomerTypePermissions,PagePermissions,PageTypePermissions,ProductPermissions,@@ -130,6 +132,11 @@ def check_attribute_required_permissions():PagePermissions.MANAGE_PAGES,PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,]+ elif attribute.type == AttributeType.CUSTOMER_TYPE:+ permissions = [+ AccountPermissions.MANAGE_USERS,+ CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES,+ ]else:permissions = [ProductPermissions.MANAGE_PRODUCTS,diff --git a/saleor/graphql/meta/permissions.py b/saleor/graphql/meta/permissions.pyindex 1125a51627..295828d141 100644--- a/saleor/graphql/meta/permissions.py+++ b/saleor/graphql/meta/permissions.py@@ -17,6 +17,7 @@ from ...permission.enums import (BasePermissionEnum,ChannelPermissions,CheckoutPermissions,+ CustomerTypePermissions,DiscountPermissions,GiftcardPermissions,MenuPermissions,@@ -243,6 +244,12 @@ def page_type_permissions(return [PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES]+def customer_type_permissions(+ _info: ResolveInfo, _object_pk: Any+) -> list[BasePermissionEnum]:+ return [CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES]++def attribute_permissions(info: ResolveInfo, attribute_pk: int):database_connection_name = get_database_connection_name(info.context)attribute = attribute_models.Attribute.objects.using(database_connection_name).get(@@ -250,6 +257,8 @@ def attribute_permissions(info: ResolveInfo, attribute_pk: int):)if attribute.type == AttributeType.PAGE_TYPE:return page_type_permissions(info, attribute_pk)+ if attribute.type == AttributeType.CUSTOMER_TYPE:+ return customer_type_permissions(info, attribute_pk)return product_type_permissions(info, attribute_pk)@@ -315,6 +324,7 @@ PUBLIC_META_PERMISSION_MAP: dict["Checkout": no_permissions,"CheckoutLine": no_permissions,"Collection": product_permissions,+ "CustomerType": customer_type_permissions,"Fulfillment": order_permissions,"GiftCard": gift_card_permissions,"Invoice": invoice_permissions,@@ -354,6 +364,7 @@ PRIVATE_META_PERMISSION_MAP: dict["Checkout": checkout_permissions,"CheckoutLine": checkout_permissions,"Collection": product_permissions,+ "CustomerType": customer_type_permissions,"Fulfillment": order_permissions,"GiftCard": gift_card_permissions,"Invoice": invoice_permissions,diff --git a/saleor/graphql/page/filters.py b/saleor/graphql/page/filters.pyindex b24dc14fbe..dbc423cb5e 100644--- a/saleor/graphql/page/filters.py+++ b/saleor/graphql/page/filters.py@@ -1,35 +1,16 @@-from typing import Literal-import django_filtersimport graphenefrom django.db.models import Exists, OuterRef, Q, QuerySetfrom ...attribute.models import (AssignedPageAttributeValue,- Attribute,AttributePage,AttributeValue,)from ...page import modelsfrom ..attribute.shared_filters import (- CONTAINS_TYPING,AssignedAttributeWhereInput,- clean_up_referenced_global_ids,- get_attribute_values_by_boolean_value,- get_attribute_values_by_date_time_value,- get_attribute_values_by_date_value,- get_attribute_values_by_numeric_value,- get_attribute_values_by_referenced_category_ids,- get_attribute_values_by_referenced_category_slugs,- get_attribute_values_by_referenced_collection_ids,- get_attribute_values_by_referenced_collection_slugs,- get_attribute_values_by_referenced_page_ids,- get_attribute_values_by_referenced_page_slugs,- get_attribute_values_by_referenced_product_ids,- get_attribute_values_by_referenced_product_slugs,- get_attribute_values_by_referenced_variant_ids,- get_attribute_values_by_referenced_variant_skus,- get_attribute_values_by_slug_or_name_value,+ filter_objects_by_attributes,validate_attribute_value_input,)from ..core.doc_category import DOC_CATEGORY_PAGES@@ -52,7 +33,6 @@ from ..core.filters.where_input import ()from ..utils import resolve_global_ids_to_primary_keysfrom ..utils.filters import (- Number,filter_by_id,filter_by_ids,filter_slug_list,@@ -101,598 +81,12 @@ def _get_assigned_page_attribute_for_attribute_value()-def filter_by_slug_or_name(- attr_id: int | None,- attr_value: dict,- db_connection_name: str,-):- attribute_values = get_attribute_values_by_slug_or_name_value(- attr_id=attr_id,- attr_value=attr_value,- db_connection_name=db_connection_name,- )- return _get_assigned_page_attribute_for_attribute_value(- attribute_values=attribute_values,- db_connection_name=db_connection_name,- )---def filter_by_numeric_attribute(- attr_id: int | None,- numeric_value: dict[str, Number | list[Number] | dict[str, Number]],- db_connection_name: str,-):- attribute_values = get_attribute_values_by_numeric_value(- attr_id=attr_id,- numeric_value=numeric_value,- db_connection_name=db_connection_name,- )- return _get_assigned_page_attribute_for_attribute_value(- attribute_values=attribute_values,- db_connection_name=db_connection_name,- )---def filter_by_boolean_attribute(- attr_id: int | None,- boolean_value: bool,- db_connection_name: str,-):- attribute_values = get_attribute_values_by_boolean_value(- attr_id=attr_id,- boolean_value=boolean_value,- db_connection_name=db_connection_name,- )- return _get_assigned_page_attribute_for_attribute_value(- attribute_values=attribute_values,- db_connection_name=db_connection_name,- )---def filter_by_date_attribute(- attr_id: int | None,- date_value: dict[str, str],- db_connection_name: str,-):- attribute_values = get_attribute_values_by_date_value(- attr_id=attr_id,- date_value=date_value,- db_connection_name=db_connection_name,- )- return _get_assigned_page_attribute_for_attribute_value(- attribute_values=attribute_values,- db_connection_name=db_connection_name,- )---def filter_by_date_time_attribute(- attr_id: int | None,- date_value: dict[str, str],- db_connection_name: str,-):- attribute_values = get_attribute_values_by_date_time_value(- attr_id=attr_id,- date_value=date_value,- db_connection_name=db_connection_name,- )- return _get_assigned_page_attribute_for_attribute_value(- attribute_values=attribute_values,- db_connection_name=db_connection_name,- )---def _filter_contains_single_expression(- attr_id: int | None,- db_connection_name: str,- referenced_attr_values: QuerySet[AttributeValue],-):- if attr_id:- referenced_attr_values = referenced_attr_values.filter(- attribute_id=attr_id,- )- return _get_assigned_page_attribute_for_attribute_value(- referenced_attr_values,- db_connection_name,- )---def filter_by_contains_referenced_page_slugs(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter pages based on their references to pages.-- - If `contains_all` is provided, only pages that reference all of the- specified pages will match.- - If `contains_any` is provided, pages that reference at least one of- the specified pages will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for page_slug in contains_all:- referenced_attr_values = get_attribute_values_by_referenced_page_slugs(- slugs=[page_slug], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_page_slugs(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def filter_by_contains_referenced_product_slugs(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter pages based on their references to products.-- - If `contains_all` is provided, only pages that reference all of the- specified products will match.- - If `contains_any` is provided, pages that reference at least one of- the specified products will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for product_slug in contains_all:- referenced_attr_values = get_attribute_values_by_referenced_product_slugs(- slugs=[product_slug], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_product_slugs(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def filter_by_contains_referenced_category_slugs(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter pages based on their references to categories.-- - If `contains_all` is provided, only pages that reference all of the- specified categories will match.- - If `contains_any` is provided, pages that reference at least one of- the specified categories will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for category_slug in contains_all:- referenced_attr_values = get_attribute_values_by_referenced_category_slugs(- slugs=[category_slug], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_category_slugs(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def filter_by_contains_referenced_collection_slugs(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter pages based on their references to collections.-- - If `contains_all` is provided, only pages that reference all of the- specified collections will match.- - If `contains_any` is provided, pages that reference at least one of- the specified collections will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for collection_slug in contains_all:- referenced_attr_values = (- get_attribute_values_by_referenced_collection_slugs(- slugs=[collection_slug], db_connection_name=db_connection_name- )- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_collection_slugs(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def filter_by_contains_referenced_variant_skus(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter pages based on their references to variants.-- - If `contains_all` is provided, only pages that reference all of the- specified variants will match.- - If `contains_any` is provided, pages that reference at least one of- the specified variants will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for variant_sku in contains_all:- referenced_attr_values = get_attribute_values_by_referenced_variant_skus(- slugs=[variant_sku], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_variant_skus(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def _filter_by_contains_all_referenced_object_ids(- variant_ids: set[int],- product_ids: set[int],- page_ids: set[int],- category_ids: set[int],- collection_ids: set[int],- attr_id: int | None,- db_connection_name: str,-) -> Q:- expression = Q()- if page_ids:- for page_id in page_ids:- referenced_attr_values = get_attribute_values_by_referenced_page_ids(- ids=[page_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if product_ids:- for product_id in product_ids:- referenced_attr_values = get_attribute_values_by_referenced_product_ids(- ids=[product_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if variant_ids:- for variant_id in variant_ids:- referenced_attr_values = get_attribute_values_by_referenced_variant_ids(- ids=[variant_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if category_ids:- for category_id in category_ids:- referenced_attr_values = get_attribute_values_by_referenced_category_ids(- ids=[category_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if collection_ids:- for collection_id in collection_ids:- referenced_attr_values = get_attribute_values_by_referenced_collection_ids(- ids=[collection_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression---def _filter_by_contains_any_referenced_object_ids(- variant_ids: set[int],- product_ids: set[int],- page_ids: set[int],- category_ids: set[int],- collection_ids: set[int],- attr_id: int | None,- db_connection_name: str,-) -> Q:- expression = Q()- if page_ids:- referenced_attr_values = get_attribute_values_by_referenced_page_ids(- ids=list(page_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if product_ids:- referenced_attr_values = get_attribute_values_by_referenced_product_ids(- ids=list(product_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if variant_ids:- referenced_attr_values = get_attribute_values_by_referenced_variant_ids(- ids=list(variant_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if category_ids:- referenced_attr_values = get_attribute_values_by_referenced_category_ids(- ids=list(category_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if collection_ids:- referenced_attr_values = get_attribute_values_by_referenced_collection_ids(- ids=list(collection_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression---def filter_by_contains_referenced_object_ids(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-) -> Q:- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- grouped_ids = clean_up_referenced_global_ids(contains_any or contains_all or [])- variant_ids = grouped_ids["ProductVariant"]- product_ids = grouped_ids["Product"]- page_ids = grouped_ids["Page"]- category_ids = grouped_ids["Category"]- collection_ids = grouped_ids["Collection"]-- if contains_all:- return _filter_by_contains_all_referenced_object_ids(- variant_ids=variant_ids,- product_ids=product_ids,- page_ids=page_ids,- category_ids=category_ids,- collection_ids=collection_ids,- attr_id=attr_id,- db_connection_name=db_connection_name,- )- if contains_any:- return _filter_by_contains_any_referenced_object_ids(- variant_ids=variant_ids,- product_ids=product_ids,- page_ids=page_ids,- category_ids=category_ids,- collection_ids=collection_ids,- attr_id=attr_id,- db_connection_name=db_connection_name,- )- return Q()---def filter_objects_by_reference_attributes(- attr_id: int | None,- attr_value: dict[- Literal[- "referenced_ids",- "page_slugs",- "product_slugs",- "product_variant_skus",- "category_slugs",- "collection_slugs",- ],- CONTAINS_TYPING,- ],- db_connection_name: str,-):- filter_expression = Q()-- if "referenced_ids" in attr_value:- filter_expression &= filter_by_contains_referenced_object_ids(- attr_id,- attr_value["referenced_ids"],- db_connection_name,- )- if "page_slugs" in attr_value:- filter_expression &= filter_by_contains_referenced_page_slugs(- attr_id,- attr_value["page_slugs"],- db_connection_name,- )- if "product_slugs" in attr_value:- filter_expression &= filter_by_contains_referenced_product_slugs(- attr_id,- attr_value["product_slugs"],- db_connection_name,- )- if "product_variant_skus" in attr_value:- filter_expression &= filter_by_contains_referenced_variant_skus(- attr_id,- attr_value["product_variant_skus"],- db_connection_name,- )- if "category_slugs" in attr_value:- filter_expression &= filter_by_contains_referenced_category_slugs(- attr_id,- attr_value["category_slugs"],- db_connection_name,- )- if "collection_slugs" in attr_value:- filter_expression &= filter_by_contains_referenced_collection_slugs(- attr_id,- attr_value["collection_slugs"],- db_connection_name,- )- return filter_expression--def filter_pages_by_attributes(qs, value):- attribute_slugs = {- attr_filter["slug"] for attr_filter in value if "slug" in attr_filter- }- attributes_map = {- attr.slug: attr- for attr in Attribute.objects.using(qs.db).filter(slug__in=attribute_slugs)- }- if len(attribute_slugs) != len(attributes_map.keys()):- # Filter over non existing attribute- return qs.none()-- attr_filter_expression = Q()-- attr_without_values_input = []- for attr_filter in value:- if "slug" in attr_filter and "value" not in attr_filter:- attr_without_values_input.append(attributes_map[attr_filter["slug"]])-- if attr_without_values_input:- atr_value_qs = AttributeValue.objects.using(qs.db).filter(- attribute_id__in=[attr.id for attr in attr_without_values_input]- )- attr_filter_expression = _get_assigned_page_attribute_for_attribute_value(- attribute_values=atr_value_qs,- db_connection_name=qs.db,- )-- for attr_filter in value:- attr_value = attr_filter.get("value")- if not attr_value:- # attrs without value input are handled separately- continue-- attr_id = None- if attr_slug := attr_filter.get("slug"):- attr = attributes_map[attr_slug]- attr_id = attr.id-- attr_value = attr_filter["value"]-- if "slug" in attr_value or "name" in attr_value:- attr_filter_expression &= filter_by_slug_or_name(- attr_id,- attr_value,- qs.db,- )- elif "numeric" in attr_value:- attr_filter_expression &= filter_by_numeric_attribute(- attr_id,- attr_value["numeric"],- qs.db,- )- elif "boolean" in attr_value:- attr_filter_expression &= filter_by_boolean_attribute(- attr_id,- attr_value["boolean"],- qs.db,- )- elif "date" in attr_value:- attr_filter_expression &= filter_by_date_attribute(- attr_id,- attr_value["date"],- qs.db,- )- elif "date_time" in attr_value:- attr_filter_expression &= filter_by_date_time_attribute(- attr_id,- attr_value["date_time"],- qs.db,- )- elif "reference" in attr_value:- attr_filter_expression &= filter_objects_by_reference_attributes(- attr_id,- attr_value["reference"],- qs.db,- )- if attr_filter_expression != Q():- return qs.filter(attr_filter_expression)- return qs.none()+ return filter_objects_by_attributes(+ qs,+ value,+ _get_assigned_page_attribute_for_attribute_value,+ )class PageWhere(MetadataWhereBase):diff --git a/saleor/graphql/page/mutations/page_create.py b/saleor/graphql/page/mutations/page_create.pyindex 78033b630d..c88ae33579 100644--- a/saleor/graphql/page/mutations/page_create.py+++ b/saleor/graphql/page/mutations/page_create.py@@ -73,7 +73,7 @@ class PageCreate(DeprecatedModelMutation):attributes_qs = page_type.page_attributesattributes_qs = cast(QuerySet, attributes_qs)cleaned_attributes = AttributeAssignmentMixin.clean_input(- attributes, attributes_qs, is_page_attributes=True+ attributes, attributes_qs, error_class=PageErrorCode)return cleaned_attributesdiff --git a/saleor/graphql/page/mutations/page_update.py b/saleor/graphql/page/mutations/page_update.pyindex a3120d9807..c6e02eec39 100644--- a/saleor/graphql/page/mutations/page_update.py+++ b/saleor/graphql/page/mutations/page_update.py@@ -6,6 +6,7 @@ from django.db.models import Exists, OuterRef, QuerySetfrom ....attribute import models as attribute_modelsfrom ....core.utils.update_mutation_manager import InstanceTrackerfrom ....page import models+from ....page.error_codes import PageErrorCodefrom ....permission.enums import PagePermissionsfrom ....product.models import Productfrom ....product.utils.search_helpers import (@@ -41,7 +42,7 @@ class PageUpdate(PageCreate):attributes_qs = page_type.page_attributesattributes_qs = cast(QuerySet, attributes_qs)cleaned_attributes = AttributeAssignmentMixin.clean_input(- attributes, attributes_qs, creation=False, is_page_attributes=True+ attributes, attributes_qs, creation=False, error_class=PageErrorCode)return cleaned_attributesdiff --git a/saleor/graphql/product/filters/product_attributes.py b/saleor/graphql/product/filters/product_attributes.pyindex ca1c0cc64d..14d1c17ee7 100644--- a/saleor/graphql/product/filters/product_attributes.py+++ b/saleor/graphql/product/filters/product_attributes.py@@ -1,7 +1,7 @@import datetimeimport mathfrom collections import defaultdict-from typing import Literal, TypedDict+from typing import TypedDictfrom django.db.models import Exists, OuterRef, Q, QuerySetfrom graphql import GraphQLError@@ -17,26 +17,9 @@ from ....attribute.models import ()from ....product.models import Product, ProductVariantfrom ...attribute.shared_filters import (- CONTAINS_TYPING,- clean_up_referenced_global_ids,- get_attribute_values_by_boolean_value,- get_attribute_values_by_date_time_value,- get_attribute_values_by_date_value,- get_attribute_values_by_numeric_value,- get_attribute_values_by_referenced_category_ids,- get_attribute_values_by_referenced_category_slugs,- get_attribute_values_by_referenced_collection_ids,- get_attribute_values_by_referenced_collection_slugs,- get_attribute_values_by_referenced_page_ids,- get_attribute_values_by_referenced_page_slugs,- get_attribute_values_by_referenced_product_ids,- get_attribute_values_by_referenced_product_slugs,- get_attribute_values_by_referenced_variant_ids,- get_attribute_values_by_referenced_variant_skus,- get_attribute_values_by_slug_or_name_value,+ filter_objects_by_attributes,validate_attribute_value_input,)-from ...utils.filters import NumberT_PRODUCT_FILTER_QUERIES = dict[int, list[int]]@@ -363,601 +346,6 @@ def _get_assigned_product_attribute_for_attribute_value()-def filter_by_slug_or_name(- attr_id: int | None,- attr_value: dict,- db_connection_name: str,-):- attribute_values = get_attribute_values_by_slug_or_name_value(- attr_id=attr_id,- attr_value=attr_value,- db_connection_name=db_connection_name,- )- return _get_assigned_product_attribute_for_attribute_value(- attribute_values=attribute_values,- db_connection_name=db_connection_name,- )---def filter_by_numeric_attribute(- attr_id: int | None,- numeric_value: dict[str, Number | list[Number] | dict[str, Number]],- db_connection_name: str,-):- qs_by_numeric = get_attribute_values_by_numeric_value(- attr_id=attr_id,- numeric_value=numeric_value,- db_connection_name=db_connection_name,- )- return _get_assigned_product_attribute_for_attribute_value(- attribute_values=qs_by_numeric,- db_connection_name=db_connection_name,- )---def filter_by_boolean_attribute(- attr_id: int | None,- boolean_value,- db_connection_name: str,-):- qs_by_boolean = get_attribute_values_by_boolean_value(- attr_id=attr_id,- boolean_value=boolean_value,- db_connection_name=db_connection_name,- )- return _get_assigned_product_attribute_for_attribute_value(- qs_by_boolean,- db_connection_name,- )---def filter_by_date_attribute(- attr_id: int | None,- date_value,- db_connection_name: str,-):- qs_by_date = get_attribute_values_by_date_value(- attr_id=attr_id,- date_value=date_value,- db_connection_name=db_connection_name,- )- return _get_assigned_product_attribute_for_attribute_value(- qs_by_date,- db_connection_name,- )---def filter_by_date_time_attribute(- attr_id: int | None,- date_value,- db_connection_name: str,-):- qs_by_date_time = get_attribute_values_by_date_time_value(- attr_id=attr_id,- date_value=date_value,- db_connection_name=db_connection_name,- )- return _get_assigned_product_attribute_for_attribute_value(- qs_by_date_time,- db_connection_name,- )---def _filter_contains_single_expression(- attr_id: int | None,- db_connection_name: str,- referenced_attr_values: QuerySet[AttributeValue],-):- if attr_id:- referenced_attr_values = referenced_attr_values.filter(- attribute_id=attr_id,- )- return _get_assigned_product_attribute_for_attribute_value(- referenced_attr_values,- db_connection_name,- )---def filter_by_contains_referenced_page_slugs(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter products based on their references to pages.-- - If `contains_all` is provided, only products that reference all of the- specified pages will match.- - If `contains_any` is provided, products that reference at least one of- the specified pages will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for page_slug in contains_all:- referenced_attr_values = get_attribute_values_by_referenced_page_slugs(- slugs=[page_slug], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_page_slugs(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def filter_by_contains_referenced_product_slugs(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter products based on their references to products.-- - If `contains_all` is provided, only products that reference all of the- specified products will match.- - If `contains_any` is provided, products that reference at least one of- the specified products will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for product_slug in contains_all:- referenced_attr_values = get_attribute_values_by_referenced_product_slugs(- slugs=[product_slug], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_product_slugs(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def filter_by_contains_referenced_variant_skus(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter products based on their references to variants.-- - If `contains_all` is provided, only products that reference all of the- specified variants will match.- - If `contains_any` is provided, products that reference at least one of- the specified variants will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for variant_sku in contains_all:- referenced_attr_values = get_attribute_values_by_referenced_variant_skus(- slugs=[variant_sku], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_variant_skus(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def filter_by_contains_referenced_category_slugs(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter products based on their references to categories.-- - If `contains_all` is provided, only products that reference all of the- specified categories will match.- - If `contains_any` is provided, products that reference at least one of- the specified categories will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for category_slug in contains_all:- referenced_attr_values = get_attribute_values_by_referenced_category_slugs(- slugs=[category_slug], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_category_slugs(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def filter_by_contains_referenced_collection_slugs(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter products based on their references to collections.-- - If `contains_all` is provided, only products that reference all of the- specified collections will match.- - If `contains_any` is provided, products that reference at least one of- the specified collections will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for collection_slug in contains_all:- referenced_attr_values = (- get_attribute_values_by_referenced_collection_slugs(- slugs=[collection_slug], db_connection_name=db_connection_name- )- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_collection_slugs(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def _filter_by_contains_all_referenced_object_ids(- variant_ids: set[int],- product_ids: set[int],- page_ids: set[int],- category_ids: set[int],- collection_ids: set[int],- attr_id: int | None,- db_connection_name: str,-) -> Q:- expression = Q()- if page_ids:- for page_id in page_ids:- referenced_attr_values = get_attribute_values_by_referenced_page_ids(- ids=[page_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if product_ids:- for product_id in product_ids:- referenced_attr_values = get_attribute_values_by_referenced_product_ids(- ids=[product_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if variant_ids:- for variant_id in variant_ids:- referenced_attr_values = get_attribute_values_by_referenced_variant_ids(- ids=[variant_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if category_ids:- for category_id in category_ids:- referenced_attr_values = get_attribute_values_by_referenced_category_ids(- ids=[category_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if collection_ids:- for collection_id in collection_ids:- referenced_attr_values = get_attribute_values_by_referenced_collection_ids(- ids=[collection_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression---def _filter_by_contains_any_referenced_object_ids(- variant_ids: set[int],- product_ids: set[int],- page_ids: set[int],- category_ids: set[int],- collection_ids: set[int],- attr_id: int | None,- db_connection_name: str,-) -> Q:- expression = Q()- if page_ids:- referenced_attr_values = get_attribute_values_by_referenced_page_ids(- ids=list(page_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if product_ids:- referenced_attr_values = get_attribute_values_by_referenced_product_ids(- ids=list(product_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if variant_ids:- referenced_attr_values = get_attribute_values_by_referenced_variant_ids(- ids=list(variant_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if category_ids:- referenced_attr_values = get_attribute_values_by_referenced_category_ids(- ids=list(category_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if collection_ids:- referenced_attr_values = get_attribute_values_by_referenced_collection_ids(- ids=list(collection_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression---def filter_by_contains_referenced_object_ids(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-) -> Q:- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- grouped_ids = clean_up_referenced_global_ids(contains_any or contains_all or [])- variant_ids = grouped_ids["ProductVariant"]- product_ids = grouped_ids["Product"]- page_ids = grouped_ids["Page"]- category_ids = grouped_ids["Category"]- collection_ids = grouped_ids["Collection"]-- if contains_all:- return _filter_by_contains_all_referenced_object_ids(- variant_ids=variant_ids,- product_ids=product_ids,- page_ids=page_ids,- category_ids=category_ids,- collection_ids=collection_ids,- attr_id=attr_id,- db_connection_name=db_connection_name,- )- if contains_any:- return _filter_by_contains_any_referenced_object_ids(- variant_ids=variant_ids,- product_ids=product_ids,- page_ids=page_ids,- category_ids=category_ids,- collection_ids=collection_ids,- attr_id=attr_id,- db_connection_name=db_connection_name,- )- return Q()---def filter_objects_by_reference_attributes(- attr_id: int | None,- attr_value: dict[- Literal[- "referenced_ids",- "page_slugs",- "product_slugs",- "product_variant_skus",- "category_slugs",- "collection_slugs",- ],- CONTAINS_TYPING,- ],- db_connection_name: str,-):- filter_expression = Q()-- if "referenced_ids" in attr_value:- filter_expression &= filter_by_contains_referenced_object_ids(- attr_id,- attr_value["referenced_ids"],- db_connection_name,- )- if "page_slugs" in attr_value:- filter_expression &= filter_by_contains_referenced_page_slugs(- attr_id,- attr_value["page_slugs"],- db_connection_name,- )- if "product_slugs" in attr_value:- filter_expression &= filter_by_contains_referenced_product_slugs(- attr_id,- attr_value["product_slugs"],- db_connection_name,- )- if "product_variant_skus" in attr_value:- filter_expression &= filter_by_contains_referenced_variant_skus(- attr_id,- attr_value["product_variant_skus"],- db_connection_name,- )- if "category_slugs" in attr_value:- filter_expression &= filter_by_contains_referenced_category_slugs(- attr_id,- attr_value["category_slugs"],- db_connection_name,- )- if "collection_slugs" in attr_value:- filter_expression &= filter_by_contains_referenced_collection_slugs(- attr_id,- attr_value["collection_slugs"],- db_connection_name,- )- return filter_expression---def _filter_products_by_attributes(- qs: QuerySet[Product], value: list[dict]-) -> QuerySet[Product]:- attribute_slugs = {- attr_filter["slug"] for attr_filter in value if "slug" in attr_filter- }- attributes_map = {- attr.slug: attr- for attr in Attribute.objects.using(qs.db).filter(slug__in=attribute_slugs)- }- if len(attribute_slugs) != len(attributes_map.keys()):- # Filter over non existing attribute- return qs.none()-- attr_filter_expression = Q()-- attr_without_values_input = []- for attr_filter in value:- if "slug" in attr_filter and "value" not in attr_filter:- attr_without_values_input.append(attributes_map[attr_filter["slug"]])-- if attr_without_values_input:- atr_value_qs = AttributeValue.objects.using(qs.db).filter(- attribute_id__in=[attr.id for attr in attr_without_values_input]- )- attr_filter_expression = _get_assigned_product_attribute_for_attribute_value(- atr_value_qs, qs.db- )-- for attr_filter in value:- attr_value = attr_filter.get("value")- if not attr_value:- # attrs without value input are handled separately- continue-- attr_id = None- if attr_slug := attr_filter.get("slug"):- attr = attributes_map[attr_slug]- attr_id = attr.id-- attr_value = attr_filter["value"]-- if "slug" in attr_value or "name" in attr_value:- attr_filter_expression &= filter_by_slug_or_name(- attr_id,- attr_value,- qs.db,- )- elif "numeric" in attr_value:- attr_filter_expression &= filter_by_numeric_attribute(- attr_id,- attr_value["numeric"],- qs.db,- )- elif "boolean" in attr_value:- attr_filter_expression &= filter_by_boolean_attribute(- attr_id,- attr_value["boolean"],- qs.db,- )- elif "date" in attr_value:- attr_filter_expression &= filter_by_date_attribute(- attr_id,- attr_value["date"],- qs.db,- )- elif "date_time" in attr_value:- attr_filter_expression &= filter_by_date_time_attribute(- attr_id,- attr_value["date_time"],- qs.db,- )- elif "reference" in attr_value:- attr_filter_expression &= filter_objects_by_reference_attributes(- attr_id,- attr_value["reference"],- qs.db,- )- if attr_filter_expression != Q():- return qs.filter(attr_filter_expression)- return qs.none()--def validate_attribute_input(attributes: list[dict], db_connection_name: str):value_used_with_deprecated_input = []missing_slug_for_deprecated_input: list[str] = []@@ -1008,4 +396,8 @@ def filter_products_by_attributes(if set(value[0].keys()).difference({"slug", "value"}):return deprecated_filter_attributes(qs, value)- return _filter_products_by_attributes(qs, value)+ return filter_objects_by_attributes(+ qs,+ value,+ _get_assigned_product_attribute_for_attribute_value,+ )diff --git a/saleor/graphql/product/filters/product_variant.py b/saleor/graphql/product/filters/product_variant.pyindex 2df57970b3..ccfd350e30 100644--- a/saleor/graphql/product/filters/product_variant.py+++ b/saleor/graphql/product/filters/product_variant.py@@ -1,5 +1,3 @@-from typing import Literal-import django_filtersimport graphenefrom django.db.models import Exists, OuterRef, Q@@ -9,29 +7,12 @@ from django.utils import timezonefrom ....attribute.models import (AssignedVariantAttribute,AssignedVariantAttributeValue,- Attribute,AttributeValue,)from ....product.models import Product, ProductVariantfrom ...attribute.shared_filters import (- CONTAINS_TYPING,AssignedAttributeWhereInput,- clean_up_referenced_global_ids,- get_attribute_values_by_boolean_value,- get_attribute_values_by_date_time_value,- get_attribute_values_by_date_value,- get_attribute_values_by_numeric_value,- get_attribute_values_by_referenced_category_ids,- get_attribute_values_by_referenced_category_slugs,- get_attribute_values_by_referenced_collection_ids,- get_attribute_values_by_referenced_collection_slugs,- get_attribute_values_by_referenced_page_ids,- get_attribute_values_by_referenced_page_slugs,- get_attribute_values_by_referenced_product_ids,- get_attribute_values_by_referenced_product_slugs,- get_attribute_values_by_referenced_variant_ids,- get_attribute_values_by_referenced_variant_skus,- get_attribute_values_by_slug_or_name_value,+ filter_objects_by_attributes,validate_attribute_value_input,)from ...channel.filters import get_channel_slug_from_filter_data@@ -51,7 +32,6 @@ from ...core.filters import (from ...core.filters.where_input import StringFilterInput, WhereInputObjectTypefrom ...core.types import DateTimeRangeInputfrom ...utils.filters import (- Number,filter_by_ids,filter_where_by_range_field,filter_where_by_value_field,@@ -79,86 +59,6 @@ def filter_is_preorder(qs, _, value):)-def filter_by_slug_or_name(- attr_id: int | None,- attr_value: dict,- db_connection_name: str,-):- attribute_values = get_attribute_values_by_slug_or_name_value(- attr_id=attr_id,- attr_value=attr_value,- db_connection_name=db_connection_name,- )- return _get_assigned_variant_attribute_for_attribute_value_qs(- attribute_values,- db_connection_name,- )---def filter_by_numeric_attribute(- attr_id: int | None,- numeric_value: dict[str, Number | list[Number] | dict[str, Number]],- db_connection_name: str,-):- qs_by_numeric = get_attribute_values_by_numeric_value(- attr_id=attr_id,- numeric_value=numeric_value,- db_connection_name=db_connection_name,- )- return _get_assigned_variant_attribute_for_attribute_value_qs(- qs_by_numeric,- db_connection_name,- )---def filter_by_boolean_attribute(- attr_id: int | None,- boolean_value,- db_connection_name: str,-):- qs_by_boolean = get_attribute_values_by_boolean_value(- attr_id=attr_id,- boolean_value=boolean_value,- db_connection_name=db_connection_name,- )- return _get_assigned_variant_attribute_for_attribute_value_qs(- qs_by_boolean,- db_connection_name,- )---def filter_by_date_attribute(- attr_id: int | None,- date_value,- db_connection_name: str,-):- qs_by_date = get_attribute_values_by_date_value(- attr_id=attr_id,- date_value=date_value,- db_connection_name=db_connection_name,- )- return _get_assigned_variant_attribute_for_attribute_value_qs(- qs_by_date,- db_connection_name,- )---def filter_by_date_time_attribute(- attr_id: int | None,- date_value,- db_connection_name: str,-):- qs_by_date_time = get_attribute_values_by_date_time_value(- attr_id=attr_id,- date_value=date_value,- db_connection_name=db_connection_name,- )- return _get_assigned_variant_attribute_for_attribute_value_qs(- qs_by_date_time,- db_connection_name,- )--def _get_assigned_variant_attribute_for_attribute_value_qs(attribute_values: QuerySet[AttributeValue],db_connection_name: str,@@ -178,527 +78,14 @@ def _get_assigned_variant_attribute_for_attribute_value_qs()-def _filter_contains_single_expression(- attr_id: int | None,- db_connection_name: str,- referenced_attr_values: QuerySet[AttributeValue],-):- if attr_id:- referenced_attr_values = referenced_attr_values.filter(- attribute_id=attr_id,- )- assigned_attr_value = AssignedVariantAttributeValue.objects.using(- db_connection_name- ).filter(- value__in=referenced_attr_values,- assignment_id=OuterRef("id"),- )- return Q(- Exists(- AssignedVariantAttribute.objects.using(db_connection_name).filter(- Exists(assigned_attr_value), variant_id=OuterRef("pk")- )- )- )---def filter_by_contains_referenced_page_slugs(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter variants based on their references to pages.-- - If `contains_all` is provided, only variants that reference all of the- specified pages will match.- - If `contains_any` is provided, variants that reference at least one of- the specified pages will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for page_slug in contains_all:- referenced_attr_values = get_attribute_values_by_referenced_page_slugs(- slugs=[page_slug], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_page_slugs(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def filter_by_contains_referenced_category_slugs(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter variants based on their references to categories.-- - If `contains_all` is provided, only variants that reference all of the- specified categories will match.- - If `contains_any` is provided, variants that reference at least one of- the specified categories will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for category_slug in contains_all:- referenced_attr_values = get_attribute_values_by_referenced_category_slugs(- slugs=[category_slug], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_category_slugs(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def filter_by_contains_referenced_collection_slugs(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter variants based on their references to collections.-- - If `contains_all` is provided, only variants that reference all of the- specified collections will match.- - If `contains_any` is provided, variants that reference at least one of- the specified collections will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for collection_slug in contains_all:- referenced_attr_values = (- get_attribute_values_by_referenced_collection_slugs(- slugs=[collection_slug], db_connection_name=db_connection_name- )- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_collection_slugs(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def filter_by_contains_referenced_product_slugs(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter variants based on their references to products.-- - If `contains_all` is provided, only variants that reference all of the- specified products will match.- - If `contains_any` is provided, variants that reference at least one of- the specified products will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for product_slug in contains_all:- referenced_attr_values = get_attribute_values_by_referenced_product_slugs(- slugs=[product_slug], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_product_slugs(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def filter_by_contains_referenced_variant_skus(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-):- """Build an expression to filter variants based on their references to variants.-- - If `contains_all` is provided, only variants that reference all of the- specified variants will match.- - If `contains_any` is provided, variants that reference at least one of- the specified variants will match.- """- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- if contains_all:- expression = Q()- for variant_sku in contains_all:- referenced_attr_values = get_attribute_values_by_referenced_variant_skus(- slugs=[variant_sku], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression-- if contains_any:- referenced_attr_values = get_attribute_values_by_referenced_variant_skus(- slugs=contains_any, db_connection_name=db_connection_name- )- return _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return Q()---def _filter_by_contains_all_referenced_object_ids(- variant_ids: set[int],- product_ids: set[int],- page_ids: set[int],- category_ids: set[int],- collection_ids: set[int],- attr_id: int | None,- db_connection_name: str,-) -> Q:- expression = Q()- if page_ids:- for page_id in page_ids:- referenced_attr_values = get_attribute_values_by_referenced_page_ids(- ids=[page_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if product_ids:- for product_id in product_ids:- referenced_attr_values = get_attribute_values_by_referenced_product_ids(- ids=[product_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if variant_ids:- for variant_id in variant_ids:- referenced_attr_values = get_attribute_values_by_referenced_variant_ids(- ids=[variant_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if category_ids:- for category_id in category_ids:- referenced_attr_values = get_attribute_values_by_referenced_category_ids(- ids=[category_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if collection_ids:- for collection_id in collection_ids:- referenced_attr_values = get_attribute_values_by_referenced_collection_ids(- ids=[collection_id], db_connection_name=db_connection_name- )- expression &= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression---def _filter_by_contains_any_referenced_object_ids(- variant_ids: set[int],- product_ids: set[int],- page_ids: set[int],- category_ids: set[int],- collection_ids: set[int],- attr_id: int | None,- db_connection_name: str,-) -> Q:- expression = Q()- if page_ids:- referenced_attr_values = get_attribute_values_by_referenced_page_ids(- ids=list(page_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if product_ids:- referenced_attr_values = get_attribute_values_by_referenced_product_ids(- ids=list(product_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if variant_ids:- referenced_attr_values = get_attribute_values_by_referenced_variant_ids(- ids=list(variant_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if category_ids:- referenced_attr_values = get_attribute_values_by_referenced_category_ids(- ids=list(category_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- if collection_ids:- referenced_attr_values = get_attribute_values_by_referenced_collection_ids(- ids=list(collection_ids), db_connection_name=db_connection_name- )- expression |= _filter_contains_single_expression(- attr_id=attr_id,- db_connection_name=db_connection_name,- referenced_attr_values=referenced_attr_values,- )- return expression---def filter_by_contains_referenced_object_ids(- attr_id: int | None,- attr_value: CONTAINS_TYPING,- db_connection_name: str,-) -> Q:- contains_all = attr_value.get("contains_all")- contains_any = attr_value.get("contains_any")-- grouped_ids = clean_up_referenced_global_ids(contains_any or contains_all or [])- variant_ids = grouped_ids["ProductVariant"]- product_ids = grouped_ids["Product"]- page_ids = grouped_ids["Page"]- category_ids = grouped_ids["Category"]- collection_ids = grouped_ids["Collection"]-- if contains_all:- return _filter_by_contains_all_referenced_object_ids(- variant_ids=variant_ids,- product_ids=product_ids,- page_ids=page_ids,- category_ids=category_ids,- collection_ids=collection_ids,- attr_id=attr_id,- db_connection_name=db_connection_name,- )- if contains_any:- return _filter_by_contains_any_referenced_object_ids(- variant_ids=variant_ids,- product_ids=product_ids,- page_ids=page_ids,- category_ids=category_ids,- collection_ids=collection_ids,- attr_id=attr_id,- db_connection_name=db_connection_name,- )- return Q()---def filter_objects_by_reference_attributes(- attr_id: int | None,- attr_value: dict[- Literal[- "referenced_ids",- "page_slugs",- "product_slugs",- "product_variant_skus",- "category_slugs",- "collection_slugs",- ],- CONTAINS_TYPING,- ],- db_connection_name: str,-):- filter_expression = Q()-- if "referenced_ids" in attr_value:- filter_expression &= filter_by_contains_referenced_object_ids(- attr_id,- attr_value["referenced_ids"],- db_connection_name,- )- if "page_slugs" in attr_value:- filter_expression &= filter_by_contains_referenced_page_slugs(- attr_id,- attr_value["page_slugs"],- db_connection_name,- )- if "product_slugs" in attr_value:- filter_expression &= filter_by_contains_referenced_product_slugs(- attr_id,- attr_value["product_slugs"],- db_connection_name,- )- if "product_variant_skus" in attr_value:- filter_expression &= filter_by_contains_referenced_variant_skus(- attr_id,- attr_value["product_variant_skus"],- db_connection_name,- )- if "category_slugs" in attr_value:- filter_expression &= filter_by_contains_referenced_category_slugs(- attr_id,- attr_value["category_slugs"],- db_connection_name,- )- if "collection_slugs" in attr_value:- filter_expression &= filter_by_contains_referenced_collection_slugs(- attr_id,- attr_value["collection_slugs"],- db_connection_name,- )- return filter_expression--def filter_variants_by_attributes(qs: QuerySet[ProductVariant], value: list[dict]) -> QuerySet[ProductVariant]:- attribute_slugs = {- attr_filter["slug"] for attr_filter in value if "slug" in attr_filter- }- attributes_map = {- attr.slug: attr- for attr in Attribute.objects.using(qs.db).filter(slug__in=attribute_slugs)- }- if len(attribute_slugs) != len(attributes_map.keys()):- # Filter over non existing attribute- return qs.none()-- attr_filter_expression = Q()-- attr_without_values_input = []- for attr_filter in value:- if "slug" in attr_filter and "value" not in attr_filter:- attr_without_values_input.append(attributes_map[attr_filter["slug"]])-- if attr_without_values_input:- atr_value_qs = AttributeValue.objects.using(qs.db).filter(- attribute_id__in=[attr.id for attr in attr_without_values_input]- )- attr_filter_expression = _get_assigned_variant_attribute_for_attribute_value_qs(- atr_value_qs,- qs.db,- )-- for attr_filter in value:- attr_value = attr_filter.get("value")- if not attr_value:- # attrs without value input are handled separately- continue-- attr_id = None- if attr_slug := attr_filter.get("slug"):- attr = attributes_map[attr_slug]- attr_id = attr.id-- attr_value = attr_filter["value"]-- if "slug" in attr_value or "name" in attr_value:- attr_filter_expression &= filter_by_slug_or_name(- attr_id,- attr_value,- qs.db,- )- elif "numeric" in attr_value:- attr_filter_expression &= filter_by_numeric_attribute(- attr_id,- attr_value["numeric"],- qs.db,- )- elif "boolean" in attr_value:- attr_filter_expression &= filter_by_boolean_attribute(- attr_id,- attr_value["boolean"],- qs.db,- )- elif "date" in attr_value:- attr_filter_expression &= filter_by_date_attribute(- attr_id,- attr_value["date"],- qs.db,- )- elif "date_time" in attr_value:- attr_filter_expression &= filter_by_date_time_attribute(- attr_id,- attr_value["date_time"],- qs.db,- )- elif "reference" in attr_value:- attr_filter_expression &= filter_objects_by_reference_attributes(- attr_id,- attr_value["reference"],- qs.db,- )- return qs.filter(attr_filter_expression)+ return filter_objects_by_attributes(+ qs,+ value,+ _get_assigned_variant_attribute_for_attribute_value_qs,+ )class ProductVariantFilter(MetadataFilterBase):diff --git a/saleor/graphql/product/tests/queries/variants_where/test_over_references_pages.py b/saleor/graphql/product/tests/queries/variants_where/test_over_references_pages.pyindex 306efb1cf9..64750d0ca0 100644--- a/saleor/graphql/product/tests/queries/variants_where/test_over_references_pages.py+++ b/saleor/graphql/product/tests/queries/variants_where/test_over_references_pages.py@@ -344,3 +344,23 @@ def test_product_variants_query_with_attr_slug_and_attribute_value_referenced_pacontent = get_graphql_content(response)product_variants_nodes = content["data"]["productVariants"]["edges"]assert len(product_variants_nodes) == expected_count+++def test_product_variants_query_with_empty_page_slugs_container_matches_no_variants(+ staff_api_client,+ product_variant_list,+ channel_USD,+):+ # given: a no-op reference filter - the container declares no+ # containsAny/containsAll key+ variables = {+ "where": {"attributes": [{"value": {"reference": {"pageSlugs": {}}}}]},+ "channel": channel_USD.slug,+ }++ # when+ response = staff_api_client.post_graphql(PRODUCT_VARIANTS_WHERE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["productVariants"]["edges"] == []diff --git a/saleor/graphql/query_cost_map.py b/saleor/graphql/query_cost_map.pyindex d860616021..1f68810bb7 100644--- a/saleor/graphql/query_cost_map.py+++ b/saleor/graphql/query_cost_map.py@@ -75,6 +75,8 @@ COST_MAP = {"collection": {"complexity": 1},"collections": {"complexity": 1, "multipliers": ["first", "last"]},"customers": {"complexity": 1, "multipliers": ["first", "last"]},+ "customerType": {"complexity": 1},+ "customerTypes": {"complexity": 1, "multipliers": ["first", "last"]},"draftOrders": {"complexity": 1, "multipliers": ["first", "last"]},"exportFile": {"complexity": 1},"exportFiles": {"complexity": 1, "multipliers": ["first", "last"]},@@ -259,6 +261,10 @@ COST_MAP = {"CollectionChannelListing": {"channel": {"complexity": 1},},+ "CustomerType": {+ "attributes": {"complexity": 1},+ "availableAttributes": {"complexity": 1, "multipliers": ["first", "last"]},+ },"Fulfillment": {"lines": {"complexity": 1},"warehouse": {"complexity": 1},@@ -421,8 +427,11 @@ COST_MAP = {"countries": {"complexity": 1},},"User": {+ "assignedAttribute": {"complexity": 1},+ "assignedAttributes": {"complexity": 1, "multipliers": ["limit"]},"avatar": {"complexity": 1},"checkout": {"complexity": 1},+ "customerType": {"complexity": 1},"editableGroups": {"complexity": 1},"events": {"complexity": 1},"giftCards": {"complexity": 1, "multipliers": ["first", "last"]},diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 6469d8be0b..557c9953be 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1560,6 +1560,52 @@ type Query {last: Int): UserCountableConnection @doc(category: "Users")+ """+ Look up a customer type by ID.++ Added in Saleor 3.23.++ Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES, MANAGE_USERS.+ """+ customerType(+ """ID of the customer type."""+ id: ID!+ ): CustomerType @doc(category: "Users")++ """+ List of the customer types.++ Added in Saleor 3.23.++ Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES, MANAGE_USERS.+ """+ customerTypes(+ """Where filtering options for customer types."""+ where: CustomerTypeWhereInput++ """Search customer types by name or slug."""+ search: String++ """Sort customer types."""+ sortBy: CustomerTypeSortingInput++ """Return the elements in the list that come before the specified cursor."""+ before: String++ """Return the elements in the list that come after the specified cursor."""+ after: String++ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int++ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): CustomerTypeCountableConnection @doc(category: "Users")+"""List of permission groups.@@ -1982,6 +2028,27 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {"""A customer account metadata is updated."""CUSTOMER_METADATA_UPDATED+ """+ A new customer type is created.++ Added in Saleor 3.23.+ """+ CUSTOMER_TYPE_CREATED++ """+ A customer type is updated.++ Added in Saleor 3.23.+ """+ CUSTOMER_TYPE_UPDATED++ """+ A customer type is deleted.++ Added in Saleor 3.23.+ """+ CUSTOMER_TYPE_DELETED+"""A new collection is created."""COLLECTION_CREATED@@ -2591,6 +2658,27 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {"""A customer account metadata is updated."""CUSTOMER_METADATA_UPDATED+ """+ A new customer type is created.++ Added in Saleor 3.23.+ """+ CUSTOMER_TYPE_CREATED++ """+ A customer type is updated.++ Added in Saleor 3.23.+ """+ CUSTOMER_TYPE_UPDATED++ """+ A customer type is deleted.++ Added in Saleor 3.23.+ """+ CUSTOMER_TYPE_DELETED+"""A new collection is created."""COLLECTION_CREATED@@ -3022,6 +3110,7 @@ enum PermissionEnum @doc(category: "Users") {HANDLE_TAXESMANAGE_TAXESMANAGE_CHANNELS+ MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTESMANAGE_DISCOUNTSMANAGE_GIFT_CARDMANAGE_MENUS@@ -3224,7 +3313,7 @@ enum AppProblemDismissedByEnum @doc(category: "Apps") {}"""Represents user data."""-type User implements Node & ObjectWithMetadata @doc(category: "Users") {+type User implements Node & ObjectWithMetadata & ObjectWithAttributes @doc(category: "Users") {"""The ID of the user."""id: ID!@@ -3258,6 +3347,26 @@ type User implements Node & ObjectWithMetadata @doc(category: "Users") {"""metafields(keys: [String!]): Metadata+ """+ Get a single attribute assigned to the user by attribute slug. The attribute is looked up among the attributes of the user's customer type. Requires one of the following permissions: MANAGE_USERS, OWNER. The owner can access only attributes that are visible in the storefront.++ Added in Saleor 3.23.+ """+ assignedAttribute(+ """Slug of the attribute"""+ slug: String!+ ): AssignedAttribute++ """+ List of attributes assigned to the user through the user's customer type. Requires one of the following permissions: MANAGE_USERS, OWNER. The owner can access only attributes that are visible in the storefront.++ Added in Saleor 3.23.+ """+ assignedAttributes(+ """Maximum number of attributes to return. Default is 100."""+ limit: PositiveInt = 100+ ): [AssignedAttribute!]!+"""The email address of the user."""email: String!@@ -3431,6 +3540,13 @@ type User implements Node & ObjectWithMetadata @doc(category: "Users") {"""External ID of this user."""externalReference: String+ """+ The customer type assigned to the user. Requires one of the following permissions: MANAGE_USERS, OWNER.++ Added in Saleor 3.23.+ """+ customerType: CustomerType+"""The date when the user last time log in to the system."""lastLogin: DateTime@@ -3449,9 +3565,48 @@ type User implements Node & ObjectWithMetadata @doc(category: "Users") {): [StoredPaymentMethod!]}-"""Represents user address data."""-type Address implements Node & ObjectWithMetadata @doc(category: "Users") {- """The ID of the address."""+"""+An object with attributes.++Added in Saleor 3.22.+"""+interface ObjectWithAttributes @doc(category: "Attributes") {+ """+ Get a single attribute attached to the object by attribute slug.++ Added in Saleor 3.22.+ """+ assignedAttribute(+ """Slug of the attribute"""+ slug: String!+ ): AssignedAttribute @doc(category: "Attributes")++ """+ List of attributes assigned to the object.++ Added in Saleor 3.22.+ """+ assignedAttributes(+ """Maximum number of attributes to return. Default is 100."""+ limit: PositiveInt = 100+ ): [AssignedAttribute!]!+}++"""+Represents an attribute assigned to an object.++Added in Saleor 3.22.+"""+interface AssignedAttribute @doc(category: "Attributes") {+ """Attribute assigned to an object."""+ attribute: Attribute!+}++"""+Custom attribute of a product. Attributes can be assigned to products and variants at the product type level.+"""+type Attribute implements Node & ObjectWithMetadata @doc(category: "Attributes") {+ """The ID of the attribute."""id: ID!"""List of private metadata items. Requires staff permissions to access."""@@ -3484,81 +3639,197 @@ type Address implements Node & ObjectWithMetadata @doc(category: "Users") {"""metafields(keys: [String!]): Metadata- """The given name of the address."""- firstName: String!+ """The input type to use for entering attribute values in the dashboard."""+ inputType: AttributeInputTypeEnum- """The family name of the address."""- lastName: String!+ """The entity type which can be used as a reference."""+ entityType: AttributeEntityTypeEnum- """Company or organization name."""- companyName: String!+ """+ The reference types (product or page type) that are used to narrow down the choices of reference objects.++ Added in Saleor 3.22.+ """+ referenceTypes(+ """+ Maximum number of objects to return. Value must be greater than 0. Default is 100.+ """+ limit: PositiveInt = 100+ ): [ReferenceType!]- """The first line of the address."""- streetAddress1: String!+ """Name of an attribute displayed in the interface."""+ name: String!- """The second line of the address."""- streetAddress2: String!+ """Internal representation of an attribute name."""+ slug: String!- """The city of the address."""- city: String!+ """The attribute type."""+ type: AttributeTypeEnum!- """The district of the address."""- cityArea: String!+ """The unit of attribute values."""+ unit: MeasurementUnitsEnum- """The postal code of the address."""- postalCode: String!+ """+ A list of predefined attribute choices available for selection. Available only for attributes with predefined choices.+ """+ choices(+ """Sort attribute choices."""+ sortBy: AttributeChoicesSortingInput- """The country of the address."""- country: CountryDisplay!+ """Filtering options for attribute choices."""+ filter: AttributeValueFilterInput @deprecated(reason: "Use `where` filter instead.")- """The country area of the address."""- countryArea: String!+ """+ Where filtering options for attribute choices.++ Added in Saleor 3.22.+ """+ where: AttributeValueWhereInput- """The phone number assigned the address."""- phone: String+ """+ Search attribute choices.++ Added in Saleor 3.22.+ """+ search: String- """Address is user's default shipping address."""- isDefaultShippingAddress: Boolean+ """Return the elements in the list that come before the specified cursor."""+ before: String- """Address is user's default billing address."""- isDefaultBillingAddress: Boolean-}+ """Return the elements in the list that come after the specified cursor."""+ after: String-type CountryDisplay {- """Country code."""- code: String!+ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int- """Country name."""- country: String!+ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): AttributeValueCountableConnection- """Country tax."""- vat: VAT @deprecated(reason: "Always returns `null`. Use `TaxClassCountryRate` type to manage tax rates per country.")-}+ """+ Whether the attribute requires values to be passed or not. Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ """+ valueRequired: Boolean!-"""Represents a VAT rate for a country."""-type VAT @doc(category: "Taxes") {- """Country code."""- countryCode: String!+ """+ Whether the attribute should be visible or not in storefront. Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ """+ visibleInStorefront: Boolean!- """Standard VAT rate in percent."""- standardRate: Float+ """+ Whether the attribute can be filtered in storefront. Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ """+ filterableInStorefront: Boolean! @deprecated- """Country's VAT rate exceptions for specific types of goods."""- reducedRates: [ReducedRate!]!+ """+ Whether the attribute can be filtered in dashboard. Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ """+ filterableInDashboard: Boolean!++ """+ Whether the attribute can be displayed in the admin product list. Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ """+ availableInGrid: Boolean! @deprecated++ """+ The position of the attribute in the storefront navigation (0 by default). Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ """+ storefrontSearchPosition: Int! @deprecated++ """Returns translated attribute fields for the given language code."""+ translation(+ """A language code to return the translation for attribute."""+ languageCode: LanguageCodeEnum!+ ): AttributeTranslation++ """Flag indicating that attribute has predefined choices."""+ withChoices: Boolean!++ """+ A list of product types that use this attribute as a product attribute.+ """+ productTypes(+ """Return the elements in the list that come before the specified cursor."""+ before: String++ """Return the elements in the list that come after the specified cursor."""+ after: String++ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int++ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): ProductTypeCountableConnection!++ """+ A list of product types that use this attribute as a product variant attribute.+ """+ productVariantTypes(+ """Return the elements in the list that come before the specified cursor."""+ before: String++ """Return the elements in the list that come after the specified cursor."""+ after: String++ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int++ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): ProductTypeCountableConnection!++ """External ID of this attribute."""+ externalReference: String}-"""Represents a reduced VAT rate for a particular type of goods."""-type ReducedRate @doc(category: "Taxes") {- """Reduced VAT rate in percent."""- rate: Float!+enum AttributeInputTypeEnum @doc(category: "Attributes") {+ DROPDOWN+ MULTISELECT+ FILE+ REFERENCE+ SINGLE_REFERENCE+ NUMERIC+ RICH_TEXT+ PLAIN_TEXT+ SWATCH+ BOOLEAN+ DATE+ DATE_TIME+}- """A type of goods."""- rateType: String!+enum AttributeEntityTypeEnum @doc(category: "Attributes") {+ PAGE+ PRODUCT+ PRODUCT_VARIANT+ CATEGORY+ COLLECTION}-"""Checkout object."""-type Checkout implements Node & ObjectWithMetadata @doc(category: "Checkout") {- """The ID of the checkout."""+"""+The reference types (product or page type) that are used to narrow down the choices of reference objects.+ProductType applicable for reference attribute with `PRODUCT` or `PRODUCT_VARIANT` entity type.+PageType applicable for reference attribute with `PAGE` entity type.+"""+union ReferenceType = ProductType | PageType++"""+Represents a type of product. It defines what attributes are available to products of this type.+"""+type ProductType implements Node & ObjectWithMetadata @doc(category: "Products") {+ """The ID of the product type."""id: ID!"""List of private metadata items. Requires staff permissions to access."""@@ -3591,209 +3862,165 @@ type Checkout implements Node & ObjectWithMetadata @doc(category: "Checkout") {"""metafields(keys: [String!]): Metadata- """The date and time when the checkout was created."""- created: DateTime!+ """Name of the product type."""+ name: String!- """Time of last modification of the given checkout."""- updatedAt: DateTime!- lastChange: DateTime! @deprecated(reason: "Use `updatedAt` instead.")+ """Slug of the product type."""+ slug: String!- """- The user assigned to the checkout. Requires one of the following permissions: MANAGE_USERS, HANDLE_PAYMENTS, OWNER.- """- user: User+ """Whether the product type has variants."""+ hasVariants: Boolean! @deprecated(reason: "This is a leftover from the past Simple/Configurable product distinction. Products can have multiple variants regardless of this setting. ")- """The channel for which checkout was created."""- channel: Channel!+ """Whether shipping is required for this product type."""+ isShippingRequired: Boolean!- """The billing address of the checkout."""- billingAddress: Address+ """Weight of the product type."""+ weight: Weight- """The shipping address of the checkout."""- shippingAddress: Address+ """The product type kind."""+ kind: ProductTypeKindEnum!- """The customer note for the checkout."""- customerNote: String!+ """List of products of this type."""+ products(+ """Slug of a channel for which the data should be returned."""+ channel: String- """- The total discount applied to the checkout. Note: Only discount created via voucher are included in this field.- """- discount: Money+ """Return the elements in the list that come before the specified cursor."""+ before: String- """The name of voucher assigned to the checkout."""- discountName: String+ """Return the elements in the list that come after the specified cursor."""+ after: String- """- Translation of the discountName field in the language set in Checkout.languageCode field.Note: this field is set automatically when Checkout.languageCode is defined; otherwise it's null- """- translatedDiscountName: String+ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int- """- The voucher assigned to the checkout.-- Requires one of the following permissions: MANAGE_DISCOUNTS.- """- voucher: Voucher+ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): ProductCountableConnection @deprecated(reason: "Use the top-level `products` query with the `productTypes` filter.")- """The code of voucher assigned to the checkout."""- voucherCode: String+ """A type of tax. Assigned by enabled tax gateway"""+ taxType: TaxType @deprecated(reason: "Use `taxClass` field instead.")"""- Shipping methods that can be used with this checkout.+ Tax class assigned to this product type. All products of this product type use this tax class, unless it's overridden in the `Product` type.- Triggers the following webhook events:- - SHIPPING_LIST_METHODS_FOR_CHECKOUT (sync): Optionally triggered when cached external shipping methods are invalid.- - CHECKOUT_FILTER_SHIPPING_METHODS (sync): Optionally triggered when cached filtered shipping methods are invalid.+ Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP."""- availableShippingMethods: [ShippingMethod!]! @webhookEventsInfo(asyncEvents: [], syncEvents: [SHIPPING_LIST_METHODS_FOR_CHECKOUT, CHECKOUT_FILTER_SHIPPING_METHODS]) @deprecated(reason: "Use `shippingMethods` instead.")+ taxClass: TaxClass++ """Variant attributes of that product type."""+ variantAttributes(+ """Define scope of returned attributes."""+ variantSelection: VariantAttributeScope+ ): [Attribute!] @deprecated(reason: "Use `assignedVariantAttributes` instead.")"""- Shipping methods that can be used with this checkout.-- Triggers the following webhook events:- - SHIPPING_LIST_METHODS_FOR_CHECKOUT (sync): Optionally triggered when cached external shipping methods are invalid.- - CHECKOUT_FILTER_SHIPPING_METHODS (sync): Optionally triggered when cached filtered shipping methods are invalid.+ Variant attributes of that product type with attached variant selection."""- shippingMethods: [ShippingMethod!]! @webhookEventsInfo(asyncEvents: [], syncEvents: [SHIPPING_LIST_METHODS_FOR_CHECKOUT, CHECKOUT_FILTER_SHIPPING_METHODS])+ assignedVariantAttributes(+ """Define scope of returned attributes."""+ variantSelection: VariantAttributeScope+ ): [AssignedVariantAttribute!]- """Collection points that can be used for this order."""- availableCollectionPoints: [Warehouse!]!+ """Product attributes of that product type."""+ productAttributes: [Attribute!]"""- List of available payment gateways.+ List of attributes which can be assigned to this product type.- Triggers the following webhook events:- - PAYMENT_LIST_GATEWAYS (sync): Fetch payment gateways available for checkout.+ Requires one of the following permissions: MANAGE_PRODUCTS."""- availablePaymentGateways: [PaymentGateway!]! @webhookEventsInfo(asyncEvents: [], syncEvents: [PAYMENT_LIST_GATEWAYS]) @deprecated(reason: "The legacy Payments API is deprecated and will be removed. Use the Transactions API instead.")-- """Email of a customer."""- email: String-- """List of gift cards associated with this checkout."""- giftCards: [GiftCard!]!-- """Returns True, if checkout requires shipping."""- isShippingRequired: Boolean!-- """The number of items purchased."""- quantity: Int!+ availableAttributes(+ """Filtering options for attributes of this product type."""+ filter: AttributeFilterInput @deprecated(reason: "Use `where` filter instead.")- """- Date when oldest stock reservation for this checkout expires or null if no stock is reserved.- """- stockReservationExpires: DateTime+ """Where filtering options for attributes of this product type."""+ where: AttributeWhereInput- """- A list of checkout lines, each containing information about an item in the checkout.- """- lines: [CheckoutLine!]!+ """Search attributes."""+ search: String- """- The price of the shipping, with all the taxes included. Set to 0 when no delivery method is selected.-- Triggers the following webhook events:- - CHECKOUT_CALCULATE_TAXES (sync): Optionally triggered when checkout prices are expired.- """- shippingPrice: TaxedMoney! @webhookEventsInfo(asyncEvents: [], syncEvents: [CHECKOUT_CALCULATE_TAXES])+ """Return the elements in the list that come before the specified cursor."""+ before: String- """- The delivery method selected for this checkout.-- Added in Saleor 3.23.- """- delivery: Delivery+ """Return the elements in the list that come after the specified cursor."""+ after: String- """- The shipping method related with checkout.-- Triggers the following webhook events:- - SHIPPING_LIST_METHODS_FOR_CHECKOUT (sync): Optionally triggered when cached external shipping methods are invalid.- - CHECKOUT_FILTER_SHIPPING_METHODS (sync): Optionally triggered when cached filtered shipping methods are invalid.- """- shippingMethod: ShippingMethod @webhookEventsInfo(asyncEvents: [], syncEvents: [SHIPPING_LIST_METHODS_FOR_CHECKOUT, CHECKOUT_FILTER_SHIPPING_METHODS]) @deprecated(reason: "Use `delivery` instead.")+ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int- """- The delivery method selected for this checkout.-- Triggers the following webhook events:- - SHIPPING_LIST_METHODS_FOR_CHECKOUT (sync): Optionally triggered when cached external shipping methods are invalid.- - CHECKOUT_FILTER_SHIPPING_METHODS (sync): Optionally triggered when cached filtered shipping methods are invalid.- """- deliveryMethod: DeliveryMethod @webhookEventsInfo(asyncEvents: [], syncEvents: [SHIPPING_LIST_METHODS_FOR_CHECKOUT, CHECKOUT_FILTER_SHIPPING_METHODS]) @deprecated(reason: "Use `delivery` instead.")+ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): AttributeCountableConnection+}- """- The price of the checkout before shipping, with taxes included.-- Triggers the following webhook events:- - CHECKOUT_CALCULATE_TAXES (sync): Optionally triggered when checkout prices are expired.- """- subtotalPrice: TaxedMoney! @webhookEventsInfo(asyncEvents: [], syncEvents: [CHECKOUT_CALCULATE_TAXES])+"""Represents weight value in a specific weight unit."""+type Weight {+ """Weight unit."""+ unit: WeightUnitsEnum!- """Returns True if checkout has to be exempt from taxes."""- taxExemption: Boolean!+ """Weight value. Returns a value with maximal three decimal places"""+ value: Float!+}- """The checkout's token."""- token: UUID!+enum WeightUnitsEnum {+ G+ LB+ OZ+ KG+ TONNE+}- """- The sum of the checkout line prices, with all the taxes,shipping costs, and discounts included.-- Triggers the following webhook events:- - CHECKOUT_CALCULATE_TAXES (sync): Optionally triggered when checkout prices are expired.- """- totalPrice: TaxedMoney! @webhookEventsInfo(asyncEvents: [], syncEvents: [CHECKOUT_CALCULATE_TAXES])+enum ProductTypeKindEnum @doc(category: "Products") {+ NORMAL+ GIFT_CARD+}- """- The difference between the paid and the checkout total amount.-- Triggers the following webhook events:- - CHECKOUT_CALCULATE_TAXES (sync): Optionally triggered when checkout prices are expired.- """- totalBalance: Money! @webhookEventsInfo(asyncEvents: [], syncEvents: [CHECKOUT_CALCULATE_TAXES])+type ProductCountableConnection @doc(category: "Products") {+ """Pagination data for this connection."""+ pageInfo: PageInfo!+ edges: [ProductCountableEdge!]!- """Checkout language code."""- languageCode: LanguageCodeEnum!+ """A total count of items in the collection."""+ totalCount: Int+}- """- List of transactions for the checkout. Requires one of the following permissions: MANAGE_CHECKOUTS, HANDLE_PAYMENTS.- """- transactions: [TransactionItem!]+"""+The Relay compliant `PageInfo` type, containing data necessary to paginate this connection.+"""+type PageInfo {+ """When paginating forwards, are there more items?"""+ hasNextPage: Boolean!- """Determines whether displayed prices should include taxes."""- displayGrossPrices: Boolean!+ """When paginating backwards, are there more items?"""+ hasPreviousPage: Boolean!- """- The authorize status of the checkout.-- Triggers the following webhook events:- - CHECKOUT_CALCULATE_TAXES (sync): Optionally triggered when checkout prices are expired.- """- authorizeStatus: CheckoutAuthorizeStatusEnum! @webhookEventsInfo(asyncEvents: [], syncEvents: [CHECKOUT_CALCULATE_TAXES])+ """When paginating backwards, the cursor to continue."""+ startCursor: String- """- The charge status of the checkout.-- Triggers the following webhook events:- - CHECKOUT_CALCULATE_TAXES (sync): Optionally triggered when checkout prices are expired.- """- chargeStatus: CheckoutChargeStatusEnum! @webhookEventsInfo(asyncEvents: [], syncEvents: [CHECKOUT_CALCULATE_TAXES])+ """When paginating forwards, the cursor to continue."""+ endCursor: String+}- """- List of user's stored payment methods that can be used in this checkout session. It uses the channel that the checkout was created in. When `amount` is not provided, `checkout.total` will be used as a default value.- """- storedPaymentMethods(- """Amount that will be used to fetch stored payment methods."""- amount: PositiveDecimal- ): [StoredPaymentMethod!]+type ProductCountableEdge @doc(category: "Products") {+ """The item at the end of the edge."""+ node: Product!- """List of problems with the checkout."""- problems: [CheckoutProblem!]+ """A cursor for use in pagination."""+ cursor: String!}-"""Represents channel."""-type Channel implements Node & ObjectWithMetadata @doc(category: "Channels") {- """The ID of the channel."""+"""Represents an individual item for sale in the storefront."""+type Product implements Node & ObjectWithMetadata & ObjectWithAttributes @doc(category: "Products") {+ """The ID of the product."""id: ID!"""List of private metadata items. Requires staff permissions to access."""@@ -3826,96 +4053,232 @@ type Channel implements Node & ObjectWithMetadata @doc(category: "Channels") {"""metafields(keys: [String!]): Metadata- """Slug of the channel."""- slug: String!+ """+ Get a single attribute attached to product by attribute slug.++ Added in Saleor 3.22.+ """+ assignedAttribute(+ """Slug of the attribute"""+ slug: String!+ ): AssignedAttribute"""- Name of the channel.+ List of attributes assigned to this product.- Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER.+ Added in Saleor 3.22."""+ assignedAttributes(+ """Maximum number of attributes to return. Default is 100."""+ limit: PositiveInt = 100+ ): [AssignedAttribute!]!++ """SEO title of the product."""+ seoTitle: String++ """SEO description of the product."""+ seoDescription: String++ """SEO description of the product."""name: String!"""- Whether the channel is active.+ Description of the product.- Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER.+ Rich text format. For reference see https://editorjs.io/"""- isActive: Boolean!+ description: JSONString++ """Type of the product."""+ productType: ProductType!++ """Slug of the product."""+ slug: String!+ category: Category++ """The date and time when the product was created."""+ created: DateTime!++ """The date and time when the product was last updated."""+ updatedAt: DateTime!+ chargeTaxes: Boolean! @deprecated(reason: "Use `Channel.taxConfiguration` field to determine whether tax collection is enabled.")++ """Weight of the product."""+ weight: Weight++ """Default variant of the product."""+ defaultVariant: ProductVariant++ """Rating of the product."""+ rating: Float"""- A currency that is assigned to the channel.-- Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER.+ Channel given to retrieve this product. Also used by federation gateway to resolve this object in a federated query."""- currencyCode: String!+ channel: String"""- Whether a channel has associated orders.+ Description of the product.- Requires one of the following permissions: MANAGE_CHANNELS.+ Rich text format. For reference see https://editorjs.io/"""- hasOrders: Boolean!+ descriptionJson: JSONString @deprecated(reason: "Use the `description` field instead.")++ """Thumbnail of the product."""+ thumbnail(+ """+ Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).+ """+ size: Int++ """+ The format of the image. When not provided, format of the original image will be used.+ """+ format: ThumbnailFormatEnum = ORIGINAL+ ): Image"""- Default country for the channel. Default country can be used in checkout to determine the stock quantities or calculate taxes when the country was not explicitly provided.-- Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER.+ Lists the storefront product's pricing, the current price and discounts, only meant for displaying."""- defaultCountry: CountryDisplay!+ pricing(+ """+ Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration.+ """+ address: AddressInput+ ): ProductPricingInfo"""- List of warehouses assigned to this channel.-- Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER.+ Whether the product is in stock, set as available for purchase in the given channel, and published."""- warehouses: [Warehouse!]!+ isAvailable(+ """+ Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration. When `Shop.useLegacyShippingZoneStockAvailability` is disabled, this argument is ignored — stock availability is determined by the direct warehouse-channel link instead of shipping zones.+ """+ address: AddressInput @deprecated+ ): Boolean- """List of shippable countries for the channel."""- countries: [CountryDisplay!]+ """A type of tax. Assigned by enabled tax gateway"""+ taxType: TaxType @deprecated(reason: "Use `taxClass` field instead.")- """Shipping methods that are available for the channel."""- availableShippingMethodsPerCountry(countries: [CountryCode!]): [ShippingMethodsPerCountry!]+ """Get a single attribute attached to product by attribute slug."""+ attribute(+ """Slug of the attribute"""+ slug: String!+ ): SelectedAttribute @deprecated(reason: "Use the `assignedAttribute` field instead.")++ """List of attributes assigned to this product."""+ attributes: [SelectedAttribute!]! @deprecated(reason: "Use the `assignedAttributes` field instead.")"""- Define the stock setting for this channel.+ List of availability in channels for the product.- Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER.+ Requires one of the following permissions: MANAGE_PRODUCTS."""- stockSettings: StockSettings!+ channelListings: [ProductChannelListing!]++ """Get a single product media by ID."""+ mediaById(+ """ID of a product media."""+ id: ID!+ ): ProductMedia++ """Get a single product image by ID."""+ imageById(+ """ID of a product image."""+ id: ID!+ ): ProductImage @deprecated(reason: "Use the `mediaById` field instead.")"""- Channel-specific order settings.-- Requires one of the following permissions: MANAGE_CHANNELS, MANAGE_ORDERS.+ List of variants for the product. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS."""- orderSettings: OrderSettings!+ variants: [ProductVariant!] @deprecated(reason: "Use `productVariants` field instead.")"""- Channel-specific checkout settings.-- Requires one of the following permissions: MANAGE_CHANNELS, MANAGE_CHECKOUTS.+ List of variants for the product. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS."""- checkoutSettings: CheckoutSettings!+ productVariants(+ """Filtering options for product variant."""+ filter: ProductVariantFilterInput @deprecated(reason: "Use `where` filter instead.")++ """Where filtering options for product variants."""+ where: ProductVariantWhereInput++ """Sort products variants."""+ sortBy: ProductVariantSortingInput++ """Return the elements in the list that come before the specified cursor."""+ before: String++ """Return the elements in the list that come after the specified cursor."""+ after: String++ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int++ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): ProductVariantCountableConnection++ """List of media for the product."""+ media(+ """Sort media."""+ sortBy: MediaSortingInput+ ): [ProductMedia!]++ """List of images for the product."""+ images: [ProductImage!] @deprecated(reason: "Use the `media` field instead.")"""- Channel-specific payment settings.-- Requires one of the following permissions: MANAGE_CHANNELS, HANDLE_PAYMENTS.+ List of collections for the product. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS."""- paymentSettings: PaymentSettings!+ collections: [Collection!]++ """Returns translated product fields for the given language code."""+ translation(+ """A language code to return the translation for product."""+ languageCode: LanguageCodeEnum!+ ): ProductTranslation++ """Date when product is available for purchase."""+ availableForPurchase: Date @deprecated(reason: "Use the `availableForPurchaseAt` field to fetch the available for purchase date.")++ """Date when product is available for purchase."""+ availableForPurchaseAt: DateTime"""- Channel specific tax configuration.+ Refers to a state that can be set by admins to control whether a product is available for purchase in storefronts. This does not guarantee the availability of stock. When set to `False`, this product is still visible to customers, but it cannot be purchased.+ """+ isAvailableForPurchase: Boolean++ """+ Tax class assigned to this product type. All products of this product type use this tax class, unless it's overridden in the `Product` type.Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP."""- taxConfiguration: TaxConfiguration!+ taxClass: TaxClass++ """External ID of this product."""+ externalReference: String}-"""Represents warehouse."""-type Warehouse implements Node & ObjectWithMetadata @doc(category: "Products") {- """The ID of the warehouse."""+"""+Positive Integer scalar implementation.++Should be used in places where value must be positive (greater than 0).+"""+scalar PositiveInt++scalar JSONString++"""+Represents a single category of products. Categories allow to organize products in a tree-hierarchies which can be used for navigation in the storefront.+"""+type Category implements Node & ObjectWithMetadata @doc(category: "Products") {+ """The ID of the category."""id: ID!"""List of private metadata items. Requires staff permissions to access."""@@ -3948,29 +4311,43 @@ type Warehouse implements Node & ObjectWithMetadata @doc(category: "Products") {"""metafields(keys: [String!]): Metadata- """Warehouse name."""- name: String!+ """SEO title of category."""+ seoTitle: String- """Warehouse slug."""- slug: String!+ """SEO description of category."""+ seoDescription: String- """Warehouse email."""- email: String!+ """Name of category"""+ name: String!- """Determine if the warehouse is private."""- isPrivate: Boolean!+ """+ Description of the category.++ Rich text format. For reference see https://editorjs.io/+ """+ description: JSONString- """Address of the warehouse."""- address: Address!+ """Slug of the category."""+ slug: String!- """Warehouse company name."""- companyName: String! @deprecated(reason: "Use `Address.companyName` instead.")+ """Parent category."""+ parent: Category- """Click and collect options: local, all or disabled."""- clickAndCollectOption: WarehouseClickAndCollectOptionEnum!+ """Level of the category."""+ level: Int!- """Shipping zones supported by the warehouse."""- shippingZones(+ """+ Description of the category.++ Rich text format. For reference see https://editorjs.io/+ """+ descriptionJson: JSONString @deprecated(reason: "Use the `description` field instead.")++ """The date and time when the category was last updated."""+ updatedAt: DateTime!++ """List of ancestors of the category."""+ ancestors("""Return the elements in the list that come before the specified cursor."""before: String@@ -3986,14 +4363,27 @@ type Warehouse implements Node & ObjectWithMetadata @doc(category: "Products") {Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query."""last: Int- ): ShippingZoneCountableConnection!+ ): CategoryCountableConnection"""- Stocks that belong to this warehouse.-- Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS.+ List of products in the category. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS."""- stocks(+ products(+ """Filtering options for products."""+ filter: ProductFilterInput @deprecated(reason: "Use `where` filter instead.")++ """Where filtering options for products."""+ where: ProductWhereInput++ """Sort products."""+ sortBy: ProductOrder++ """Search products."""+ search: String++ """Slug of a channel for which the data should be returned."""+ channel: String+"""Return the elements in the list that come before the specified cursor."""before: String@@ -4009,318 +4399,567 @@ type Warehouse implements Node & ObjectWithMetadata @doc(category: "Products") {Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query."""last: Int- ): StockCountableConnection+ ): ProductCountableConnection- """External ID of this warehouse."""- externalReference: String-}+ """List of children of the category."""+ children(+ """Return the elements in the list that come before the specified cursor."""+ before: String-enum WarehouseClickAndCollectOptionEnum @doc(category: "Products") {- DISABLED- LOCAL- ALL+ """Return the elements in the list that come after the specified cursor."""+ after: String++ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int++ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): CategoryCountableConnection++ """Background image of the category."""+ backgroundImage(+ """+ Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).+ """+ size: Int++ """+ The format of the image. When not provided, format of the original image will be used.+ """+ format: ThumbnailFormatEnum = ORIGINAL+ ): Image++ """Returns translated category fields for the given language code."""+ translation(+ """A language code to return the translation for category."""+ languageCode: LanguageCodeEnum!+ ): CategoryTranslation}-type ShippingZoneCountableConnection @doc(category: "Shipping") {+type CategoryCountableConnection @doc(category: "Products") {"""Pagination data for this connection."""pageInfo: PageInfo!- edges: [ShippingZoneCountableEdge!]!+ edges: [CategoryCountableEdge!]!"""A total count of items in the collection."""totalCount: Int}-"""-The Relay compliant `PageInfo` type, containing data necessary to paginate this connection.-"""-type PageInfo {- """When paginating forwards, are there more items?"""- hasNextPage: Boolean!-- """When paginating backwards, are there more items?"""- hasPreviousPage: Boolean!-- """When paginating backwards, the cursor to continue."""- startCursor: String-- """When paginating forwards, the cursor to continue."""- endCursor: String-}--type ShippingZoneCountableEdge @doc(category: "Shipping") {+type CategoryCountableEdge @doc(category: "Products") {"""The item at the end of the edge."""- node: ShippingZone!+ node: Category!"""A cursor for use in pagination."""cursor: String!}-"""-Represents a shipping zone in the shop. Zones are the concept used only for grouping shipping methods in the dashboard, and are never exposed to the customers directly.-"""-type ShippingZone implements Node & ObjectWithMetadata @doc(category: "Shipping") {- """The ID of shipping zone."""- id: ID!+input ProductFilterInput @doc(category: "Products") {+ isPublished: Boolean+ collections: [ID!]+ categories: [ID!]+ hasCategory: Boolean+ attributes: [AttributeInput!]- """List of private metadata items. Requires staff permissions to access."""- privateMetadata: [MetadataItem!]!+ """Filter by variants having specific stock status."""+ stockAvailability: StockAvailability+ stocks: ProductStockFilterInput+ search: String+ metadata: [MetadataFilter!]++ """Filter by the publication date."""+ publishedFrom: DateTime++ """Filter by availability for purchase."""+ isAvailable: Boolean++ """Filter by the date of availability for purchase."""+ availableFrom: DateTime++ """Filter by visibility in product listings."""+ isVisibleInListing: Boolean+ price: PriceRangeInput++ """Filter by the lowest variant price after discounts."""+ minimalPrice: PriceRangeInput++ """Filter by when was the most recent update."""+ updatedAt: DateTimeRangeInput+ productTypes: [ID!]++ """Filter on whether product is a gift card or not."""+ giftCard: Boolean+ ids: [ID!]+ hasPreorderedVariants: Boolean+ slugs: [String!]++ """Specifies the channel by which the data should be filtered."""+ channel: String @deprecated(reason: "Use root-level channel argument instead.")+}++input AttributeInput @doc(category: "Attributes") {+ """Internal representation of an attribute name."""+ slug: String"""- A single key from private metadata. Requires staff permissions to access.-- Tip: Use GraphQL aliases to fetch multiple keys.+ Filter by value of the attribute. Only one value input field is allowed. If provided more than one, the error will be raised. Cannot be combined with deprecated fields of `AttributeInput`."""- privateMetafield(key: String!): String+ value: AssignedAttributeValueInput"""- Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.+ Slugs identifying the attributeValues associated with the Attribute. When specified, it filters the results to include only records with one of the matching values. Requires `slug` to be provided."""- privateMetafields(keys: [String!]): Metadata+ values: [String!] @deprecated(reason: "Use `value` instead.")- """List of public metadata items. Can be accessed without permissions."""- metadata: [MetadataItem!]!+ """+ The range that the returned values should be in. Requires `slug` to be provided.+ """+ valuesRange: IntRangeInput @deprecated(reason: "Use `value` instead.")"""- A single key from public metadata.-- Tip: Use GraphQL aliases to fetch multiple keys.+ The date/time range that the returned values should be in. Requires `slug` to be provided."""- metafield(key: String!): String+ dateTime: DateTimeRangeInput @deprecated(reason: "Use `value` instead.")"""- Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.+ The date range that the returned values should be in. In case of date/time attributes, the UTC midnight of the given date is used. Requires `slug` to be provided."""- metafields(keys: [String!]): Metadata+ date: DateRangeInput @deprecated(reason: "Use `value` instead.")- """Shipping zone name."""- name: String!+ """The boolean value of the attribute. Requires `slug` to be provided."""+ boolean: Boolean @deprecated(reason: "Use `value` instead.")+}- """Indicates if the shipping zone is default one."""- default: Boolean!+input AssignedAttributeValueInput {+ """Filter by slug assigned to AttributeValue."""+ slug: StringFilterInput- """Lowest and highest prices for the shipping."""- priceRange: MoneyRange+ """Filter by name assigned to AttributeValue."""+ name: StringFilterInput- """List of countries available for the method."""- countries: [CountryDisplay!]!+ """Filter by numeric value for attributes of numeric type."""+ numeric: DecimalFilterInput- """- List of shipping methods available for orders shipped to countries within this shipping zone.- """- shippingMethods: [ShippingMethodType!]+ """Filter by date value for attributes of date type."""+ date: DateRangeInput- """List of warehouses for shipping zone."""- warehouses: [Warehouse!]!+ """Filter by date time value for attributes of date time type."""+ dateTime: DateTimeRangeInput- """List of channels for shipping zone."""- channels: [Channel!]!+ """Filter by boolean value for attributes of boolean type."""+ boolean: Boolean- """Description of a shipping zone."""- description: String+ """Filter by reference attribute value."""+ reference: AssignedAttributeReferenceInput}-"""Represents a range of amounts of money."""-type MoneyRange {- """Lower bound of a price range."""- start: Money+"""Define the filtering options for string fields."""+input StringFilterInput {+ """The value equal to."""+ eq: String- """Upper bound of a price range."""- stop: Money+ """The value included in."""+ oneOf: [String!]}-"""Represents amount of money in specific currency."""-type Money {- """Currency code."""- currency: String!-- """Amount of money."""- amount: Float!+"""Define the filtering options for decimal fields."""+input DecimalFilterInput {+ """The value equal to."""+ eq: Decimal- """- Amount of money represented as an integer in the smallest currency unit.- """- fractionalAmount: Int!+ """The value included in."""+ oneOf: [Decimal!]- """Number of digits after the decimal point in the currency."""- fractionDigits: Int!+ """The value in range."""+ range: DecimalRangeInput}"""-Shipping method are the methods you'll use to get customer's orders to them. They are directly exposed to the customers.+Custom Decimal implementation.++Returns Decimal as a float in the API,+parses float to the Decimal on the way back."""-type ShippingMethodType implements Node & ObjectWithMetadata @doc(category: "Shipping") {- """Shipping method ID."""- id: ID!+scalar Decimal- """List of private metadata items. Requires staff permissions to access."""- privateMetadata: [MetadataItem!]!+input DecimalRangeInput {+ """Decimal value greater than or equal to."""+ gte: Decimal- """- A single key from private metadata. Requires staff permissions to access.-- Tip: Use GraphQL aliases to fetch multiple keys.- """- privateMetafield(key: String!): String+ """Decimal value less than or equal to."""+ lte: Decimal+}- """- Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.- """- privateMetafields(keys: [String!]): Metadata+input DateRangeInput {+ """Start date."""+ gte: Date- """List of public metadata items. Can be accessed without permissions."""- metadata: [MetadataItem!]!+ """End date."""+ lte: Date+}++"""+The `Date` scalar type represents a Date+value as specified by+[iso8601](https://en.wikipedia.org/wiki/ISO_8601).+"""+scalar Date++input DateTimeRangeInput {+ """Start date."""+ gte: DateTime++ """End date."""+ lte: DateTime+}+input AssignedAttributeReferenceInput {"""- A single key from public metadata.-- Tip: Use GraphQL aliases to fetch multiple keys.+ Returns objects with a reference pointing to an object identified by the given ID."""- metafield(key: String!): String+ referencedIds: ContainsFilterInput"""- Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.+ Returns objects with a reference pointing to a page identified by the given slug."""- metafields(keys: [String!]): Metadata-- """Shipping method name."""- name: String!+ pageSlugs: ContainsFilterInput"""- Shipping method description.-- Rich text format. For reference see https://editorjs.io/+ Returns objects with a reference pointing to a product identified by the given slug."""- description: JSONString-- """Type of the shipping method."""- type: ShippingMethodTypeEnum-- """Returns translated shipping method fields for the given language code."""- translation(- """A language code to return the translation for shipping method."""- languageCode: LanguageCodeEnum!- ): ShippingMethodTranslation+ productSlugs: ContainsFilterInput"""- List of channels available for the method.-- Requires one of the following permissions: MANAGE_SHIPPING.+ Returns objects with a reference pointing to a product variant identified by the given sku."""- channelListings: [ShippingMethodChannelListing!]-- """The price of the cheapest variant (including discounts)."""- maximumOrderPrice: Money-- """The price of the cheapest variant (including discounts)."""- minimumOrderPrice: Money+ productVariantSkus: ContainsFilterInput"""- Postal code ranges rule of exclusion or inclusion of the shipping method.+ Returns objects with a reference pointing to a category identified by the given slug."""- postalCodeRules: [ShippingMethodPostalCodeRule!]+ categorySlugs: ContainsFilterInput"""- List of excluded products for the shipping method.-- Requires one of the following permissions: MANAGE_SHIPPING.+ Returns objects with a reference pointing to a collection identified by the given slug."""- excludedProducts(- """Return the elements in the list that come before the specified cursor."""- before: String+ collectionSlugs: ContainsFilterInput+}- """Return the elements in the list that come after the specified cursor."""- after: String+"""+Define the filtering options for fields that can contain multiple values.+"""+input ContainsFilterInput {+ """The field contains at least one of the specified values."""+ containsAny: [String!]- """- Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- first: Int+ """The field contains all of the specified values."""+ containsAll: [String!]+}- """- Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- last: Int- ): ProductCountableConnection+input IntRangeInput {+ """Value greater than or equal to."""+ gte: Int- """Minimum order weight to use this shipping method."""- minimumOrderWeight: Weight+ """Value less than or equal to."""+ lte: Int+}- """Maximum order weight to use this shipping method."""- maximumOrderWeight: Weight+enum StockAvailability @doc(category: "Products") {+ IN_STOCK+ OUT_OF_STOCK+}- """Maximum number of days for delivery."""- maximumDeliveryDays: Int+input ProductStockFilterInput @doc(category: "Products") {+ warehouseIds: [ID!]+ quantity: IntRangeInput+}- """Minimal number of days for delivery."""- minimumDeliveryDays: Int+input MetadataFilter {+ """Key of a metadata item."""+ key: String!- """- Tax class assigned to this shipping method.-- Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP.- """- taxClass: TaxClass+ """Value of a metadata item."""+ value: String}-scalar JSONString+input PriceRangeInput {+ """Price greater than or equal to."""+ gte: Float-enum ShippingMethodTypeEnum @doc(category: "Shipping") {- PRICE- WEIGHT+ """Price less than or equal to."""+ lte: Float}-"""Represents shipping method translations."""-type ShippingMethodTranslation implements Node @doc(category: "Shipping") {- """The ID of the shipping method translation."""- id: ID!-- """Translation language."""- language: LanguageDisplay!+input ProductWhereInput @doc(category: "Products") {+ metadata: [MetadataFilter!]+ ids: [ID!]- """Translated shipping method name."""- name: String+ """Filter by product name."""+ name: StringFilterInput- """- Translated description of the shipping method.-- Rich text format. For reference see https://editorjs.io/- """- description: JSONString+ """Filter by product slug."""+ slug: StringFilterInput- """Represents the shipping method fields to translate."""- translatableContent: ShippingMethodTranslatableContent-}+ """Filter by product type."""+ productType: GlobalIDFilterInput-type LanguageDisplay {- """ISO 639 representation of the language name."""- code: LanguageCodeEnum!+ """Filter by product category."""+ category: GlobalIDFilterInput- """Full name of the language."""- language: String!-}+ """Filter by collection."""+ collection: GlobalIDFilterInput-"""Language code enum. It contains all the languages supported by Saleor."""-enum LanguageCodeEnum {- """Afrikaans"""- AF+ """Filter by availability for purchase."""+ isAvailable: Boolean- """Afrikaans (Namibia)"""- AF_NA+ """Filter by public visibility."""+ isPublished: Boolean- """Afrikaans (South Africa)"""- AF_ZA+ """Filter by visibility on the channel."""+ isVisibleInListing: Boolean- """Aghem"""- AGQ+ """Filter by the publication date."""+ publishedFrom: DateTime- """Aghem (Cameroon)"""- AGQ_CM+ """Filter by the date of availability for purchase."""+ availableFrom: DateTime- """Akan"""- AK+ """Filter by product with category assigned."""+ hasCategory: Boolean- """Akan (Ghana)"""- AK_GH+ """Filter by product variant price."""+ price: DecimalFilterInput++ """Filter by the lowest variant price after discounts."""+ minimalPrice: DecimalFilterInput++ """Filter by attributes associated with the product."""+ attributes: [AttributeInput!]++ """Filter by variants having specific stock status."""+ stockAvailability: StockAvailability++ """Filter by stock of the product variant."""+ stocks: ProductStockFilterInput++ """Filter on whether product is a gift card or not."""+ giftCard: Boolean++ """Filter by product with preordered variants."""+ hasPreorderedVariants: Boolean++ """Filter by when was the most recent update."""+ updatedAt: DateTimeFilterInput++ """List of conditions that must be met."""+ AND: [ProductWhereInput!]++ """A list of conditions of which at least one must be met."""+ OR: [ProductWhereInput!]+}++"""Define the filtering options for foreign key fields."""+input GlobalIDFilterInput {+ """The value equal to."""+ eq: ID++ """The value included in."""+ oneOf: [ID!]+}++"""Define the filtering options for date time fields."""+input DateTimeFilterInput {+ """The value equal to."""+ eq: DateTime++ """The value included in."""+ oneOf: [DateTime!]++ """The value in range."""+ range: DateTimeRangeInput+}++input ProductOrder @doc(category: "Products") {+ """Specifies the direction in which to sort products."""+ direction: OrderDirection!++ """Specifies the channel in which to sort the data."""+ channel: String @deprecated(reason: "Use root-level channel argument instead.")++ """+ Sort product by the selected attribute's values.+ Note: this doesn't take translations into account yet.+ """+ attributeId: ID++ """Sort products by the selected field."""+ field: ProductOrderField+}++enum OrderDirection {+ """Specifies an ascending sort order."""+ ASC++ """Specifies a descending sort order."""+ DESC+}++enum ProductOrderField @doc(category: "Products") {+ """Sort products by name."""+ NAME++ """+ Sort products by rank. Note: This option is available only with the `search` filter.+ """+ RANK++ """+ Sort products by price.++ This option requires a channel filter to work as the values can vary between channels.+ """+ PRICE++ """+ Sort products by a minimal price of a product's variant.++ This option requires a channel filter to work as the values can vary between channels.+ """+ MINIMAL_PRICE++ """Sort products by update date."""+ LAST_MODIFIED @deprecated(reason: "Use `LAST_MODIFIED_AT` instead.")++ """Sort products by update date."""+ DATE @deprecated(reason: "Use `LAST_MODIFIED_AT` instead.")++ """Sort products by type."""+ TYPE++ """+ Sort products by publication status.++ This option requires a channel filter to work as the values can vary between channels.+ """+ PUBLISHED++ """+ Sort products by publication date.++ This option requires a channel filter to work as the values can vary between channels.+ """+ PUBLICATION_DATE @deprecated(reason: "Use `PUBLISHED_AT` instead.")++ """+ Sort products by publication date.++ This option requires a channel filter to work as the values can vary between channels.+ """+ PUBLISHED_AT++ """Sort products by update date."""+ LAST_MODIFIED_AT++ """+ Sort products by collection. Note: This option is available only for the `Collection.products` query.++ This option requires a channel filter to work as the values can vary between channels.+ """+ COLLECTION++ """Sort products by rating."""+ RATING++ """Sort products by creation date."""+ CREATED_AT+}++"""Represents an image."""+type Image {+ """The URL of the image."""+ url: String!++ """Alt text for an image."""+ alt: String+}++enum ThumbnailFormatEnum {+ ORIGINAL+ AVIF+ WEBP+}++"""Represents category translations."""+type CategoryTranslation implements Node @doc(category: "Products") {+ """The ID of the category translation."""+ id: ID!++ """Translation language."""+ language: LanguageDisplay!++ """Translated SEO title."""+ seoTitle: String++ """Translated SEO description."""+ seoDescription: String++ """Translated category slug."""+ slug: String++ """Translated category name."""+ name: String++ """+ Translated description of the category.++ Rich text format. For reference see https://editorjs.io/+ """+ description: JSONString++ """+ Translated description of the category.++ Rich text format. For reference see https://editorjs.io/+ """+ descriptionJson: JSONString @deprecated(reason: "Use the `description` field instead.")++ """Represents the category fields to translate."""+ translatableContent: CategoryTranslatableContent+}++type LanguageDisplay {+ """ISO 639 representation of the language name."""+ code: LanguageCodeEnum!++ """Full name of the language."""+ language: String!+}++"""Language code enum. It contains all the languages supported by Saleor."""+enum LanguageCodeEnum {+ """Afrikaans"""+ AF++ """Afrikaans (Namibia)"""+ AF_NA++ """Afrikaans (South Africa)"""+ AF_ZA++ """Aghem"""+ AGQ++ """Aghem (Cameroon)"""+ AGQ_CM++ """Akan"""+ AK++ """Akan (Ghana)"""+ AK_GH"""Amharic"""AM@@ -6640,97 +7279,54 @@ enum LanguageCodeEnum {}"""-Represents shipping method's original translatable fields and related translations.+Represents category original translatable fields and related translations."""-type ShippingMethodTranslatableContent implements Node @doc(category: "Shipping") {- """The ID of the shipping method translatable content."""+type CategoryTranslatableContent implements Node @doc(category: "Products") {+ """The ID of the category translatable content."""id: ID!- """The ID of the shipping method to translate."""- shippingMethodId: ID!+ """The ID of the category to translate."""+ categoryId: ID!- """Shipping method name to translate."""+ """SEO title to translate."""+ seoTitle: String++ """SEO description to translate."""+ seoDescription: String++ """Slug to translate."""+ slug: String++ """Name of the category translatable content."""name: String!"""- Shipping method description to translate.+ Category description to translate.Rich text format. For reference see https://editorjs.io/"""description: JSONString- """Returns translated shipping method fields for the given language code."""- translation(- """A language code to return the translation for shipping method."""- languageCode: LanguageCodeEnum!- ): ShippingMethodTranslation-"""- Shipping method are the methods you'll use to get customer's orders to them. They are directly exposed to the customers.+ Description of the category.- Requires one of the following permissions: MANAGE_SHIPPING.+ Rich text format. For reference see https://editorjs.io/"""- shippingMethod: ShippingMethodType @deprecated(reason: "Get model fields from the root level queries.")-}--"""Represents shipping method channel listing."""-type ShippingMethodChannelListing implements Node @doc(category: "Shipping") {- """The ID of shipping method channel listing."""- id: ID!-- """The channel associated with the shipping method channel listing."""- channel: Channel!-- """Maximum order price."""- maximumOrderPrice: Money-- """Minimum order price."""- minimumOrderPrice: Money-- """Price of the shipping method in the associated channel."""- price: Money-}--"""Represents shipping method postal code rule."""-type ShippingMethodPostalCodeRule implements Node @doc(category: "Shipping") {- """The ID of the object."""- id: ID!-- """Start address range."""- start: String-- """End address range."""- end: String-- """Inclusion type of the postal code rule."""- inclusionType: PostalCodeRuleInclusionTypeEnum-}--enum PostalCodeRuleInclusionTypeEnum @doc(category: "Shipping") {- INCLUDE- EXCLUDE-}--type ProductCountableConnection @doc(category: "Products") {- """Pagination data for this connection."""- pageInfo: PageInfo!- edges: [ProductCountableEdge!]!-- """A total count of items in the collection."""- totalCount: Int-}+ descriptionJson: JSONString @deprecated(reason: "Use the `description` field instead.")-type ProductCountableEdge @doc(category: "Products") {- """The item at the end of the edge."""- node: Product!+ """Returns translated category fields for the given language code."""+ translation(+ """A language code to return the translation for category."""+ languageCode: LanguageCodeEnum!+ ): CategoryTranslation- """A cursor for use in pagination."""- cursor: String!+ """Represents a single category of products."""+ category: Category @deprecated(reason: "Get model fields from the root level queries.")}-"""Represents an individual item for sale in the storefront."""-type Product implements Node & ObjectWithMetadata & ObjectWithAttributes @doc(category: "Products") {- """The ID of the product."""+"""Represents a version of a product such as different size or color."""+type ProductVariant implements Node & ObjectWithMetadata & ObjectWithAttributes @doc(category: "Products") {+ """The ID of the product variant."""id: ID!"""List of private metadata items. Requires staff permissions to access."""@@ -6774,7 +7370,7 @@ type Product implements Node & ObjectWithMetadata & ObjectWithAttributes @doc(ca): AssignedAttribute"""- List of attributes assigned to this product.+ List of attributes assigned to this variant.Added in Saleor 3.22."""@@ -6783,240 +7379,161 @@ type Product implements Node & ObjectWithMetadata & ObjectWithAttributes @doc(calimit: PositiveInt = 100): [AssignedAttribute!]!- """SEO title of the product."""- seoTitle: String+ """The name of the product variant."""+ name: String!- """SEO description of the product."""- seoDescription: String+ """The SKU (stock keeping unit) of the product variant."""+ sku: String- """SEO description of the product."""- name: String!+ """The product to which the variant belongs."""+ product: Product!"""- Description of the product.-- Rich text format. For reference see https://editorjs.io/+ Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item. If the field is not provided, `Shop.trackInventoryByDefault` will be used."""- description: JSONString-- """Type of the product."""- productType: ProductType!-- """Slug of the product."""- slug: String!- category: Category-- """The date and time when the product was created."""- created: DateTime!+ trackInventory: Boolean!- """The date and time when the product was last updated."""- updatedAt: DateTime!- chargeTaxes: Boolean! @deprecated(reason: "Use `Channel.taxConfiguration` field to determine whether tax collection is enabled.")+ """The maximum quantity of this variant that a customer can purchase."""+ quantityLimitPerCustomer: Int- """Weight of the product."""+ """The weight of the product variant."""weight: Weight- """Default variant of the product."""- defaultVariant: ProductVariant-- """Rating of the product."""- rating: Float-"""- Channel given to retrieve this product. Also used by federation gateway to resolve this object in a federated query.+ Channel given to retrieve this product variant. Also used by federation gateway to resolve this object in a federated query."""channel: String"""- Description of the product.+ List of price information in channels for the product.- Rich text format. For reference see https://editorjs.io/+ Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER."""- descriptionJson: JSONString @deprecated(reason: "Use the `description` field instead.")-- """Thumbnail of the product."""- thumbnail(- """- Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).- """- size: Int-- """- The format of the image. When not provided, format of the original image will be used.- """- format: ThumbnailFormatEnum = ORIGINAL- ): Image+ channelListings: [ProductVariantChannelListing!]"""- Lists the storefront product's pricing, the current price and discounts, only meant for displaying.+ Lists the storefront variant's pricing, the current price and discounts, only meant for displaying."""pricing("""Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration."""address: AddressInput- ): ProductPricingInfo-- """- Whether the product is in stock, set as available for purchase in the given channel, and published.- """- isAvailable(- """- Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration. When `Shop.useLegacyShippingZoneStockAvailability` is disabled, this argument is ignored — stock availability is determined by the direct warehouse-channel link instead of shipping zones.- """- address: AddressInput @deprecated- ): Boolean-- """A type of tax. Assigned by enabled tax gateway"""- taxType: TaxType @deprecated(reason: "Use `taxClass` field instead.")+ ): VariantPricingInfo- """Get a single attribute attached to product by attribute slug."""- attribute(- """Slug of the attribute"""- slug: String!- ): SelectedAttribute @deprecated(reason: "Use the `assignedAttribute` field instead.")+ """List of attributes assigned to this variant."""+ attributes(+ """Define scope of returned attributes."""+ variantSelection: VariantAttributeScope+ ): [SelectedAttribute!]! @deprecated(reason: "Use the `assignedAttributes` field instead.")- """List of attributes assigned to this product."""- attributes: [SelectedAttribute!]! @deprecated(reason: "Use the `assignedAttributes` field instead.")+ """Gross margin percentage value."""+ margin: Int"""- List of availability in channels for the product.+ Total quantity ordered.Requires one of the following permissions: MANAGE_PRODUCTS."""- channelListings: [ProductChannelListing!]-- """Get a single product media by ID."""- mediaById(- """ID of a product media."""- id: ID!- ): ProductMedia-- """Get a single product image by ID."""- imageById(- """ID of a product image."""- id: ID!- ): ProductImage @deprecated(reason: "Use the `mediaById` field instead.")-- """- List of variants for the product. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.- """- variants: [ProductVariant!] @deprecated(reason: "Use `productVariants` field instead.")+ quantityOrdered: Int"""- List of variants for the product. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.+ Total revenue generated by a variant in given period of time. Note: this field should be queried using `reportProductSales` query as it uses optimizations suitable for such calculations.++ Requires one of the following permissions: MANAGE_PRODUCTS."""- productVariants(- """Filtering options for product variant."""- filter: ProductVariantFilterInput @deprecated(reason: "Use `where` filter instead.")-- """Where filtering options for product variants."""- where: ProductVariantWhereInput-- """Sort products variants."""- sortBy: ProductVariantSortingInput+ revenue(period: ReportingPeriod): TaxedMoney- """Return the elements in the list that come before the specified cursor."""- before: String+ """List of images for the product variant."""+ images: [ProductImage!] @deprecated(reason: "Use the `media` field instead.")- """Return the elements in the list that come after the specified cursor."""- after: String+ """List of media for the product variant."""+ media: [ProductMedia!]- """- Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- first: Int+ """Returns translated product variant fields for the given language code."""+ translation(+ """A language code to return the translation for product variant."""+ languageCode: LanguageCodeEnum!+ ): ProductVariantTranslation+ """+ Stocks for the product variant.++ Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS.+ """+ stocks("""- Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration. When `Shop.useLegacyShippingZoneStockAvailability` is disabled, this argument is ignored — stock availability is determined by the direct warehouse-channel link instead of shipping zones."""- last: Int- ): ProductVariantCountableConnection-- """List of media for the product."""- media(- """Sort media."""- sortBy: MediaSortingInput- ): [ProductMedia!]+ address: AddressInput @deprecated- """List of images for the product."""- images: [ProductImage!] @deprecated(reason: "Use the `media` field instead.")+ """Two-letter ISO 3166-1 country code."""+ countryCode: CountryCode @deprecated(reason: "Use `address` argument instead.")+ ): [Stock!]"""- List of collections for the product. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.+ Quantity of a product available for sale in one checkout. Field value will be `null` when no `limitQuantityPerCheckout` in global settings has been set, and `productVariant` stocks are not tracked."""- collections: [Collection!]-- """Returns translated product fields for the given language code."""- translation(- """A language code to return the translation for product."""- languageCode: LanguageCodeEnum!- ): ProductTranslation+ quantityAvailable(+ """+ Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration. When `Shop.useLegacyShippingZoneStockAvailability` is disabled, this argument is ignored — stock availability is determined by the direct warehouse-channel link instead of shipping zones.+ """+ address: AddressInput @deprecated- """Date when product is available for purchase."""- availableForPurchase: Date @deprecated(reason: "Use the `availableForPurchaseAt` field to fetch the available for purchase date.")+ """+ Two-letter ISO 3166-1 country code. When provided, the exact quantity from a warehouse operating in shipping zones that contain this country will be returned. Otherwise, it will return the maximum quantity from all shipping zones.+ """+ countryCode: CountryCode @deprecated(reason: "Use `address` argument instead.")+ ): Int- """Date when product is available for purchase."""- availableForPurchaseAt: DateTime+ """Preorder data for product variant."""+ preorder: PreorderData- """- Refers to a state that can be set by admins to control whether a product is available for purchase in storefronts. This does not guarantee the availability of stock. When set to `False`, this product is still visible to customers, but it cannot be purchased.- """- isAvailableForPurchase: Boolean+ """The date and time when the product variant was created."""+ created: DateTime!- """- Tax class assigned to this product type. All products of this product type use this tax class, unless it's overridden in the `Product` type.-- Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP.- """- taxClass: TaxClass+ """The date and time when the product variant was last updated."""+ updatedAt: DateTime!"""External ID of this product."""externalReference: String}-"""-An object with attributes.+"""Represents product variant channel listing."""+type ProductVariantChannelListing implements Node @doc(category: "Products") {+ """The ID of the variant channel listing."""+ id: ID!++ """The channel to which the variant listing belongs."""+ channel: Channel!++ """The price of the variant."""+ price: Money++ """Cost price of the variant."""+ costPrice: Money-Added in Saleor 3.22.-"""-interface ObjectWithAttributes @doc(category: "Attributes") {"""- Get a single attribute attached to the object by attribute slug.+ Previous price of the variant in channel. Useful for providing promotion information required by customer protection laws such as EU Omnibus directive.- Added in Saleor 3.22.+ Warning: This field is not updated automatically. Use Channel Listings mutation to update it manually."""- assignedAttribute(- """Slug of the attribute"""- slug: String!- ): AssignedAttribute @doc(category: "Attributes")+ priorPrice: Money"""- List of attributes assigned to the object.+ Gross margin percentage value.- Added in Saleor 3.22.+ Requires one of the following permissions: MANAGE_PRODUCTS."""- assignedAttributes(- """Maximum number of attributes to return. Default is 100."""- limit: PositiveInt = 100- ): [AssignedAttribute!]!-}--"""-Represents an attribute assigned to an object.+ margin: Int-Added in Saleor 3.22.-"""-interface AssignedAttribute @doc(category: "Attributes") {- """Attribute assigned to an object."""- attribute: Attribute!+ """Preorder variant data."""+ preorderThreshold: PreorderThreshold}-"""-Custom attribute of a product. Attributes can be assigned to products and variants at the product type level.-"""-type Attribute implements Node & ObjectWithMetadata @doc(category: "Attributes") {- """The ID of the attribute."""+"""Represents channel."""+type Channel implements Node & ObjectWithMetadata @doc(category: "Channels") {+ """The ID of the channel."""id: ID!"""List of private metadata items. Requires staff permissions to access."""@@ -7049,197 +7566,128 @@ type Attribute implements Node & ObjectWithMetadata @doc(category: "Attributes")"""metafields(keys: [String!]): Metadata- """The input type to use for entering attribute values in the dashboard."""- inputType: AttributeInputTypeEnum-- """The entity type which can be used as a reference."""- entityType: AttributeEntityTypeEnum+ """Slug of the channel."""+ slug: String!"""- The reference types (product or page type) that are used to narrow down the choices of reference objects.+ Name of the channel.- Added in Saleor 3.22.+ Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER."""- referenceTypes(- """- Maximum number of objects to return. Value must be greater than 0. Default is 100.- """- limit: PositiveInt = 100- ): [ReferenceType!]-- """Name of an attribute displayed in the interface."""name: String!- """Internal representation of an attribute name."""- slug: String!-- """The attribute type."""- type: AttributeTypeEnum!-- """The unit of attribute values."""- unit: MeasurementUnitsEnum-"""- A list of predefined attribute choices available for selection. Available only for attributes with predefined choices.+ Whether the channel is active.++ Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER."""- choices(- """Sort attribute choices."""- sortBy: AttributeChoicesSortingInput-- """Filtering options for attribute choices."""- filter: AttributeValueFilterInput @deprecated(reason: "Use `where` filter instead.")-- """- Where filtering options for attribute choices.-- Added in Saleor 3.22.- """- where: AttributeValueWhereInput-- """- Search attribute choices.-- Added in Saleor 3.22.- """- search: String-- """Return the elements in the list that come before the specified cursor."""- before: String-- """Return the elements in the list that come after the specified cursor."""- after: String-- """- Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- first: Int-- """- Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- last: Int- ): AttributeValueCountableConnection+ isActive: Boolean!"""- Whether the attribute requires values to be passed or not. Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ A currency that is assigned to the channel.++ Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER."""- valueRequired: Boolean!+ currencyCode: String!"""- Whether the attribute should be visible or not in storefront. Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ Whether a channel has associated orders.++ Requires one of the following permissions: MANAGE_CHANNELS."""- visibleInStorefront: Boolean!+ hasOrders: Boolean!"""- Whether the attribute can be filtered in storefront. Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ Default country for the channel. Default country can be used in checkout to determine the stock quantities or calculate taxes when the country was not explicitly provided.++ Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER."""- filterableInStorefront: Boolean! @deprecated+ defaultCountry: CountryDisplay!"""- Whether the attribute can be filtered in dashboard. Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ List of warehouses assigned to this channel.++ Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER."""- filterableInDashboard: Boolean!+ warehouses: [Warehouse!]!++ """List of shippable countries for the channel."""+ countries: [CountryDisplay!]++ """Shipping methods that are available for the channel."""+ availableShippingMethodsPerCountry(countries: [CountryCode!]): [ShippingMethodsPerCountry!]"""- Whether the attribute can be displayed in the admin product list. Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ Define the stock setting for this channel.++ Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER."""- availableInGrid: Boolean! @deprecated+ stockSettings: StockSettings!"""- The position of the attribute in the storefront navigation (0 by default). Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES.+ Channel-specific order settings.++ Requires one of the following permissions: MANAGE_CHANNELS, MANAGE_ORDERS."""- storefrontSearchPosition: Int! @deprecated-- """Returns translated attribute fields for the given language code."""- translation(- """A language code to return the translation for attribute."""- languageCode: LanguageCodeEnum!- ): AttributeTranslation-- """Flag indicating that attribute has predefined choices."""- withChoices: Boolean!+ orderSettings: OrderSettings!"""- A list of product types that use this attribute as a product attribute.+ Channel-specific checkout settings.++ Requires one of the following permissions: MANAGE_CHANNELS, MANAGE_CHECKOUTS."""- productTypes(- """Return the elements in the list that come before the specified cursor."""- before: String-- """Return the elements in the list that come after the specified cursor."""- after: String-- """- Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- first: Int-- """- Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- last: Int- ): ProductTypeCountableConnection!+ checkoutSettings: CheckoutSettings!"""- A list of product types that use this attribute as a product variant attribute.+ Channel-specific payment settings.++ Requires one of the following permissions: MANAGE_CHANNELS, HANDLE_PAYMENTS."""- productVariantTypes(- """Return the elements in the list that come before the specified cursor."""- before: String+ paymentSettings: PaymentSettings!- """Return the elements in the list that come after the specified cursor."""- after: String+ """+ Channel specific tax configuration.++ Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP.+ """+ taxConfiguration: TaxConfiguration!+}- """- Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- first: Int+type CountryDisplay {+ """Country code."""+ code: String!- """- Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- last: Int- ): ProductTypeCountableConnection!+ """Country name."""+ country: String!- """External ID of this attribute."""- externalReference: String+ """Country tax."""+ vat: VAT @deprecated(reason: "Always returns `null`. Use `TaxClassCountryRate` type to manage tax rates per country.")}-enum AttributeInputTypeEnum @doc(category: "Attributes") {- DROPDOWN- MULTISELECT- FILE- REFERENCE- SINGLE_REFERENCE- NUMERIC- RICH_TEXT- PLAIN_TEXT- SWATCH- BOOLEAN- DATE- DATE_TIME-}+"""Represents a VAT rate for a country."""+type VAT @doc(category: "Taxes") {+ """Country code."""+ countryCode: String!-enum AttributeEntityTypeEnum @doc(category: "Attributes") {- PAGE- PRODUCT- PRODUCT_VARIANT- CATEGORY- COLLECTION+ """Standard VAT rate in percent."""+ standardRate: Float++ """Country's VAT rate exceptions for specific types of goods."""+ reducedRates: [ReducedRate!]!}-"""-The reference types (product or page type) that are used to narrow down the choices of reference objects.-ProductType applicable for reference attribute with `PRODUCT` or `PRODUCT_VARIANT` entity type.-PageType applicable for reference attribute with `PAGE` entity type.-"""-union ReferenceType = ProductType | PageType+"""Represents a reduced VAT rate for a particular type of goods."""+type ReducedRate @doc(category: "Taxes") {+ """Reduced VAT rate in percent."""+ rate: Float!-"""-Represents a type of product. It defines what attributes are available to products of this type.-"""-type ProductType implements Node & ObjectWithMetadata @doc(category: "Products") {- """The ID of the product type."""+ """A type of goods."""+ rateType: String!+}++"""Represents warehouse."""+type Warehouse implements Node & ObjectWithMetadata @doc(category: "Products") {+ """The ID of the warehouse."""id: ID!"""List of private metadata items. Requires staff permissions to access."""@@ -7272,29 +7720,29 @@ type ProductType implements Node & ObjectWithMetadata @doc(category: "Products")"""metafields(keys: [String!]): Metadata- """Name of the product type."""+ """Warehouse name."""name: String!- """Slug of the product type."""+ """Warehouse slug."""slug: String!- """Whether the product type has variants."""- hasVariants: Boolean! @deprecated(reason: "This is a leftover from the past Simple/Configurable product distinction. Products can have multiple variants regardless of this setting. ")+ """Warehouse email."""+ email: String!- """Whether shipping is required for this product type."""- isShippingRequired: Boolean!+ """Determine if the warehouse is private."""+ isPrivate: Boolean!- """Weight of the product type."""- weight: Weight+ """Address of the warehouse."""+ address: Address!- """The product type kind."""- kind: ProductTypeKindEnum!+ """Warehouse company name."""+ companyName: String! @deprecated(reason: "Use `Address.companyName` instead.")- """List of products of this type."""- products(- """Slug of a channel for which the data should be returned."""- channel: String+ """Click and collect options: local, all or disabled."""+ clickAndCollectOption: WarehouseClickAndCollectOptionEnum!+ """Shipping zones supported by the warehouse."""+ shippingZones("""Return the elements in the list that come before the specified cursor."""before: String@@ -7310,50 +7758,14 @@ type ProductType implements Node & ObjectWithMetadata @doc(category: "Products")Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query."""last: Int- ): ProductCountableConnection @deprecated(reason: "Use the top-level `products` query with the `productTypes` filter.")-- """A type of tax. Assigned by enabled tax gateway"""- taxType: TaxType @deprecated(reason: "Use `taxClass` field instead.")-- """- Tax class assigned to this product type. All products of this product type use this tax class, unless it's overridden in the `Product` type.-- Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP.- """- taxClass: TaxClass-- """Variant attributes of that product type."""- variantAttributes(- """Define scope of returned attributes."""- variantSelection: VariantAttributeScope- ): [Attribute!] @deprecated(reason: "Use `assignedVariantAttributes` instead.")-- """- Variant attributes of that product type with attached variant selection.- """- assignedVariantAttributes(- """Define scope of returned attributes."""- variantSelection: VariantAttributeScope- ): [AssignedVariantAttribute!]-- """Product attributes of that product type."""- productAttributes: [Attribute!]+ ): ShippingZoneCountableConnection!"""- List of attributes which can be assigned to this product type.+ Stocks that belong to this warehouse.- Requires one of the following permissions: MANAGE_PRODUCTS.+ Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS."""- availableAttributes(- """Filtering options for attributes of this product type."""- filter: AttributeFilterInput @deprecated(reason: "Use `where` filter instead.")-- """Where filtering options for attributes of this product type."""- where: AttributeWhereInput-- """Search attributes."""- search: String-+ stocks("""Return the elements in the list that come before the specified cursor."""before: String@@ -7369,45 +7781,15 @@ type ProductType implements Node & ObjectWithMetadata @doc(category: "Products")Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query."""last: Int- ): AttributeCountableConnection-}--"""Represents weight value in a specific weight unit."""-type Weight {- """Weight unit."""- unit: WeightUnitsEnum!-- """Weight value. Returns a value with maximal three decimal places"""- value: Float!-}--enum WeightUnitsEnum {- G- LB- OZ- KG- TONNE-}--enum ProductTypeKindEnum @doc(category: "Products") {- NORMAL- GIFT_CARD-}--"""Representation of tax types fetched from tax gateway."""-type TaxType @doc(category: "Taxes") {- """Description of the tax type."""- description: String+ ): StockCountableConnection- """External tax code used to identify given tax group."""- taxCode: String+ """External ID of this warehouse."""+ externalReference: String}-"""-Tax class is a named object used to define tax rates per country. Tax class can be assigned to product types, products and shipping methods to define their tax rates.-"""-type TaxClass implements Node & ObjectWithMetadata @doc(category: "Taxes") {- """The ID of the object."""+"""Represents user address data."""+type Address implements Node & ObjectWithMetadata @doc(category: "Users") {+ """The ID of the address."""id: ID!"""List of private metadata items. Requires staff permissions to access."""@@ -7440,202 +7822,164 @@ type TaxClass implements Node & ObjectWithMetadata @doc(category: "Taxes") {"""metafields(keys: [String!]): Metadata- """Name of the tax class."""- name: String!+ """The given name of the address."""+ firstName: String!- """Country-specific tax rates for this tax class."""- countries: [TaxClassCountryRate!]!-}+ """The family name of the address."""+ lastName: String!-"""-Tax rate for a country. When tax class is null, it represents the default tax rate for that country; otherwise it's a country tax rate specific to the given tax class.-"""-type TaxClassCountryRate @doc(category: "Taxes") {- """Country in which this tax rate applies."""+ """Company or organization name."""+ companyName: String!++ """The first line of the address."""+ streetAddress1: String!++ """The second line of the address."""+ streetAddress2: String!++ """The city of the address."""+ city: String!++ """The district of the address."""+ cityArea: String!++ """The postal code of the address."""+ postalCode: String!++ """The country of the address."""country: CountryDisplay!- """Tax rate value."""- rate: Float!+ """The country area of the address."""+ countryArea: String!- """Related tax class."""- taxClass: TaxClass-}+ """The phone number assigned the address."""+ phone: String-enum VariantAttributeScope @doc(category: "Products") {- ALL- VARIANT_SELECTION- NOT_VARIANT_SELECTION-}+ """Address is user's default shipping address."""+ isDefaultShippingAddress: Boolean-"""-Represents assigned attribute to variant with variant selection attached.-"""-type AssignedVariantAttribute @doc(category: "Attributes") {- """Attribute assigned to variant."""- attribute: Attribute!+ """Address is user's default billing address."""+ isDefaultBillingAddress: Boolean+}- """- Determines, whether assigned attribute is allowed for variant selection. Supported variant types for variant selection are: ['dropdown', 'boolean', 'swatch', 'numeric']- """- variantSelection: Boolean!+enum WarehouseClickAndCollectOptionEnum @doc(category: "Products") {+ DISABLED+ LOCAL+ ALL}-type AttributeCountableConnection @doc(category: "Attributes") {+type ShippingZoneCountableConnection @doc(category: "Shipping") {"""Pagination data for this connection."""pageInfo: PageInfo!- edges: [AttributeCountableEdge!]!+ edges: [ShippingZoneCountableEdge!]!"""A total count of items in the collection."""totalCount: Int}-type AttributeCountableEdge @doc(category: "Attributes") {+type ShippingZoneCountableEdge @doc(category: "Shipping") {"""The item at the end of the edge."""- node: Attribute!+ node: ShippingZone!"""A cursor for use in pagination."""cursor: String!}-input AttributeFilterInput @doc(category: "Attributes") {- valueRequired: Boolean- isVariantOnly: Boolean- visibleInStorefront: Boolean- filterableInStorefront: Boolean- filterableInDashboard: Boolean- availableInGrid: Boolean- metadata: [MetadataFilter!]- search: String- ids: [ID!]- type: AttributeTypeEnum- inCollection: ID- inCategory: ID- slugs: [String!]+"""+Represents a shipping zone in the shop. Zones are the concept used only for grouping shipping methods in the dashboard, and are never exposed to the customers directly.+"""+type ShippingZone implements Node & ObjectWithMetadata @doc(category: "Shipping") {+ """The ID of shipping zone."""+ id: ID!- """Specifies the channel by which the data should be filtered."""- channel: String @deprecated(reason: "Use root-level channel argument instead.")-}+ """List of private metadata items. Requires staff permissions to access."""+ privateMetadata: [MetadataItem!]!-input MetadataFilter {- """Key of a metadata item."""- key: String!+ """+ A single key from private metadata. Requires staff permissions to access.++ Tip: Use GraphQL aliases to fetch multiple keys.+ """+ privateMetafield(key: String!): String- """Value of a metadata item."""- value: String-}+ """+ Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.+ """+ privateMetafields(keys: [String!]): Metadata-enum AttributeTypeEnum @doc(category: "Attributes") {- PRODUCT_TYPE- PAGE_TYPE-}+ """List of public metadata items. Can be accessed without permissions."""+ metadata: [MetadataItem!]!-"""Where filtering options."""-input AttributeWhereInput @doc(category: "Attributes") {- metadata: [MetadataFilter!]- ids: [ID!]- name: StringFilterInput- slug: StringFilterInput- withChoices: Boolean- inputType: AttributeInputTypeEnumFilterInput- entityType: AttributeEntityTypeEnumFilterInput- type: AttributeTypeEnumFilterInput- unit: MeasurementUnitsEnumFilterInput- inCollection: ID- inCategory: ID- valueRequired: Boolean- visibleInStorefront: Boolean- filterableInDashboard: Boolean+ """+ A single key from public metadata.++ Tip: Use GraphQL aliases to fetch multiple keys.+ """+ metafield(key: String!): String- """List of conditions that must be met."""- AND: [AttributeWhereInput!]+ """+ Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.+ """+ metafields(keys: [String!]): Metadata- """A list of conditions of which at least one must be met."""- OR: [AttributeWhereInput!]-}+ """Shipping zone name."""+ name: String!-"""Define the filtering options for string fields."""-input StringFilterInput {- """The value equal to."""- eq: String+ """Indicates if the shipping zone is default one."""+ default: Boolean!- """The value included in."""- oneOf: [String!]-}+ """Lowest and highest prices for the shipping."""+ priceRange: MoneyRange-input AttributeInputTypeEnumFilterInput @doc(category: "Attributes") {- """The value equal to."""- eq: AttributeInputTypeEnum+ """List of countries available for the method."""+ countries: [CountryDisplay!]!- """The value included in."""- oneOf: [AttributeInputTypeEnum!]-}+ """+ List of shipping methods available for orders shipped to countries within this shipping zone.+ """+ shippingMethods: [ShippingMethodType!]-input AttributeEntityTypeEnumFilterInput @doc(category: "Attributes") {- """The value equal to."""- eq: AttributeEntityTypeEnum+ """List of warehouses for shipping zone."""+ warehouses: [Warehouse!]!- """The value included in."""- oneOf: [AttributeEntityTypeEnum!]+ """List of channels for shipping zone."""+ channels: [Channel!]!++ """Description of a shipping zone."""+ description: String}-input AttributeTypeEnumFilterInput @doc(category: "Attributes") {- """The value equal to."""- eq: AttributeTypeEnum+"""Represents a range of amounts of money."""+type MoneyRange {+ """Lower bound of a price range."""+ start: Money- """The value included in."""- oneOf: [AttributeTypeEnum!]+ """Upper bound of a price range."""+ stop: Money}-input MeasurementUnitsEnumFilterInput @doc(category: "Attributes") {- """The value equal to."""- eq: MeasurementUnitsEnum+"""Represents amount of money in specific currency."""+type Money {+ """Currency code."""+ currency: String!- """The value included in."""- oneOf: [MeasurementUnitsEnum!]-}+ """Amount of money."""+ amount: Float!-enum MeasurementUnitsEnum {- MM- CM- DM- M- KM- FT- YD- INCH- SQ_MM- SQ_CM- SQ_DM- SQ_M- SQ_KM- SQ_FT- SQ_YD- SQ_INCH- CUBIC_MILLIMETER- CUBIC_CENTIMETER- CUBIC_DECIMETER- CUBIC_METER- LITER- CUBIC_FOOT- CUBIC_INCH- CUBIC_YARD- QT- PINT- FL_OZ- ACRE_IN- ACRE_FT- G- LB- OZ- KG- TONNE+ """+ Amount of money represented as an integer in the smallest currency unit.+ """+ fractionalAmount: Int!++ """Number of digits after the decimal point in the currency."""+ fractionDigits: Int!}"""-Represents a type of page. It defines what attributes are available to pages of this type.+Shipping method are the methods you'll use to get customer's orders to them. They are directly exposed to the customers."""-type PageType implements Node & ObjectWithMetadata @doc(category: "Pages") {- """ID of the page type."""+type ShippingMethodType implements Node & ObjectWithMetadata @doc(category: "Shipping") {+ """Shipping method ID."""id: ID!"""List of private metadata items. Requires staff permissions to access."""@@ -7668,30 +8012,49 @@ type PageType implements Node & ObjectWithMetadata @doc(category: "Pages") {"""metafields(keys: [String!]): Metadata- """Name of the page type."""+ """Shipping method name."""name: String!- """Slug of the page type."""- slug: String!+ """+ Shipping method description.++ Rich text format. For reference see https://editorjs.io/+ """+ description: JSONString- """Page attributes of that page type."""- attributes: [Attribute!]+ """Type of the shipping method."""+ type: ShippingMethodTypeEnum++ """Returns translated shipping method fields for the given language code."""+ translation(+ """A language code to return the translation for shipping method."""+ languageCode: LanguageCodeEnum!+ ): ShippingMethodTranslation"""- Attributes that can be assigned to the page type.+ List of channels available for the method.- Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES.+ Requires one of the following permissions: MANAGE_SHIPPING."""- availableAttributes(- """Filtering options for attributes."""- filter: AttributeFilterInput @deprecated(reason: "Use `where` filter instead.")+ channelListings: [ShippingMethodChannelListing!]- """Where filtering options for attributes."""- where: AttributeWhereInput+ """The price of the cheapest variant (including discounts)."""+ maximumOrderPrice: Money- """Search attributes."""- search: String+ """The price of the cheapest variant (including discounts)."""+ minimumOrderPrice: Money++ """+ Postal code ranges rule of exclusion or inclusion of the shipping method.+ """+ postalCodeRules: [ShippingMethodPostalCodeRule!]+ """+ List of excluded products for the shipping method.++ Requires one of the following permissions: MANAGE_SHIPPING.+ """+ excludedProducts("""Return the elements in the list that come before the specified cursor."""before: String@@ -7707,2030 +8070,1649 @@ type PageType implements Node & ObjectWithMetadata @doc(category: "Pages") {Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query."""last: Int- ): AttributeCountableConnection+ ): ProductCountableConnection- """- Whether page type has pages assigned.-- Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES.- """- hasPages: Boolean-}+ """Minimum order weight to use this shipping method."""+ minimumOrderWeight: Weight-"""-Positive Integer scalar implementation.+ """Maximum order weight to use this shipping method."""+ maximumOrderWeight: Weight-Should be used in places where value must be positive (greater than 0).-"""-scalar PositiveInt+ """Maximum number of days for delivery."""+ maximumDeliveryDays: Int-type AttributeValueCountableConnection @doc(category: "Attributes") {- """Pagination data for this connection."""- pageInfo: PageInfo!- edges: [AttributeValueCountableEdge!]!+ """Minimal number of days for delivery."""+ minimumDeliveryDays: Int- """A total count of items in the collection."""- totalCount: Int+ """+ Tax class assigned to this shipping method.++ Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP.+ """+ taxClass: TaxClass}-type AttributeValueCountableEdge @doc(category: "Attributes") {- """The item at the end of the edge."""- node: AttributeValue!-- """A cursor for use in pagination."""- cursor: String!+enum ShippingMethodTypeEnum @doc(category: "Shipping") {+ PRICE+ WEIGHT}-"""Represents a value of an attribute."""-type AttributeValue implements Node @doc(category: "Attributes") {- """The ID of the attribute value."""+"""Represents shipping method translations."""+type ShippingMethodTranslation implements Node @doc(category: "Shipping") {+ """The ID of the shipping method translation."""id: ID!- """Name of a value displayed in the interface."""- name: String+ """Translation language."""+ language: LanguageDisplay!- """Internal representation of a value (unique per attribute)."""- slug: String+ """Translated shipping method name."""+ name: String"""- Represent value of the attribute value (e.g. color values for swatch attributes).+ Translated description of the shipping method.++ Rich text format. For reference see https://editorjs.io/"""- value: String+ description: JSONString- """Returns translated attribute value fields for the given language code."""- translation(- """A language code to return the translation for attribute value."""- languageCode: LanguageCodeEnum!- ): AttributeValueTranslation+ """Represents the shipping method fields to translate."""+ translatableContent: ShippingMethodTranslatableContent+}- """The input type to use for entering attribute values in the dashboard."""- inputType: AttributeInputTypeEnum+"""+Represents shipping method's original translatable fields and related translations.+"""+type ShippingMethodTranslatableContent implements Node @doc(category: "Shipping") {+ """The ID of the shipping method translatable content."""+ id: ID!- """The ID of the referenced object."""- reference: ID+ """The ID of the shipping method to translate."""+ shippingMethodId: ID!- """Represents file URL and content type (if attribute value is a file)."""- file: File+ """Shipping method name to translate."""+ name: String!"""- Represents the text of the attribute value, includes formatting.+ Shipping method description to translate.Rich text format. For reference see https://editorjs.io/"""- richText: JSONString+ description: JSONString++ """Returns translated shipping method fields for the given language code."""+ translation(+ """A language code to return the translation for shipping method."""+ languageCode: LanguageCodeEnum!+ ): ShippingMethodTranslation"""- Represents the text of the attribute value, plain text without formatting.+ Shipping method are the methods you'll use to get customer's orders to them. They are directly exposed to the customers.++ Requires one of the following permissions: MANAGE_SHIPPING."""- plainText: String+ shippingMethod: ShippingMethodType @deprecated(reason: "Get model fields from the root level queries.")+}- """Represents the boolean value of the attribute value."""- boolean: Boolean+"""Represents shipping method channel listing."""+type ShippingMethodChannelListing implements Node @doc(category: "Shipping") {+ """The ID of shipping method channel listing."""+ id: ID!- """Represents the date value of the attribute value."""- date: Date+ """The channel associated with the shipping method channel listing."""+ channel: Channel!- """Represents the date/time value of the attribute value."""- dateTime: DateTime+ """Maximum order price."""+ maximumOrderPrice: Money- """External ID of this attribute value."""- externalReference: String+ """Minimum order price."""+ minimumOrderPrice: Money++ """Price of the shipping method in the associated channel."""+ price: Money}-"""Represents attribute value translations."""-type AttributeValueTranslation implements Node @doc(category: "Attributes") {- """The ID of the attribute value translation."""+"""Represents shipping method postal code rule."""+type ShippingMethodPostalCodeRule implements Node @doc(category: "Shipping") {+ """The ID of the object."""id: ID!- """Translation language."""- language: LanguageDisplay!-- """Translated attribute value name."""- name: String!+ """Start address range."""+ start: String- """- Translated rich-text attribute value.-- Rich text format. For reference see https://editorjs.io/- """- richText: JSONString+ """End address range."""+ end: String- """Translated plain text attribute value ."""- plainText: String+ """Inclusion type of the postal code rule."""+ inclusionType: PostalCodeRuleInclusionTypeEnum+}- """Represents the attribute value fields to translate."""- translatableContent: AttributeValueTranslatableContent+enum PostalCodeRuleInclusionTypeEnum @doc(category: "Shipping") {+ INCLUDE+ EXCLUDE}"""-Represents attribute value's original translatable fields and related translations.+Tax class is a named object used to define tax rates per country. Tax class can be assigned to product types, products and shipping methods to define their tax rates."""-type AttributeValueTranslatableContent implements Node @doc(category: "Attributes") {- """The ID of the attribute value translatable content."""+type TaxClass implements Node & ObjectWithMetadata @doc(category: "Taxes") {+ """The ID of the object."""id: ID!- """The ID of the attribute value to translate."""- attributeValueId: ID!-- """Name of the attribute value to translate."""- name: String!+ """List of private metadata items. Requires staff permissions to access."""+ privateMetadata: [MetadataItem!]!"""- Attribute value.+ A single key from private metadata. Requires staff permissions to access.- Rich text format. For reference see https://editorjs.io/+ Tip: Use GraphQL aliases to fetch multiple keys."""- richText: JSONString-- """Attribute plain text value."""- plainText: String-- """Returns translated attribute value fields for the given language code."""- translation(- """A language code to return the translation for attribute value."""- languageCode: LanguageCodeEnum!- ): AttributeValueTranslation-- """Represents a value of an attribute."""- attributeValue: AttributeValue @deprecated(reason: "Get model fields from the root level queries.")-- """Associated attribute that can be translated."""- attribute: AttributeTranslatableContent-}--"""-Represents attribute's original translatable fields and related translations.-"""-type AttributeTranslatableContent implements Node @doc(category: "Attributes") {- """The ID of the attribute translatable content."""- id: ID!-- """The ID of the attribute to translate."""- attributeId: ID!-- """Name of the attribute to translate."""- name: String!+ privateMetafield(key: String!): String- """Returns translated attribute fields for the given language code."""- translation(- """A language code to return the translation for attribute."""- languageCode: LanguageCodeEnum!- ): AttributeTranslation+ """+ Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.+ """+ privateMetafields(keys: [String!]): Metadata- """Custom attribute of a product."""- attribute: Attribute @deprecated(reason: "Get model fields from the root level queries.")-}+ """List of public metadata items. Can be accessed without permissions."""+ metadata: [MetadataItem!]!-"""Represents attribute translations."""-type AttributeTranslation implements Node @doc(category: "Attributes") {- """The ID of the attribute translation."""- id: ID!+ """+ A single key from public metadata.++ Tip: Use GraphQL aliases to fetch multiple keys.+ """+ metafield(key: String!): String- """Translation language."""- language: LanguageDisplay!+ """+ Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.+ """+ metafields(keys: [String!]): Metadata- """Translated attribute name."""+ """Name of the tax class."""name: String!- """Represents the attribute fields to translate."""- translatableContent: AttributeTranslatableContent-}--type File {- """The URL of the file."""- url: String!-- """Content type of the file."""- contentType: String+ """Country-specific tax rates for this tax class."""+ countries: [TaxClassCountryRate!]!}"""-The `Date` scalar type represents a Date-value as specified by-[iso8601](https://en.wikipedia.org/wiki/ISO_8601).+Tax rate for a country. When tax class is null, it represents the default tax rate for that country; otherwise it's a country tax rate specific to the given tax class."""-scalar Date--input AttributeChoicesSortingInput @doc(category: "Attributes") {- """Specifies the direction in which to sort attribute choices."""- direction: OrderDirection!-- """Sort attribute choices by the selected field."""- field: AttributeChoicesSortField!-}--enum OrderDirection {- """Specifies an ascending sort order."""- ASC-- """Specifies a descending sort order."""- DESC-}--enum AttributeChoicesSortField @doc(category: "Attributes") {- """Sort attribute choice by name."""- NAME-- """Sort attribute choice by slug."""- SLUG-}--input AttributeValueFilterInput @doc(category: "Attributes") {- search: String- ids: [ID!]- slugs: [String!]-}--"""Where filtering options for attribute values."""-input AttributeValueWhereInput @doc(category: "Attributes") {- ids: [ID!]- name: StringFilterInput- slug: StringFilterInput+type TaxClassCountryRate @doc(category: "Taxes") {+ """Country in which this tax rate applies."""+ country: CountryDisplay!- """List of conditions that must be met."""- AND: [AttributeValueWhereInput!]+ """Tax rate value."""+ rate: Float!- """A list of conditions of which at least one must be met."""- OR: [AttributeValueWhereInput!]+ """Related tax class."""+ taxClass: TaxClass}-type ProductTypeCountableConnection @doc(category: "Products") {+type StockCountableConnection @doc(category: "Products") {"""Pagination data for this connection."""pageInfo: PageInfo!- edges: [ProductTypeCountableEdge!]!+ edges: [StockCountableEdge!]!"""A total count of items in the collection."""totalCount: Int}-type ProductTypeCountableEdge @doc(category: "Products") {+type StockCountableEdge @doc(category: "Products") {"""The item at the end of the edge."""- node: ProductType!+ node: Stock!"""A cursor for use in pagination."""cursor: String!}-"""-Represents a single category of products. Categories allow to organize products in a tree-hierarchies which can be used for navigation in the storefront.-"""-type Category implements Node & ObjectWithMetadata @doc(category: "Products") {- """The ID of the category."""+"""Represents stock."""+type Stock implements Node @doc(category: "Products") {+ """The ID of stock."""id: ID!- """List of private metadata items. Requires staff permissions to access."""- privateMetadata: [MetadataItem!]!+ """The warehouse associated with the stock."""+ warehouse: Warehouse!- """- A single key from private metadata. Requires staff permissions to access.-- Tip: Use GraphQL aliases to fetch multiple keys.- """- privateMetafield(key: String!): String+ """Information about the product variant."""+ productVariant: ProductVariant!"""- Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.+ Quantity of a product in the warehouse's possession, including the allocated stock that is waiting for shipment.++ Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS."""- privateMetafields(keys: [String!]): Metadata-- """List of public metadata items. Can be accessed without permissions."""- metadata: [MetadataItem!]!+ quantity: Int!"""- A single key from public metadata.+ Quantity allocated for orders.- Tip: Use GraphQL aliases to fetch multiple keys.+ Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS."""- metafield(key: String!): String+ quantityAllocated: Int!"""- Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.+ Quantity reserved for checkouts.++ Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS."""- metafields(keys: [String!]): Metadata+ quantityReserved: Int!+}- """SEO title of category."""- seoTitle: String+"""List of shipping methods available for the country."""+type ShippingMethodsPerCountry @doc(category: "Shipping") {+ """The country code."""+ countryCode: CountryCode!- """SEO description of category."""- seoDescription: String+ """List of available shipping methods."""+ shippingMethods: [ShippingMethod!]+}- """Name of category"""- name: String!+"""+Represents country codes defined by the ISO 3166-1 alpha-2 standard.- """- Description of the category.-- Rich text format. For reference see https://editorjs.io/- """- description: JSONString+The `EU` value is DEPRECATED and will be removed in Saleor 3.21.+"""+enum CountryCode {+ """Afghanistan"""+ AF- """Slug of the category."""- slug: String!+ """Åland Islands"""+ AX- """Parent category."""- parent: Category+ """Albania"""+ AL- """Level of the category."""- level: Int!+ """Algeria"""+ DZ- """- Description of the category.-- Rich text format. For reference see https://editorjs.io/- """- descriptionJson: JSONString @deprecated(reason: "Use the `description` field instead.")+ """American Samoa"""+ AS- """The date and time when the category was last updated."""- updatedAt: DateTime!+ """Andorra"""+ AD- """List of ancestors of the category."""- ancestors(- """Return the elements in the list that come before the specified cursor."""- before: String+ """Angola"""+ AO- """Return the elements in the list that come after the specified cursor."""- after: String+ """Anguilla"""+ AI- """- Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- first: Int+ """Antarctica"""+ AQ- """- Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- last: Int- ): CategoryCountableConnection+ """Antigua and Barbuda"""+ AG- """- List of products in the category. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS.- """- products(- """Filtering options for products."""- filter: ProductFilterInput @deprecated(reason: "Use `where` filter instead.")+ """Argentina"""+ AR- """Where filtering options for products."""- where: ProductWhereInput+ """Armenia"""+ AM- """Sort products."""- sortBy: ProductOrder+ """Aruba"""+ AW- """Search products."""- search: String+ """Australia"""+ AU- """Slug of a channel for which the data should be returned."""- channel: String+ """Austria"""+ AT- """Return the elements in the list that come before the specified cursor."""- before: String+ """Azerbaijan"""+ AZ- """Return the elements in the list that come after the specified cursor."""- after: String+ """Bahamas"""+ BS- """- Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- first: Int+ """Bahrain"""+ BH- """- Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- last: Int- ): ProductCountableConnection+ """Bangladesh"""+ BD- """List of children of the category."""- children(- """Return the elements in the list that come before the specified cursor."""- before: String+ """Barbados"""+ BB- """Return the elements in the list that come after the specified cursor."""- after: String+ """Belarus"""+ BY- """- Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- first: Int+ """Belgium"""+ BE- """- Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- last: Int- ): CategoryCountableConnection+ """Belize"""+ BZ- """Background image of the category."""- backgroundImage(- """- Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).- """- size: Int+ """Benin"""+ BJ- """- The format of the image. When not provided, format of the original image will be used.- """- format: ThumbnailFormatEnum = ORIGINAL- ): Image+ """Bermuda"""+ BM- """Returns translated category fields for the given language code."""- translation(- """A language code to return the translation for category."""- languageCode: LanguageCodeEnum!- ): CategoryTranslation-}+ """Bhutan"""+ BT-type CategoryCountableConnection @doc(category: "Products") {- """Pagination data for this connection."""- pageInfo: PageInfo!- edges: [CategoryCountableEdge!]!+ """Bolivia"""+ BO- """A total count of items in the collection."""- totalCount: Int-}+ """Bonaire, Sint Eustatius and Saba"""+ BQ-type CategoryCountableEdge @doc(category: "Products") {- """The item at the end of the edge."""- node: Category!+ """Bosnia and Herzegovina"""+ BA- """A cursor for use in pagination."""- cursor: String!-}+ """Botswana"""+ BW-input ProductFilterInput @doc(category: "Products") {- isPublished: Boolean- collections: [ID!]- categories: [ID!]- hasCategory: Boolean- attributes: [AttributeInput!]+ """Bouvet Island"""+ BV- """Filter by variants having specific stock status."""- stockAvailability: StockAvailability- stocks: ProductStockFilterInput- search: String- metadata: [MetadataFilter!]+ """Brazil"""+ BR- """Filter by the publication date."""- publishedFrom: DateTime+ """British Indian Ocean Territory"""+ IO- """Filter by availability for purchase."""- isAvailable: Boolean+ """Brunei"""+ BN- """Filter by the date of availability for purchase."""- availableFrom: DateTime+ """Bulgaria"""+ BG- """Filter by visibility in product listings."""- isVisibleInListing: Boolean- price: PriceRangeInput+ """Burkina Faso"""+ BF- """Filter by the lowest variant price after discounts."""- minimalPrice: PriceRangeInput+ """Burundi"""+ BI- """Filter by when was the most recent update."""- updatedAt: DateTimeRangeInput- productTypes: [ID!]+ """Cabo Verde"""+ CV- """Filter on whether product is a gift card or not."""- giftCard: Boolean- ids: [ID!]- hasPreorderedVariants: Boolean- slugs: [String!]+ """Cambodia"""+ KH- """Specifies the channel by which the data should be filtered."""- channel: String @deprecated(reason: "Use root-level channel argument instead.")-}+ """Cameroon"""+ CM-input AttributeInput @doc(category: "Attributes") {- """Internal representation of an attribute name."""- slug: String+ """Canada"""+ CA- """- Filter by value of the attribute. Only one value input field is allowed. If provided more than one, the error will be raised. Cannot be combined with deprecated fields of `AttributeInput`.- """- value: AssignedAttributeValueInput+ """Cayman Islands"""+ KY- """- Slugs identifying the attributeValues associated with the Attribute. When specified, it filters the results to include only records with one of the matching values. Requires `slug` to be provided.- """- values: [String!] @deprecated(reason: "Use `value` instead.")+ """Central African Republic"""+ CF- """- The range that the returned values should be in. Requires `slug` to be provided.- """- valuesRange: IntRangeInput @deprecated(reason: "Use `value` instead.")+ """Chad"""+ TD- """- The date/time range that the returned values should be in. Requires `slug` to be provided.- """- dateTime: DateTimeRangeInput @deprecated(reason: "Use `value` instead.")+ """Chile"""+ CL- """- The date range that the returned values should be in. In case of date/time attributes, the UTC midnight of the given date is used. Requires `slug` to be provided.- """- date: DateRangeInput @deprecated(reason: "Use `value` instead.")+ """China"""+ CN- """The boolean value of the attribute. Requires `slug` to be provided."""- boolean: Boolean @deprecated(reason: "Use `value` instead.")-}+ """Christmas Island"""+ CX-input AssignedAttributeValueInput {- """Filter by slug assigned to AttributeValue."""- slug: StringFilterInput+ """Cocos (Keeling) Islands"""+ CC- """Filter by name assigned to AttributeValue."""- name: StringFilterInput+ """Colombia"""+ CO- """Filter by numeric value for attributes of numeric type."""- numeric: DecimalFilterInput+ """Comoros"""+ KM- """Filter by date value for attributes of date type."""- date: DateRangeInput+ """Congo"""+ CG- """Filter by date time value for attributes of date time type."""- dateTime: DateTimeRangeInput+ """Congo (the Democratic Republic of the)"""+ CD- """Filter by boolean value for attributes of boolean type."""- boolean: Boolean+ """Cook Islands"""+ CK- """Filter by reference attribute value."""- reference: AssignedAttributeReferenceInput-}+ """Costa Rica"""+ CR-"""Define the filtering options for decimal fields."""-input DecimalFilterInput {- """The value equal to."""- eq: Decimal+ """Côte d'Ivoire"""+ CI- """The value included in."""- oneOf: [Decimal!]+ """Croatia"""+ HR- """The value in range."""- range: DecimalRangeInput-}+ """Cuba"""+ CU-"""-Custom Decimal implementation.+ """Curaçao"""+ CW-Returns Decimal as a float in the API,-parses float to the Decimal on the way back.-"""-scalar Decimal+ """Cyprus"""+ CY-input DecimalRangeInput {- """Decimal value greater than or equal to."""- gte: Decimal+ """Czechia"""+ CZ- """Decimal value less than or equal to."""- lte: Decimal-}+ """Denmark"""+ DK-input DateRangeInput {- """Start date."""- gte: Date+ """Djibouti"""+ DJ- """End date."""- lte: Date-}+ """Dominica"""+ DM-input DateTimeRangeInput {- """Start date."""- gte: DateTime+ """Dominican Republic"""+ DO- """End date."""- lte: DateTime-}+ """Ecuador"""+ EC-input AssignedAttributeReferenceInput {- """- Returns objects with a reference pointing to an object identified by the given ID.- """- referencedIds: ContainsFilterInput+ """Egypt"""+ EG- """- Returns objects with a reference pointing to a page identified by the given slug.- """- pageSlugs: ContainsFilterInput+ """El Salvador"""+ SV- """- Returns objects with a reference pointing to a product identified by the given slug.- """- productSlugs: ContainsFilterInput+ """Equatorial Guinea"""+ GQ- """- Returns objects with a reference pointing to a product variant identified by the given sku.- """- productVariantSkus: ContainsFilterInput+ """Eritrea"""+ ER- """- Returns objects with a reference pointing to a category identified by the given slug.- """- categorySlugs: ContainsFilterInput+ """Estonia"""+ EE- """- Returns objects with a reference pointing to a collection identified by the given slug.- """- collectionSlugs: ContainsFilterInput-}+ """Eswatini"""+ SZ-"""-Define the filtering options for fields that can contain multiple values.-"""-input ContainsFilterInput {- """The field contains at least one of the specified values."""- containsAny: [String!]+ """Ethiopia"""+ ET- """The field contains all of the specified values."""- containsAll: [String!]-}+ """European Union"""+ EU-input IntRangeInput {- """Value greater than or equal to."""- gte: Int+ """Falkland Islands (Malvinas)"""+ FK- """Value less than or equal to."""- lte: Int-}+ """Faroe Islands"""+ FO-enum StockAvailability @doc(category: "Products") {- IN_STOCK- OUT_OF_STOCK-}+ """Fiji"""+ FJ-input ProductStockFilterInput @doc(category: "Products") {- warehouseIds: [ID!]- quantity: IntRangeInput-}+ """Finland"""+ FI-input PriceRangeInput {- """Price greater than or equal to."""- gte: Float+ """France"""+ FR- """Price less than or equal to."""- lte: Float-}+ """French Guiana"""+ GF-input ProductWhereInput @doc(category: "Products") {- metadata: [MetadataFilter!]- ids: [ID!]+ """French Polynesia"""+ PF- """Filter by product name."""- name: StringFilterInput+ """French Southern Territories"""+ TF- """Filter by product slug."""- slug: StringFilterInput+ """Gabon"""+ GA- """Filter by product type."""- productType: GlobalIDFilterInput+ """Gambia"""+ GM- """Filter by product category."""- category: GlobalIDFilterInput+ """Georgia"""+ GE- """Filter by collection."""- collection: GlobalIDFilterInput+ """Germany"""+ DE- """Filter by availability for purchase."""- isAvailable: Boolean+ """Ghana"""+ GH- """Filter by public visibility."""- isPublished: Boolean+ """Gibraltar"""+ GI- """Filter by visibility on the channel."""- isVisibleInListing: Boolean+ """Greece"""+ GR- """Filter by the publication date."""- publishedFrom: DateTime+ """Greenland"""+ GL- """Filter by the date of availability for purchase."""- availableFrom: DateTime+ """Grenada"""+ GD- """Filter by product with category assigned."""- hasCategory: Boolean+ """Guadeloupe"""+ GP- """Filter by product variant price."""- price: DecimalFilterInput+ """Guam"""+ GU- """Filter by the lowest variant price after discounts."""- minimalPrice: DecimalFilterInput+ """Guatemala"""+ GT- """Filter by attributes associated with the product."""- attributes: [AttributeInput!]+ """Guernsey"""+ GG- """Filter by variants having specific stock status."""- stockAvailability: StockAvailability+ """Guinea"""+ GN- """Filter by stock of the product variant."""- stocks: ProductStockFilterInput+ """Guinea-Bissau"""+ GW- """Filter on whether product is a gift card or not."""- giftCard: Boolean+ """Guyana"""+ GY- """Filter by product with preordered variants."""- hasPreorderedVariants: Boolean+ """Haiti"""+ HT- """Filter by when was the most recent update."""- updatedAt: DateTimeFilterInput+ """Heard Island and McDonald Islands"""+ HM- """List of conditions that must be met."""- AND: [ProductWhereInput!]+ """Holy See"""+ VA- """A list of conditions of which at least one must be met."""- OR: [ProductWhereInput!]-}+ """Honduras"""+ HN-"""Define the filtering options for foreign key fields."""-input GlobalIDFilterInput {- """The value equal to."""- eq: ID+ """Hong Kong"""+ HK- """The value included in."""- oneOf: [ID!]-}+ """Hungary"""+ HU-"""Define the filtering options for date time fields."""-input DateTimeFilterInput {- """The value equal to."""- eq: DateTime+ """Iceland"""+ IS- """The value included in."""- oneOf: [DateTime!]+ """India"""+ IN- """The value in range."""- range: DateTimeRangeInput-}+ """Indonesia"""+ ID-input ProductOrder @doc(category: "Products") {- """Specifies the direction in which to sort products."""- direction: OrderDirection!+ """Iran"""+ IR- """Specifies the channel in which to sort the data."""- channel: String @deprecated(reason: "Use root-level channel argument instead.")+ """Iraq"""+ IQ- """- Sort product by the selected attribute's values.- Note: this doesn't take translations into account yet.- """- attributeId: ID+ """Ireland"""+ IE- """Sort products by the selected field."""- field: ProductOrderField-}+ """Isle of Man"""+ IM-enum ProductOrderField @doc(category: "Products") {- """Sort products by name."""- NAME+ """Israel"""+ IL- """- Sort products by rank. Note: This option is available only with the `search` filter.- """- RANK+ """Italy"""+ IT- """- Sort products by price.-- This option requires a channel filter to work as the values can vary between channels.- """- PRICE+ """Jamaica"""+ JM- """- Sort products by a minimal price of a product's variant.-- This option requires a channel filter to work as the values can vary between channels.- """- MINIMAL_PRICE+ """Japan"""+ JP- """Sort products by update date."""- LAST_MODIFIED @deprecated(reason: "Use `LAST_MODIFIED_AT` instead.")+ """Jersey"""+ JE- """Sort products by update date."""- DATE @deprecated(reason: "Use `LAST_MODIFIED_AT` instead.")+ """Jordan"""+ JO- """Sort products by type."""- TYPE+ """Kazakhstan"""+ KZ- """- Sort products by publication status.-- This option requires a channel filter to work as the values can vary between channels.- """- PUBLISHED+ """Kenya"""+ KE- """- Sort products by publication date.-- This option requires a channel filter to work as the values can vary between channels.- """- PUBLICATION_DATE @deprecated(reason: "Use `PUBLISHED_AT` instead.")+ """Kiribati"""+ KI- """- Sort products by publication date.-- This option requires a channel filter to work as the values can vary between channels.- """- PUBLISHED_AT+ """Kosovo"""+ XK- """Sort products by update date."""- LAST_MODIFIED_AT+ """Kuwait"""+ KW- """- Sort products by collection. Note: This option is available only for the `Collection.products` query.-- This option requires a channel filter to work as the values can vary between channels.- """- COLLECTION+ """Kyrgyzstan"""+ KG- """Sort products by rating."""- RATING+ """Laos"""+ LA- """Sort products by creation date."""- CREATED_AT-}+ """Latvia"""+ LV-"""Represents an image."""-type Image {- """The URL of the image."""- url: String!+ """Lebanon"""+ LB- """Alt text for an image."""- alt: String-}+ """Lesotho"""+ LS-enum ThumbnailFormatEnum {- ORIGINAL- AVIF- WEBP-}+ """Liberia"""+ LR-"""Represents category translations."""-type CategoryTranslation implements Node @doc(category: "Products") {- """The ID of the category translation."""- id: ID!+ """Libya"""+ LY- """Translation language."""- language: LanguageDisplay!+ """Liechtenstein"""+ LI- """Translated SEO title."""- seoTitle: String+ """Lithuania"""+ LT- """Translated SEO description."""- seoDescription: String+ """Luxembourg"""+ LU- """Translated category slug."""- slug: String+ """Macao"""+ MO- """Translated category name."""- name: String+ """Madagascar"""+ MG- """- Translated description of the category.-- Rich text format. For reference see https://editorjs.io/- """- description: JSONString+ """Malawi"""+ MW- """- Translated description of the category.-- Rich text format. For reference see https://editorjs.io/- """- descriptionJson: JSONString @deprecated(reason: "Use the `description` field instead.")+ """Malaysia"""+ MY- """Represents the category fields to translate."""- translatableContent: CategoryTranslatableContent-}+ """Maldives"""+ MV-"""-Represents category original translatable fields and related translations.-"""-type CategoryTranslatableContent implements Node @doc(category: "Products") {- """The ID of the category translatable content."""- id: ID!+ """Mali"""+ ML- """The ID of the category to translate."""- categoryId: ID!+ """Malta"""+ MT- """SEO title to translate."""- seoTitle: String+ """Marshall Islands"""+ MH- """SEO description to translate."""- seoDescription: String+ """Martinique"""+ MQ- """Slug to translate."""- slug: String+ """Mauritania"""+ MR- """Name of the category translatable content."""- name: String!+ """Mauritius"""+ MU- """- Category description to translate.-- Rich text format. For reference see https://editorjs.io/- """- description: JSONString+ """Mayotte"""+ YT- """- Description of the category.-- Rich text format. For reference see https://editorjs.io/- """- descriptionJson: JSONString @deprecated(reason: "Use the `description` field instead.")+ """Mexico"""+ MX- """Returns translated category fields for the given language code."""- translation(- """A language code to return the translation for category."""- languageCode: LanguageCodeEnum!- ): CategoryTranslation+ """Micronesia"""+ FM- """Represents a single category of products."""- category: Category @deprecated(reason: "Get model fields from the root level queries.")-}+ """Moldova"""+ MD-"""Represents a version of a product such as different size or color."""-type ProductVariant implements Node & ObjectWithMetadata & ObjectWithAttributes @doc(category: "Products") {- """The ID of the product variant."""- id: ID!+ """Monaco"""+ MC- """List of private metadata items. Requires staff permissions to access."""- privateMetadata: [MetadataItem!]!+ """Mongolia"""+ MN- """- A single key from private metadata. Requires staff permissions to access.-- Tip: Use GraphQL aliases to fetch multiple keys.- """- privateMetafield(key: String!): String+ """Montenegro"""+ ME- """- Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.- """- privateMetafields(keys: [String!]): Metadata+ """Montserrat"""+ MS- """List of public metadata items. Can be accessed without permissions."""- metadata: [MetadataItem!]!+ """Morocco"""+ MA- """- A single key from public metadata.-- Tip: Use GraphQL aliases to fetch multiple keys.- """- metafield(key: String!): String+ """Mozambique"""+ MZ- """- Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.- """- metafields(keys: [String!]): Metadata+ """Myanmar"""+ MM- """- Get a single attribute attached to product by attribute slug.-- Added in Saleor 3.22.- """- assignedAttribute(- """Slug of the attribute"""- slug: String!- ): AssignedAttribute+ """Namibia"""+ NA- """- List of attributes assigned to this variant.-- Added in Saleor 3.22.- """- assignedAttributes(- """Maximum number of attributes to return. Default is 100."""- limit: PositiveInt = 100- ): [AssignedAttribute!]!+ """Nauru"""+ NR- """The name of the product variant."""- name: String!+ """Nepal"""+ NP- """The SKU (stock keeping unit) of the product variant."""- sku: String+ """Netherlands"""+ NL- """The product to which the variant belongs."""- product: Product!+ """New Caledonia"""+ NC- """- Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item. If the field is not provided, `Shop.trackInventoryByDefault` will be used.- """- trackInventory: Boolean!+ """New Zealand"""+ NZ- """The maximum quantity of this variant that a customer can purchase."""- quantityLimitPerCustomer: Int+ """Nicaragua"""+ NI- """The weight of the product variant."""- weight: Weight+ """Niger"""+ NE- """- Channel given to retrieve this product variant. Also used by federation gateway to resolve this object in a federated query.- """- channel: String+ """Nigeria"""+ NG- """- List of price information in channels for the product.-- Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER.- """- channelListings: [ProductVariantChannelListing!]+ """Niue"""+ NU- """- Lists the storefront variant's pricing, the current price and discounts, only meant for displaying.- """- pricing(- """- Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration.- """- address: AddressInput- ): VariantPricingInfo+ """Norfolk Island"""+ NF- """List of attributes assigned to this variant."""- attributes(- """Define scope of returned attributes."""- variantSelection: VariantAttributeScope- ): [SelectedAttribute!]! @deprecated(reason: "Use the `assignedAttributes` field instead.")+ """North Korea"""+ KP- """Gross margin percentage value."""- margin: Int+ """North Macedonia"""+ MK- """- Total quantity ordered.-- Requires one of the following permissions: MANAGE_PRODUCTS.- """- quantityOrdered: Int+ """Northern Mariana Islands"""+ MP- """- Total revenue generated by a variant in given period of time. Note: this field should be queried using `reportProductSales` query as it uses optimizations suitable for such calculations.-- Requires one of the following permissions: MANAGE_PRODUCTS.- """- revenue(period: ReportingPeriod): TaxedMoney+ """Norway"""+ NO- """List of images for the product variant."""- images: [ProductImage!] @deprecated(reason: "Use the `media` field instead.")+ """Oman"""+ OM- """List of media for the product variant."""- media: [ProductMedia!]+ """Pakistan"""+ PK- """Returns translated product variant fields for the given language code."""- translation(- """A language code to return the translation for product variant."""- languageCode: LanguageCodeEnum!- ): ProductVariantTranslation+ """Palau"""+ PW- """- Stocks for the product variant.-- Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS.- """- stocks(- """- Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration. When `Shop.useLegacyShippingZoneStockAvailability` is disabled, this argument is ignored — stock availability is determined by the direct warehouse-channel link instead of shipping zones.- """- address: AddressInput @deprecated+ """Palestine, State of"""+ PS- """Two-letter ISO 3166-1 country code."""- countryCode: CountryCode @deprecated(reason: "Use `address` argument instead.")- ): [Stock!]+ """Panama"""+ PA- """- Quantity of a product available for sale in one checkout. Field value will be `null` when no `limitQuantityPerCheckout` in global settings has been set, and `productVariant` stocks are not tracked.- """- quantityAvailable(- """- Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration. When `Shop.useLegacyShippingZoneStockAvailability` is disabled, this argument is ignored — stock availability is determined by the direct warehouse-channel link instead of shipping zones.- """- address: AddressInput @deprecated+ """Papua New Guinea"""+ PG- """- Two-letter ISO 3166-1 country code. When provided, the exact quantity from a warehouse operating in shipping zones that contain this country will be returned. Otherwise, it will return the maximum quantity from all shipping zones.- """- countryCode: CountryCode @deprecated(reason: "Use `address` argument instead.")- ): Int+ """Paraguay"""+ PY- """Preorder data for product variant."""- preorder: PreorderData+ """Peru"""+ PE- """The date and time when the product variant was created."""- created: DateTime!+ """Philippines"""+ PH- """The date and time when the product variant was last updated."""- updatedAt: DateTime!+ """Pitcairn"""+ PN- """External ID of this product."""- externalReference: String-}+ """Poland"""+ PL-"""Represents product variant channel listing."""-type ProductVariantChannelListing implements Node @doc(category: "Products") {- """The ID of the variant channel listing."""- id: ID!+ """Portugal"""+ PT- """The channel to which the variant listing belongs."""- channel: Channel!+ """Puerto Rico"""+ PR- """The price of the variant."""- price: Money+ """Qatar"""+ QA- """Cost price of the variant."""- costPrice: Money+ """Réunion"""+ RE- """- Previous price of the variant in channel. Useful for providing promotion information required by customer protection laws such as EU Omnibus directive.-- Warning: This field is not updated automatically. Use Channel Listings mutation to update it manually.- """- priorPrice: Money+ """Romania"""+ RO- """- Gross margin percentage value.-- Requires one of the following permissions: MANAGE_PRODUCTS.- """- margin: Int+ """Russia"""+ RU- """Preorder variant data."""- preorderThreshold: PreorderThreshold-}+ """Rwanda"""+ RW-"""Represents preorder variant data for channel."""-type PreorderThreshold @doc(category: "Products") {- """Preorder threshold for product variant in this channel."""- quantity: Int+ """Saint Barthélemy"""+ BL- """Number of sold product variant in this channel."""- soldUnits: Int!-}+ """Saint Helena, Ascension and Tristan da Cunha"""+ SH-"""Represents availability of a variant in the storefront."""-type VariantPricingInfo @doc(category: "Products") {- """Whether it is in sale or not."""- onSale: Boolean+ """Saint Kitts and Nevis"""+ KN- """The discount amount if in sale (null otherwise)."""- discount: TaxedMoney+ """Saint Lucia"""+ LC- """- The discount amount compared to prior price. Null if product is not on sale or prior price was not provided in VariantChannelListing- """- discountPrior: TaxedMoney+ """Saint Martin (French part)"""+ MF- """The discount amount in the local currency."""- discountLocalCurrency: TaxedMoney @deprecated(reason: "Always returns `null`.")+ """Saint Pierre and Miquelon"""+ PM- """The price, with any discount subtracted."""- price: TaxedMoney+ """Saint Vincent and the Grenadines"""+ VC- """The price without any discount."""- priceUndiscounted: TaxedMoney+ """Samoa"""+ WS- """The price prior to discount."""- pricePrior: TaxedMoney+ """San Marino"""+ SM- """The discounted price in the local currency."""- priceLocalCurrency: TaxedMoney @deprecated(reason: "Always returns `null`.")-}+ """Sao Tome and Principe"""+ ST-"""-Represents a monetary value with taxes. In cases where taxes were not applied, net and gross values will be equal.-"""-type TaxedMoney {- """Currency code."""- currency: String!+ """Saudi Arabia"""+ SA- """Amount of money including taxes."""- gross: Money!+ """Senegal"""+ SN- """Amount of money without taxes."""- net: Money!+ """Serbia"""+ RS- """Amount of taxes."""- tax: Money!-}+ """Seychelles"""+ SC-input AddressInput {- """Given name."""- firstName: String+ """Sierra Leone"""+ SL- """Family name."""- lastName: String+ """Singapore"""+ SG- """Company or organization."""- companyName: String+ """Sint Maarten (Dutch part)"""+ SX- """Address."""- streetAddress1: String+ """Slovakia"""+ SK- """Address."""- streetAddress2: String+ """Slovenia"""+ SI- """City."""- city: String+ """Solomon Islands"""+ SB- """District."""- cityArea: String+ """Somalia"""+ SO- """Postal code."""- postalCode: String+ """South Africa"""+ ZA- """Country."""- country: CountryCode+ """South Georgia and the South Sandwich Islands"""+ GS- """State or province."""- countryArea: String+ """South Korea"""+ KR- """- Phone number.-- Phone numbers are validated with Google's [libphonenumber](https://github.com/google/libphonenumber) library.- """- phone: String+ """South Sudan"""+ SS- """- Address public metadata. Can be read by any API client authorized to read the object it's attached to.-- Warning: never store sensitive information, including financial data such as credit card details.- """- metadata: [MetadataInput!]+ """Spain"""+ ES- """- Determine if the address should be validated. By default, Saleor accepts only address inputs matching ruleset from [Google Address Data]{https://chromium-i18n.appspot.com/ssl-address), using [i18naddress](https://github.com/mirumee/google-i18n-address) library. Some mutations may require additional permissions to use the the field. More info about permissions can be found in relevant mutation.-- Note: this API is currently in Feature Preview and can be subject to changes at later point.- """- skipValidation: Boolean = false-}+ """Sri Lanka"""+ LK-"""-Represents country codes defined by the ISO 3166-1 alpha-2 standard.+ """Sudan"""+ SD-The `EU` value is DEPRECATED and will be removed in Saleor 3.21.-"""-enum CountryCode {- """Afghanistan"""- AF+ """Suriname"""+ SR- """Åland Islands"""- AX+ """Svalbard and Jan Mayen"""+ SJ- """Albania"""- AL+ """Sweden"""+ SE- """Algeria"""- DZ+ """Switzerland"""+ CH- """American Samoa"""- AS+ """Syria"""+ SY- """Andorra"""- AD+ """Taiwan"""+ TW- """Angola"""- AO+ """Tajikistan"""+ TJ- """Anguilla"""- AI+ """Tanzania"""+ TZ- """Antarctica"""- AQ+ """Thailand"""+ TH- """Antigua and Barbuda"""- AG+ """Timor-Leste"""+ TL- """Argentina"""- AR+ """Togo"""+ TG- """Armenia"""- AM+ """Tokelau"""+ TK- """Aruba"""- AW+ """Tonga"""+ TO- """Australia"""- AU+ """Trinidad and Tobago"""+ TT- """Austria"""- AT+ """Tunisia"""+ TN- """Azerbaijan"""- AZ+ """Türkiye"""+ TR- """Bahamas"""- BS+ """Turkmenistan"""+ TM- """Bahrain"""- BH+ """Turks and Caicos Islands"""+ TC- """Bangladesh"""- BD+ """Tuvalu"""+ TV- """Barbados"""- BB+ """Uganda"""+ UG- """Belarus"""- BY+ """Ukraine"""+ UA- """Belgium"""- BE+ """United Arab Emirates"""+ AE- """Belize"""- BZ+ """United Kingdom"""+ GB- """Benin"""- BJ+ """United States Minor Outlying Islands"""+ UM- """Bermuda"""- BM+ """United States of America"""+ US- """Bhutan"""- BT+ """Uruguay"""+ UY- """Bolivia"""- BO+ """Uzbekistan"""+ UZ- """Bonaire, Sint Eustatius and Saba"""- BQ+ """Vanuatu"""+ VU- """Bosnia and Herzegovina"""- BA+ """Venezuela"""+ VE- """Botswana"""- BW+ """Vietnam"""+ VN- """Bouvet Island"""- BV-- """Brazil"""- BR-- """British Indian Ocean Territory"""- IO-- """Brunei"""- BN-- """Bulgaria"""- BG-- """Burkina Faso"""- BF-- """Burundi"""- BI-- """Cabo Verde"""- CV-- """Cambodia"""- KH-- """Cameroon"""- CM-- """Canada"""- CA-- """Cayman Islands"""- KY-- """Central African Republic"""- CF-- """Chad"""- TD-- """Chile"""- CL-- """China"""- CN-- """Christmas Island"""- CX-- """Cocos (Keeling) Islands"""- CC-- """Colombia"""- CO-- """Comoros"""- KM-- """Congo"""- CG-- """Congo (the Democratic Republic of the)"""- CD-- """Cook Islands"""- CK-- """Costa Rica"""- CR-- """Côte d'Ivoire"""- CI-- """Croatia"""- HR-- """Cuba"""- CU-- """Curaçao"""- CW-- """Cyprus"""- CY-- """Czechia"""- CZ-- """Denmark"""- DK-- """Djibouti"""- DJ-- """Dominica"""- DM-- """Dominican Republic"""- DO-- """Ecuador"""- EC-- """Egypt"""- EG-- """El Salvador"""- SV-- """Equatorial Guinea"""- GQ-- """Eritrea"""- ER-- """Estonia"""- EE-- """Eswatini"""- SZ-- """Ethiopia"""- ET-- """European Union"""- EU-- """Falkland Islands (Malvinas)"""- FK-- """Faroe Islands"""- FO-- """Fiji"""- FJ-- """Finland"""- FI-- """France"""- FR-- """French Guiana"""- GF-- """French Polynesia"""- PF-- """French Southern Territories"""- TF-- """Gabon"""- GA-- """Gambia"""- GM-- """Georgia"""- GE-- """Germany"""- DE-- """Ghana"""- GH-- """Gibraltar"""- GI-- """Greece"""- GR-- """Greenland"""- GL-- """Grenada"""- GD-- """Guadeloupe"""- GP-- """Guam"""- GU-- """Guatemala"""- GT-- """Guernsey"""- GG-- """Guinea"""- GN-- """Guinea-Bissau"""- GW-- """Guyana"""- GY-- """Haiti"""- HT-- """Heard Island and McDonald Islands"""- HM-- """Holy See"""- VA-- """Honduras"""- HN-- """Hong Kong"""- HK-- """Hungary"""- HU-- """Iceland"""- IS-- """India"""- IN+ """Virgin Islands (British)"""+ VG- """Indonesia"""- ID+ """Virgin Islands (U.S.)"""+ VI- """Iran"""- IR+ """Wallis and Futuna"""+ WF- """Iraq"""- IQ+ """Western Sahara"""+ EH- """Ireland"""- IE+ """Yemen"""+ YE- """Isle of Man"""- IM+ """Zambia"""+ ZM- """Israel"""- IL+ """Zimbabwe"""+ ZW+}- """Italy"""- IT+"""+Shipping methods that can be used as means of shipping for orders and checkouts.+"""+type ShippingMethod implements Node & ObjectWithMetadata @doc(category: "Shipping") {+ """Unique ID of ShippingMethod available for Order."""+ id: ID!- """Jamaica"""- JM+ """List of private metadata items. Requires staff permissions to access."""+ privateMetadata: [MetadataItem!]!- """Japan"""- JP+ """+ A single key from private metadata. Requires staff permissions to access.++ Tip: Use GraphQL aliases to fetch multiple keys.+ """+ privateMetafield(key: String!): String- """Jersey"""- JE+ """+ Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.+ """+ privateMetafields(keys: [String!]): Metadata- """Jordan"""- JO+ """List of public metadata items. Can be accessed without permissions."""+ metadata: [MetadataItem!]!- """Kazakhstan"""- KZ+ """+ A single key from public metadata.++ Tip: Use GraphQL aliases to fetch multiple keys.+ """+ metafield(key: String!): String- """Kenya"""- KE+ """+ Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.+ """+ metafields(keys: [String!]): Metadata- """Kiribati"""- KI+ """Type of the shipping method."""+ type: ShippingMethodTypeEnum @deprecated- """Kosovo"""- XK+ """Shipping method name."""+ name: String!- """Kuwait"""- KW+ """+ Shipping method description.++ Rich text format. For reference see https://editorjs.io/+ """+ description: JSONString- """Kyrgyzstan"""- KG+ """Maximum delivery days for this shipping method."""+ maximumDeliveryDays: Int- """Laos"""- LA+ """Minimum delivery days for this shipping method."""+ minimumDeliveryDays: Int- """Latvia"""- LV+ """Maximum order weight for this shipping method."""+ maximumOrderWeight: Weight @deprecated- """Lebanon"""- LB+ """Minimum order weight for this shipping method."""+ minimumOrderWeight: Weight @deprecated- """Lesotho"""- LS+ """Returns translated shipping method fields for the given language code."""+ translation(+ """A language code to return the translation for shipping method."""+ languageCode: LanguageCodeEnum!+ ): ShippingMethodTranslation- """Liberia"""- LR+ """The price of selected shipping method."""+ price: Money!- """Libya"""- LY+ """Maximum order price for this shipping method."""+ maximumOrderPrice: Money @deprecated- """Liechtenstein"""- LI+ """Minimal order price for this shipping method."""+ minimumOrderPrice: Money @deprecated- """Lithuania"""- LT+ """Describes if this shipping method is active and can be selected."""+ active: Boolean!- """Luxembourg"""- LU+ """Message connected to this shipping method."""+ message: String+}- """Macao"""- MO+"""Represents the channel stock settings."""+type StockSettings @doc(category: "Products") {+ """+ Allocation strategy defines the preference of warehouses for allocations and reservations.+ """+ allocationStrategy: AllocationStrategyEnum!+}- """Madagascar"""- MG+"""+Determine the allocation strategy for the channel.- """Malawi"""- MW+ PRIORITIZE_SORTING_ORDER - allocate stocks according to the warehouses' order+ within the channel- """Malaysia"""- MY+ PRIORITIZE_HIGH_STOCK - allocate stock in a warehouse with the most stock+"""+enum AllocationStrategyEnum @doc(category: "Products") {+ PRIORITIZE_SORTING_ORDER+ PRIORITIZE_HIGH_STOCK+}- """Maldives"""- MV+"""Represents the channel-specific order settings."""+type OrderSettings {+ """+ When disabled, all new orders from checkout will be marked as unconfirmed. When enabled orders from checkout will become unfulfilled immediately.+ """+ automaticallyConfirmAllNewOrders: Boolean!- """Mali"""- ML+ """+ When enabled, all non-shippable gift card orders will be fulfilled automatically.+ """+ automaticallyFulfillNonShippableGiftCard: Boolean!- """Malta"""- MT+ """+ Expiration time in minutes. Default null - means do not expire any orders.+ """+ expireOrdersAfter: Minute- """Marshall Islands"""- MH+ """+ Determine what strategy will be used to mark the order as paid. Based on the chosen option, the proper object will be created and attached to the order when it's manually marked as paid.+ `PAYMENT_FLOW` - [default option] creates the `Payment` object.+ `TRANSACTION_FLOW` - creates the `TransactionItem` object.+ """+ markAsPaidStrategy: MarkAsPaidStrategyEnum!- """Martinique"""- MQ+ """The time in days after expired orders will be deleted."""+ deleteExpiredOrdersAfter: Day!- """Mauritania"""- MR+ """+ Determine if it is possible to place unpaid order by calling `checkoutComplete` mutation.+ """+ allowUnpaidOrders: Boolean!- """Mauritius"""- MU+ """+ Determine if voucher applied on draft order should be count toward voucher usage.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ includeDraftOrderInVoucherUsage: Boolean!- """Mayotte"""- YT+ """+ Time in hours after which the draft order line price will be refreshed.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ draftOrderLinePriceFreezePeriod: Hour- """Mexico"""- MX+ """+ This flag only affects orders created from checkout and applies specifically to vouchers of the types: `SPECIFIC_PRODUCT` and `ENTIRE_ORDER` with `applyOncePerOrder` enabled.+ - When legacy propagation is enabled, discounts from these vouchers are represented as `OrderDiscount` objects, attached to the order and returned in the `Order.discounts` field. Additionally, percentage-based vouchers are converted to fixed-value discounts.+ - When legacy propagation is disabled, discounts are represented as `OrderLineDiscount` objects, attached to individual lines and returned in the `OrderLine.discounts` field. In this case, percentage-based vouchers retain their original type.+ In future releases, `OrderLineDiscount` will become the default behavior, and this flag will be deprecated and removed.+ """+ useLegacyLineDiscountPropagation: Boolean!+}- """Micronesia"""- FM+"""+The `Minute` scalar type represents number of minutes by integer value.+"""+scalar Minute- """Moldova"""- MD+"""+Determine the mark as paid strategy for the channel.- """Monaco"""- MC+ TRANSACTION_FLOW - new orders marked as paid will receive a+ `TransactionItem` object, that will cover the `order.total`.- """Mongolia"""- MN+ PAYMENT_FLOW - new orders marked as paid will receive a+ `Payment` object, that will cover the `order.total`.+"""+enum MarkAsPaidStrategyEnum @doc(category: "Channels") {+ TRANSACTION_FLOW+ PAYMENT_FLOW @deprecated(reason: "The legacy Payments API is deprecated and will be removed. Use the Transactions API instead.")+}- """Montenegro"""- ME+"""The `Day` scalar type represents number of days by integer value."""+scalar Day- """Montserrat"""- MS+"""The `Hour` scalar type represents number of hours by integer value."""+scalar Hour- """Morocco"""- MA+"""Represents the channel-specific checkout settings."""+type CheckoutSettings {+ """+ Default `true`. Determines if the checkout mutations should use legacy error flow. In legacy flow, all mutations can raise an exception unrelated to the requested action - (e.g. out-of-stock exception when updating checkoutShippingAddress.) If `false`, the errors will be aggregated in `checkout.problems` field. Some of the `problems` can block the finalizing checkout process. The legacy flow will be removed in Saleor 4.0. The flow with `checkout.problems` will be the default one.+ """+ useLegacyErrorFlow: Boolean!- """Mozambique"""- MZ+ """+ Default `false`. Determines if the paid checkouts should be automatically completed. This setting applies only to checkouts where payment was processed through transactions.When enabled, the checkout will be automatically completed once the checkout `charge_status` reaches `FULL`. This occurs when the total sum of charged and authorized transaction amounts equals or exceeds the checkout's total amount.+ """+ automaticallyCompleteFullyPaidCheckouts: Boolean!- """Myanmar"""- MM+ """+ The time in minutes to wait after a checkout is fully paid before automatically completing it.++ Added in Saleor 3.22.+ """+ automaticCompletionDelay: Minute- """Namibia"""- NA+ """+ The date time defines the earliest checkout creation date on which fully paid checkouts can begin to be automatically completed.++ Added in Saleor 3.22.+ """+ automaticCompletionCutOffDate: DateTime- """Nauru"""- NR+ """+ Default to `true`. Determines whether gift cards can be attached to a Checkout via `addPromoCode` mutation. Usage of this mutation with gift cards is deprecated.++ Added in Saleor 3.23.+ """+ allowLegacyGiftCardUse: Boolean!+}- """Nepal"""- NP+"""Represents the channel-specific payment settings."""+type PaymentSettings {+ """+ Determine the transaction flow strategy to be used. Include the selected option in the payload sent to the payment app, as a requested action for the transaction.+ """+ defaultTransactionFlowStrategy: TransactionFlowStrategyEnum!- """Netherlands"""- NL+ """+ Determine if the funds for expired checkouts should be released automatically.+ """+ releaseFundsForExpiredCheckouts: Boolean- """New Caledonia"""- NC+ """+ The time in hours after which funds for expired checkouts will be released.+ """+ checkoutTtlBeforeReleasingFunds: Hour- """New Zealand"""- NZ+ """+ Specifies the earliest date on which funds for expired checkouts can begin to be released. Expired checkouts dated before this cut-off will not have their funds released. Additionally, no funds will be released for checkouts that are more than one year old, regardless of the cut-off date.+ """+ checkoutReleaseFundsCutOffDate: DateTime+}- """Nicaragua"""- NI+"""+Determine the transaction flow strategy.- """Niger"""- NE+ AUTHORIZATION - the processed transaction should be only authorized+ CHARGE - the processed transaction should be charged.+"""+enum TransactionFlowStrategyEnum @doc(category: "Payments") {+ AUTHORIZATION+ CHARGE+}- """Nigeria"""- NG+"""Channel-specific tax configuration."""+type TaxConfiguration implements Node & ObjectWithMetadata @doc(category: "Taxes") {+ """The ID of the object."""+ id: ID!- """Niue"""- NU+ """List of private metadata items. Requires staff permissions to access."""+ privateMetadata: [MetadataItem!]!- """Norfolk Island"""- NF+ """+ A single key from private metadata. Requires staff permissions to access.++ Tip: Use GraphQL aliases to fetch multiple keys.+ """+ privateMetafield(key: String!): String- """North Korea"""- KP+ """+ Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.+ """+ privateMetafields(keys: [String!]): Metadata- """North Macedonia"""- MK+ """List of public metadata items. Can be accessed without permissions."""+ metadata: [MetadataItem!]!- """Northern Mariana Islands"""- MP+ """+ A single key from public metadata.++ Tip: Use GraphQL aliases to fetch multiple keys.+ """+ metafield(key: String!): String- """Norway"""- NO+ """+ Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.+ """+ metafields(keys: [String!]): Metadata- """Oman"""- OM+ """A channel to which the tax configuration applies to."""+ channel: Channel!- """Pakistan"""- PK+ """Determines whether taxes are charged in the given channel."""+ chargeTaxes: Boolean!- """Palau"""- PW+ """+ The default strategy to use for tax calculation in the given channel. Taxes can be calculated either using user-defined flat rates or with a tax app. Empty value means that no method is selected and taxes are not calculated.+ """+ taxCalculationStrategy: TaxCalculationStrategy- """Palestine, State of"""- PS+ """Determines whether displayed prices should include taxes."""+ displayGrossPrices: Boolean!- """Panama"""- PA+ """Determines whether prices are entered with the tax included."""+ pricesEnteredWithTax: Boolean!- """Papua New Guinea"""- PG+ """List of country-specific exceptions in tax configuration."""+ countries: [TaxConfigurationPerCountry!]!- """Paraguay"""- PY+ """+ The tax app `App.identifier` that will be used to calculate the taxes for the given channel. Empty value for `TAX_APP` set as `taxCalculationStrategy` means that Saleor will iterate over all installed tax apps. If multiple tax apps exist with provided tax app id use the `App` with newest `created` date. Will become mandatory in 4.0 for `TAX_APP` `taxCalculationStrategy`.+ """+ taxAppId: String- """Peru"""- PE+ """+ Determines whether to use weighted tax for shipping. When set to true, the tax rate for shipping will be calculated based on the weighted average of tax rates from the order or checkout lines.+ """+ useWeightedTaxForShipping: Boolean+}- """Philippines"""- PH+enum TaxCalculationStrategy @doc(category: "Taxes") {+ FLAT_RATES+ TAX_APP+}- """Pitcairn"""- PN+"""Country-specific exceptions of a channel's tax configuration."""+type TaxConfigurationPerCountry @doc(category: "Taxes") {+ """Country in which this configuration applies."""+ country: CountryDisplay!- """Poland"""- PL+ """Determines whether taxes are charged in this country."""+ chargeTaxes: Boolean!- """Portugal"""- PT+ """+ A country-specific strategy to use for tax calculation. Taxes can be calculated either using user-defined flat rates or with a tax app. If not provided, use the value from the channel's tax configuration.+ """+ taxCalculationStrategy: TaxCalculationStrategy- """Puerto Rico"""- PR+ """+ Determines whether displayed prices should include taxes for this country.+ """+ displayGrossPrices: Boolean!- """Qatar"""- QA+ """+ The tax app `App.identifier` that will be used to calculate the taxes for the given channel and country. If not provided, use the value from the channel's tax configuration.+ """+ taxAppId: String- """Réunion"""- RE+ """+ Determines whether to use weighted tax for shipping. When set to true, the tax rate for shipping will be calculated based on the weighted average of tax rates from the order or checkout lines.+ """+ useWeightedTaxForShipping: Boolean+}- """Romania"""- RO+"""Represents preorder variant data for channel."""+type PreorderThreshold @doc(category: "Products") {+ """Preorder threshold for product variant in this channel."""+ quantity: Int- """Russia"""- RU+ """Number of sold product variant in this channel."""+ soldUnits: Int!+}- """Rwanda"""- RW+"""Represents availability of a variant in the storefront."""+type VariantPricingInfo @doc(category: "Products") {+ """Whether it is in sale or not."""+ onSale: Boolean- """Saint Barthélemy"""- BL+ """The discount amount if in sale (null otherwise)."""+ discount: TaxedMoney- """Saint Helena, Ascension and Tristan da Cunha"""- SH+ """+ The discount amount compared to prior price. Null if product is not on sale or prior price was not provided in VariantChannelListing+ """+ discountPrior: TaxedMoney- """Saint Kitts and Nevis"""- KN+ """The discount amount in the local currency."""+ discountLocalCurrency: TaxedMoney @deprecated(reason: "Always returns `null`.")- """Saint Lucia"""- LC+ """The price, with any discount subtracted."""+ price: TaxedMoney- """Saint Martin (French part)"""- MF+ """The price without any discount."""+ priceUndiscounted: TaxedMoney- """Saint Pierre and Miquelon"""- PM+ """The price prior to discount."""+ pricePrior: TaxedMoney- """Saint Vincent and the Grenadines"""- VC+ """The discounted price in the local currency."""+ priceLocalCurrency: TaxedMoney @deprecated(reason: "Always returns `null`.")+}- """Samoa"""- WS+"""+Represents a monetary value with taxes. In cases where taxes were not applied, net and gross values will be equal.+"""+type TaxedMoney {+ """Currency code."""+ currency: String!- """San Marino"""- SM+ """Amount of money including taxes."""+ gross: Money!- """Sao Tome and Principe"""- ST+ """Amount of money without taxes."""+ net: Money!- """Saudi Arabia"""- SA+ """Amount of taxes."""+ tax: Money!+}- """Senegal"""- SN+input AddressInput {+ """Given name."""+ firstName: String- """Serbia"""- RS+ """Family name."""+ lastName: String- """Seychelles"""- SC+ """Company or organization."""+ companyName: String- """Sierra Leone"""- SL+ """Address."""+ streetAddress1: String- """Singapore"""- SG+ """Address."""+ streetAddress2: String- """Sint Maarten (Dutch part)"""- SX+ """City."""+ city: String- """Slovakia"""- SK+ """District."""+ cityArea: String- """Slovenia"""- SI+ """Postal code."""+ postalCode: String- """Solomon Islands"""- SB+ """Country."""+ country: CountryCode- """Somalia"""- SO+ """State or province."""+ countryArea: String- """South Africa"""- ZA+ """+ Phone number.++ Phone numbers are validated with Google's [libphonenumber](https://github.com/google/libphonenumber) library.+ """+ phone: String- """South Georgia and the South Sandwich Islands"""- GS+ """+ Address public metadata. Can be read by any API client authorized to read the object it's attached to.++ Warning: never store sensitive information, including financial data such as credit card details.+ """+ metadata: [MetadataInput!]- """South Korea"""- KR+ """+ Determine if the address should be validated. By default, Saleor accepts only address inputs matching ruleset from [Google Address Data]{https://chromium-i18n.appspot.com/ssl-address), using [i18naddress](https://github.com/mirumee/google-i18n-address) library. Some mutations may require additional permissions to use the the field. More info about permissions can be found in relevant mutation.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ skipValidation: Boolean = false+}- """South Sudan"""- SS+input MetadataInput {+ """Key of a metadata item."""+ key: String!- """Spain"""- ES+ """Value of a metadata item."""+ value: String!+}- """Sri Lanka"""- LK+"""Represents an assigned attribute to an object."""+type SelectedAttribute @doc(category: "Attributes") {+ """Name of an attribute displayed in the interface."""+ attribute: Attribute!- """Sudan"""- SD+ """Values of an attribute."""+ values: [AttributeValue!]!+}- """Suriname"""- SR+"""Represents a value of an attribute."""+type AttributeValue implements Node @doc(category: "Attributes") {+ """The ID of the attribute value."""+ id: ID!- """Svalbard and Jan Mayen"""- SJ+ """Name of a value displayed in the interface."""+ name: String- """Sweden"""- SE+ """Internal representation of a value (unique per attribute)."""+ slug: String- """Switzerland"""- CH+ """+ Represent value of the attribute value (e.g. color values for swatch attributes).+ """+ value: String- """Syria"""- SY+ """Returns translated attribute value fields for the given language code."""+ translation(+ """A language code to return the translation for attribute value."""+ languageCode: LanguageCodeEnum!+ ): AttributeValueTranslation- """Taiwan"""- TW+ """The input type to use for entering attribute values in the dashboard."""+ inputType: AttributeInputTypeEnum- """Tajikistan"""- TJ+ """The ID of the referenced object."""+ reference: ID- """Tanzania"""- TZ+ """Represents file URL and content type (if attribute value is a file)."""+ file: File- """Thailand"""- TH+ """+ Represents the text of the attribute value, includes formatting.++ Rich text format. For reference see https://editorjs.io/+ """+ richText: JSONString- """Timor-Leste"""- TL+ """+ Represents the text of the attribute value, plain text without formatting.+ """+ plainText: String- """Togo"""- TG+ """Represents the boolean value of the attribute value."""+ boolean: Boolean- """Tokelau"""- TK+ """Represents the date value of the attribute value."""+ date: Date- """Tonga"""- TO+ """Represents the date/time value of the attribute value."""+ dateTime: DateTime- """Trinidad and Tobago"""- TT+ """External ID of this attribute value."""+ externalReference: String+}- """Tunisia"""- TN+"""Represents attribute value translations."""+type AttributeValueTranslation implements Node @doc(category: "Attributes") {+ """The ID of the attribute value translation."""+ id: ID!- """Türkiye"""- TR+ """Translation language."""+ language: LanguageDisplay!- """Turkmenistan"""- TM+ """Translated attribute value name."""+ name: String!- """Turks and Caicos Islands"""- TC+ """+ Translated rich-text attribute value.++ Rich text format. For reference see https://editorjs.io/+ """+ richText: JSONString- """Tuvalu"""- TV+ """Translated plain text attribute value ."""+ plainText: String- """Uganda"""- UG+ """Represents the attribute value fields to translate."""+ translatableContent: AttributeValueTranslatableContent+}- """Ukraine"""- UA+"""+Represents attribute value's original translatable fields and related translations.+"""+type AttributeValueTranslatableContent implements Node @doc(category: "Attributes") {+ """The ID of the attribute value translatable content."""+ id: ID!- """United Arab Emirates"""- AE+ """The ID of the attribute value to translate."""+ attributeValueId: ID!- """United Kingdom"""- GB+ """Name of the attribute value to translate."""+ name: String!- """United States Minor Outlying Islands"""- UM+ """+ Attribute value.++ Rich text format. For reference see https://editorjs.io/+ """+ richText: JSONString- """United States of America"""- US+ """Attribute plain text value."""+ plainText: String- """Uruguay"""- UY+ """Returns translated attribute value fields for the given language code."""+ translation(+ """A language code to return the translation for attribute value."""+ languageCode: LanguageCodeEnum!+ ): AttributeValueTranslation- """Uzbekistan"""- UZ+ """Represents a value of an attribute."""+ attributeValue: AttributeValue @deprecated(reason: "Get model fields from the root level queries.")- """Vanuatu"""- VU+ """Associated attribute that can be translated."""+ attribute: AttributeTranslatableContent+}- """Venezuela"""- VE+"""+Represents attribute's original translatable fields and related translations.+"""+type AttributeTranslatableContent implements Node @doc(category: "Attributes") {+ """The ID of the attribute translatable content."""+ id: ID!- """Vietnam"""- VN+ """The ID of the attribute to translate."""+ attributeId: ID!- """Virgin Islands (British)"""- VG+ """Name of the attribute to translate."""+ name: String!- """Virgin Islands (U.S.)"""- VI+ """Returns translated attribute fields for the given language code."""+ translation(+ """A language code to return the translation for attribute."""+ languageCode: LanguageCodeEnum!+ ): AttributeTranslation- """Wallis and Futuna"""- WF+ """Custom attribute of a product."""+ attribute: Attribute @deprecated(reason: "Get model fields from the root level queries.")+}- """Western Sahara"""- EH+"""Represents attribute translations."""+type AttributeTranslation implements Node @doc(category: "Attributes") {+ """The ID of the attribute translation."""+ id: ID!- """Yemen"""- YE+ """Translation language."""+ language: LanguageDisplay!- """Zambia"""- ZM+ """Translated attribute name."""+ name: String!- """Zimbabwe"""- ZW+ """Represents the attribute fields to translate."""+ translatableContent: AttributeTranslatableContent}-input MetadataInput {- """Key of a metadata item."""- key: String!+type File {+ """The URL of the file."""+ url: String!- """Value of a metadata item."""- value: String!+ """Content type of the file."""+ contentType: String}-"""Represents an assigned attribute to an object."""-type SelectedAttribute @doc(category: "Attributes") {- """Name of an attribute displayed in the interface."""- attribute: Attribute!-- """Values of an attribute."""- values: [AttributeValue!]!+enum VariantAttributeScope @doc(category: "Products") {+ ALL+ VARIANT_SELECTION+ NOT_VARIANT_SELECTION}enum ReportingPeriod {@@ -9875,39 +9857,6 @@ type ProductVariantTranslatableContent implements Node @doc(category: "Products"attributeValues: [AttributeValueTranslatableContent!]!}-"""Represents stock."""-type Stock implements Node @doc(category: "Products") {- """The ID of stock."""- id: ID!-- """The warehouse associated with the stock."""- warehouse: Warehouse!-- """Information about the product variant."""- productVariant: ProductVariant!-- """- Quantity of a product in the warehouse's possession, including the allocated stock that is waiting for shipment.-- Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS.- """- quantity: Int!-- """- Quantity allocated for orders.-- Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS.- """- quantityAllocated: Int!-- """- Quantity reserved for checkouts.-- Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS.- """- quantityReserved: Int!-}-"""Represents preorder settings for product variant."""type PreorderData @doc(category: "Products") {"""@@ -9971,6 +9920,15 @@ type TaxedMoneyRange {stop: TaxedMoney}+"""Representation of tax types fetched from tax gateway."""+type TaxType @doc(category: "Taxes") {+ """Description of the tax type."""+ description: String++ """External tax code used to identify given tax group."""+ taxCode: String+}+"""Represents product channel listing."""type ProductChannelListing implements Node @doc(category: "Products") {"""The ID of the product channel listing."""@@ -10445,37 +10403,159 @@ type ProductTranslatableContent implements Node @doc(category: "Products") {attributeValues: [AttributeValueTranslatableContent!]!}-type StockCountableConnection @doc(category: "Products") {+"""+Represents assigned attribute to variant with variant selection attached.+"""+type AssignedVariantAttribute @doc(category: "Attributes") {+ """Attribute assigned to variant."""+ attribute: Attribute!++ """+ Determines, whether assigned attribute is allowed for variant selection. Supported variant types for variant selection are: ['dropdown', 'boolean', 'swatch', 'numeric']+ """+ variantSelection: Boolean!+}++type AttributeCountableConnection @doc(category: "Attributes") {"""Pagination data for this connection."""pageInfo: PageInfo!- edges: [StockCountableEdge!]!+ edges: [AttributeCountableEdge!]!"""A total count of items in the collection."""totalCount: Int}-type StockCountableEdge @doc(category: "Products") {+type AttributeCountableEdge @doc(category: "Attributes") {"""The item at the end of the edge."""- node: Stock!+ node: Attribute!"""A cursor for use in pagination."""cursor: String!}-"""List of shipping methods available for the country."""-type ShippingMethodsPerCountry @doc(category: "Shipping") {- """The country code."""- countryCode: CountryCode!+input AttributeFilterInput @doc(category: "Attributes") {+ valueRequired: Boolean+ isVariantOnly: Boolean+ visibleInStorefront: Boolean+ filterableInStorefront: Boolean+ filterableInDashboard: Boolean+ availableInGrid: Boolean+ metadata: [MetadataFilter!]+ search: String+ ids: [ID!]+ type: AttributeTypeEnum+ inCollection: ID+ inCategory: ID+ slugs: [String!]- """List of available shipping methods."""- shippingMethods: [ShippingMethod!]+ """Specifies the channel by which the data should be filtered."""+ channel: String @deprecated(reason: "Use root-level channel argument instead.")+}++enum AttributeTypeEnum @doc(category: "Attributes") {+ PRODUCT_TYPE+ PAGE_TYPE+ CUSTOMER_TYPE+}++"""Where filtering options."""+input AttributeWhereInput @doc(category: "Attributes") {+ metadata: [MetadataFilter!]+ ids: [ID!]+ name: StringFilterInput+ slug: StringFilterInput+ withChoices: Boolean+ inputType: AttributeInputTypeEnumFilterInput+ entityType: AttributeEntityTypeEnumFilterInput+ type: AttributeTypeEnumFilterInput+ unit: MeasurementUnitsEnumFilterInput+ inCollection: ID+ inCategory: ID+ valueRequired: Boolean+ visibleInStorefront: Boolean+ filterableInDashboard: Boolean++ """List of conditions that must be met."""+ AND: [AttributeWhereInput!]++ """A list of conditions of which at least one must be met."""+ OR: [AttributeWhereInput!]+}++input AttributeInputTypeEnumFilterInput @doc(category: "Attributes") {+ """The value equal to."""+ eq: AttributeInputTypeEnum++ """The value included in."""+ oneOf: [AttributeInputTypeEnum!]+}++input AttributeEntityTypeEnumFilterInput @doc(category: "Attributes") {+ """The value equal to."""+ eq: AttributeEntityTypeEnum++ """The value included in."""+ oneOf: [AttributeEntityTypeEnum!]+}++input AttributeTypeEnumFilterInput @doc(category: "Attributes") {+ """The value equal to."""+ eq: AttributeTypeEnum++ """The value included in."""+ oneOf: [AttributeTypeEnum!]+}++input MeasurementUnitsEnumFilterInput @doc(category: "Attributes") {+ """The value equal to."""+ eq: MeasurementUnitsEnum++ """The value included in."""+ oneOf: [MeasurementUnitsEnum!]+}++enum MeasurementUnitsEnum {+ MM+ CM+ DM+ M+ KM+ FT+ YD+ INCH+ SQ_MM+ SQ_CM+ SQ_DM+ SQ_M+ SQ_KM+ SQ_FT+ SQ_YD+ SQ_INCH+ CUBIC_MILLIMETER+ CUBIC_CENTIMETER+ CUBIC_DECIMETER+ CUBIC_METER+ LITER+ CUBIC_FOOT+ CUBIC_INCH+ CUBIC_YARD+ QT+ PINT+ FL_OZ+ ACRE_IN+ ACRE_FT+ G+ LB+ OZ+ KG+ TONNE}"""-Shipping methods that can be used as means of shipping for orders and checkouts.+Represents a type of page. It defines what attributes are available to pages of this type."""-type ShippingMethod implements Node & ObjectWithMetadata @doc(category: "Shipping") {- """Unique ID of ShippingMethod available for Order."""+type PageType implements Node & ObjectWithMetadata @doc(category: "Pages") {+ """ID of the page type."""id: ID!"""List of private metadata items. Requires staff permissions to access."""@@ -10508,225 +10588,127 @@ type ShippingMethod implements Node & ObjectWithMetadata @doc(category: "Shippin"""metafields(keys: [String!]): Metadata- """Type of the shipping method."""- type: ShippingMethodTypeEnum @deprecated-- """Shipping method name."""+ """Name of the page type."""name: String!- """- Shipping method description.-- Rich text format. For reference see https://editorjs.io/- """- description: JSONString-- """Maximum delivery days for this shipping method."""- maximumDeliveryDays: Int-- """Minimum delivery days for this shipping method."""- minimumDeliveryDays: Int-- """Maximum order weight for this shipping method."""- maximumOrderWeight: Weight @deprecated-- """Minimum order weight for this shipping method."""- minimumOrderWeight: Weight @deprecated-- """Returns translated shipping method fields for the given language code."""- translation(- """A language code to return the translation for shipping method."""- languageCode: LanguageCodeEnum!- ): ShippingMethodTranslation-- """The price of selected shipping method."""- price: Money!-- """Maximum order price for this shipping method."""- maximumOrderPrice: Money @deprecated-- """Minimal order price for this shipping method."""- minimumOrderPrice: Money @deprecated-- """Describes if this shipping method is active and can be selected."""- active: Boolean!+ """Slug of the page type."""+ slug: String!- """Message connected to this shipping method."""- message: String-}+ """Page attributes of that page type."""+ attributes: [Attribute!]-"""Represents the channel stock settings."""-type StockSettings @doc(category: "Products") {"""- Allocation strategy defines the preference of warehouses for allocations and reservations.+ Attributes that can be assigned to the page type.++ Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES."""- allocationStrategy: AllocationStrategyEnum!-}--"""-Determine the allocation strategy for the channel.-- PRIORITIZE_SORTING_ORDER - allocate stocks according to the warehouses' order- within the channel-- PRIORITIZE_HIGH_STOCK - allocate stock in a warehouse with the most stock-"""-enum AllocationStrategyEnum @doc(category: "Products") {- PRIORITIZE_SORTING_ORDER- PRIORITIZE_HIGH_STOCK-}+ availableAttributes(+ """Filtering options for attributes."""+ filter: AttributeFilterInput @deprecated(reason: "Use `where` filter instead.")-"""Represents the channel-specific order settings."""-type OrderSettings {- """- When disabled, all new orders from checkout will be marked as unconfirmed. When enabled orders from checkout will become unfulfilled immediately.- """- automaticallyConfirmAllNewOrders: Boolean!+ """Where filtering options for attributes."""+ where: AttributeWhereInput- """- When enabled, all non-shippable gift card orders will be fulfilled automatically.- """- automaticallyFulfillNonShippableGiftCard: Boolean!+ """Search attributes."""+ search: String- """- Expiration time in minutes. Default null - means do not expire any orders.- """- expireOrdersAfter: Minute+ """Return the elements in the list that come before the specified cursor."""+ before: String- """- Determine what strategy will be used to mark the order as paid. Based on the chosen option, the proper object will be created and attached to the order when it's manually marked as paid.- `PAYMENT_FLOW` - [default option] creates the `Payment` object.- `TRANSACTION_FLOW` - creates the `TransactionItem` object.- """- markAsPaidStrategy: MarkAsPaidStrategyEnum!+ """Return the elements in the list that come after the specified cursor."""+ after: String- """The time in days after expired orders will be deleted."""- deleteExpiredOrdersAfter: Day!+ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int- """- Determine if it is possible to place unpaid order by calling `checkoutComplete` mutation.- """- allowUnpaidOrders: Boolean!+ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): AttributeCountableConnection"""- Determine if voucher applied on draft order should be count toward voucher usage.+ Whether page type has pages assigned.- Note: this API is currently in Feature Preview and can be subject to changes at later point.+ Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES."""- includeDraftOrderInVoucherUsage: Boolean!+ hasPages: Boolean+}- """- Time in hours after which the draft order line price will be refreshed.-- Note: this API is currently in Feature Preview and can be subject to changes at later point.- """- draftOrderLinePriceFreezePeriod: Hour+type AttributeValueCountableConnection @doc(category: "Attributes") {+ """Pagination data for this connection."""+ pageInfo: PageInfo!+ edges: [AttributeValueCountableEdge!]!- """- This flag only affects orders created from checkout and applies specifically to vouchers of the types: `SPECIFIC_PRODUCT` and `ENTIRE_ORDER` with `applyOncePerOrder` enabled.- - When legacy propagation is enabled, discounts from these vouchers are represented as `OrderDiscount` objects, attached to the order and returned in the `Order.discounts` field. Additionally, percentage-based vouchers are converted to fixed-value discounts.- - When legacy propagation is disabled, discounts are represented as `OrderLineDiscount` objects, attached to individual lines and returned in the `OrderLine.discounts` field. In this case, percentage-based vouchers retain their original type.- In future releases, `OrderLineDiscount` will become the default behavior, and this flag will be deprecated and removed.- """- useLegacyLineDiscountPropagation: Boolean!+ """A total count of items in the collection."""+ totalCount: Int}-"""-The `Minute` scalar type represents number of minutes by integer value.-"""-scalar Minute+type AttributeValueCountableEdge @doc(category: "Attributes") {+ """The item at the end of the edge."""+ node: AttributeValue!-"""-Determine the mark as paid strategy for the channel.+ """A cursor for use in pagination."""+ cursor: String!+}- TRANSACTION_FLOW - new orders marked as paid will receive a- `TransactionItem` object, that will cover the `order.total`.+input AttributeChoicesSortingInput @doc(category: "Attributes") {+ """Specifies the direction in which to sort attribute choices."""+ direction: OrderDirection!- PAYMENT_FLOW - new orders marked as paid will receive a- `Payment` object, that will cover the `order.total`.-"""-enum MarkAsPaidStrategyEnum @doc(category: "Channels") {- TRANSACTION_FLOW- PAYMENT_FLOW @deprecated(reason: "The legacy Payments API is deprecated and will be removed. Use the Transactions API instead.")+ """Sort attribute choices by the selected field."""+ field: AttributeChoicesSortField!}-"""The `Day` scalar type represents number of days by integer value."""-scalar Day--"""The `Hour` scalar type represents number of hours by integer value."""-scalar Hour+enum AttributeChoicesSortField @doc(category: "Attributes") {+ """Sort attribute choice by name."""+ NAME-"""Represents the channel-specific checkout settings."""-type CheckoutSettings {- """- Default `true`. Determines if the checkout mutations should use legacy error flow. In legacy flow, all mutations can raise an exception unrelated to the requested action - (e.g. out-of-stock exception when updating checkoutShippingAddress.) If `false`, the errors will be aggregated in `checkout.problems` field. Some of the `problems` can block the finalizing checkout process. The legacy flow will be removed in Saleor 4.0. The flow with `checkout.problems` will be the default one.- """- useLegacyErrorFlow: Boolean!+ """Sort attribute choice by slug."""+ SLUG+}- """- Default `false`. Determines if the paid checkouts should be automatically completed. This setting applies only to checkouts where payment was processed through transactions.When enabled, the checkout will be automatically completed once the checkout `charge_status` reaches `FULL`. This occurs when the total sum of charged and authorized transaction amounts equals or exceeds the checkout's total amount.- """- automaticallyCompleteFullyPaidCheckouts: Boolean!+input AttributeValueFilterInput @doc(category: "Attributes") {+ search: String+ ids: [ID!]+ slugs: [String!]+}- """- The time in minutes to wait after a checkout is fully paid before automatically completing it.-- Added in Saleor 3.22.- """- automaticCompletionDelay: Minute+"""Where filtering options for attribute values."""+input AttributeValueWhereInput @doc(category: "Attributes") {+ ids: [ID!]+ name: StringFilterInput+ slug: StringFilterInput- """- The date time defines the earliest checkout creation date on which fully paid checkouts can begin to be automatically completed.-- Added in Saleor 3.22.- """- automaticCompletionCutOffDate: DateTime+ """List of conditions that must be met."""+ AND: [AttributeValueWhereInput!]- """- Default to `true`. Determines whether gift cards can be attached to a Checkout via `addPromoCode` mutation. Usage of this mutation with gift cards is deprecated.-- Added in Saleor 3.23.- """- allowLegacyGiftCardUse: Boolean!+ """A list of conditions of which at least one must be met."""+ OR: [AttributeValueWhereInput!]}-"""Represents the channel-specific payment settings."""-type PaymentSettings {- """- Determine the transaction flow strategy to be used. Include the selected option in the payload sent to the payment app, as a requested action for the transaction.- """- defaultTransactionFlowStrategy: TransactionFlowStrategyEnum!-- """- Determine if the funds for expired checkouts should be released automatically.- """- releaseFundsForExpiredCheckouts: Boolean-- """- The time in hours after which funds for expired checkouts will be released.- """- checkoutTtlBeforeReleasingFunds: Hour+type ProductTypeCountableConnection @doc(category: "Products") {+ """Pagination data for this connection."""+ pageInfo: PageInfo!+ edges: [ProductTypeCountableEdge!]!- """- Specifies the earliest date on which funds for expired checkouts can begin to be released. Expired checkouts dated before this cut-off will not have their funds released. Additionally, no funds will be released for checkouts that are more than one year old, regardless of the cut-off date.- """- checkoutReleaseFundsCutOffDate: DateTime+ """A total count of items in the collection."""+ totalCount: Int}-"""-Determine the transaction flow strategy.+type ProductTypeCountableEdge @doc(category: "Products") {+ """The item at the end of the edge."""+ node: ProductType!- AUTHORIZATION - the processed transaction should be only authorized- CHARGE - the processed transaction should be charged.-"""-enum TransactionFlowStrategyEnum @doc(category: "Payments") {- AUTHORIZATION- CHARGE+ """A cursor for use in pagination."""+ cursor: String!}-"""Channel-specific tax configuration."""-type TaxConfiguration implements Node & ObjectWithMetadata @doc(category: "Taxes") {- """The ID of the object."""+"""Checkout object."""+type Checkout implements Node & ObjectWithMetadata @doc(category: "Checkout") {+ """The ID of the checkout."""id: ID!"""List of private metadata items. Requires staff permissions to access."""@@ -10759,69 +10741,204 @@ type TaxConfiguration implements Node & ObjectWithMetadata @doc(category: "Taxes"""metafields(keys: [String!]): Metadata- """A channel to which the tax configuration applies to."""+ """The date and time when the checkout was created."""+ created: DateTime!++ """Time of last modification of the given checkout."""+ updatedAt: DateTime!+ lastChange: DateTime! @deprecated(reason: "Use `updatedAt` instead.")++ """+ The user assigned to the checkout. Requires one of the following permissions: MANAGE_USERS, HANDLE_PAYMENTS, OWNER.+ """+ user: User++ """The channel for which checkout was created."""channel: Channel!- """Determines whether taxes are charged in the given channel."""- chargeTaxes: Boolean!+ """The billing address of the checkout."""+ billingAddress: Address++ """The shipping address of the checkout."""+ shippingAddress: Address++ """The customer note for the checkout."""+ customerNote: String!"""- The default strategy to use for tax calculation in the given channel. Taxes can be calculated either using user-defined flat rates or with a tax app. Empty value means that no method is selected and taxes are not calculated.+ The total discount applied to the checkout. Note: Only discount created via voucher are included in this field."""- taxCalculationStrategy: TaxCalculationStrategy+ discount: Money- """Determines whether displayed prices should include taxes."""- displayGrossPrices: Boolean!+ """The name of voucher assigned to the checkout."""+ discountName: String- """Determines whether prices are entered with the tax included."""- pricesEnteredWithTax: Boolean!+ """+ Translation of the discountName field in the language set in Checkout.languageCode field.Note: this field is set automatically when Checkout.languageCode is defined; otherwise it's null+ """+ translatedDiscountName: String- """List of country-specific exceptions in tax configuration."""- countries: [TaxConfigurationPerCountry!]!+ """+ The voucher assigned to the checkout.++ Requires one of the following permissions: MANAGE_DISCOUNTS.+ """+ voucher: Voucher++ """The code of voucher assigned to the checkout."""+ voucherCode: String"""- The tax app `App.identifier` that will be used to calculate the taxes for the given channel. Empty value for `TAX_APP` set as `taxCalculationStrategy` means that Saleor will iterate over all installed tax apps. If multiple tax apps exist with provided tax app id use the `App` with newest `created` date. Will become mandatory in 4.0 for `TAX_APP` `taxCalculationStrategy`.+ Shipping methods that can be used with this checkout.++ Triggers the following webhook events:+ - SHIPPING_LIST_METHODS_FOR_CHECKOUT (sync): Optionally triggered when cached external shipping methods are invalid.+ - CHECKOUT_FILTER_SHIPPING_METHODS (sync): Optionally triggered when cached filtered shipping methods are invalid."""- taxAppId: String+ availableShippingMethods: [ShippingMethod!]! @webhookEventsInfo(asyncEvents: [], syncEvents: [SHIPPING_LIST_METHODS_FOR_CHECKOUT, CHECKOUT_FILTER_SHIPPING_METHODS]) @deprecated(reason: "Use `shippingMethods` instead.")"""- Determines whether to use weighted tax for shipping. When set to true, the tax rate for shipping will be calculated based on the weighted average of tax rates from the order or checkout lines.+ Shipping methods that can be used with this checkout.++ Triggers the following webhook events:+ - SHIPPING_LIST_METHODS_FOR_CHECKOUT (sync): Optionally triggered when cached external shipping methods are invalid.+ - CHECKOUT_FILTER_SHIPPING_METHODS (sync): Optionally triggered when cached filtered shipping methods are invalid."""- useWeightedTaxForShipping: Boolean-}+ shippingMethods: [ShippingMethod!]! @webhookEventsInfo(asyncEvents: [], syncEvents: [SHIPPING_LIST_METHODS_FOR_CHECKOUT, CHECKOUT_FILTER_SHIPPING_METHODS])-enum TaxCalculationStrategy @doc(category: "Taxes") {- FLAT_RATES- TAX_APP-}+ """Collection points that can be used for this order."""+ availableCollectionPoints: [Warehouse!]!-"""Country-specific exceptions of a channel's tax configuration."""-type TaxConfigurationPerCountry @doc(category: "Taxes") {- """Country in which this configuration applies."""- country: CountryDisplay!+ """+ List of available payment gateways.++ Triggers the following webhook events:+ - PAYMENT_LIST_GATEWAYS (sync): Fetch payment gateways available for checkout.+ """+ availablePaymentGateways: [PaymentGateway!]! @webhookEventsInfo(asyncEvents: [], syncEvents: [PAYMENT_LIST_GATEWAYS]) @deprecated(reason: "The legacy Payments API is deprecated and will be removed. Use the Transactions API instead.")- """Determines whether taxes are charged in this country."""- chargeTaxes: Boolean!+ """Email of a customer."""+ email: String++ """List of gift cards associated with this checkout."""+ giftCards: [GiftCard!]!++ """Returns True, if checkout requires shipping."""+ isShippingRequired: Boolean!++ """The number of items purchased."""+ quantity: Int!"""- A country-specific strategy to use for tax calculation. Taxes can be calculated either using user-defined flat rates or with a tax app. If not provided, use the value from the channel's tax configuration.+ Date when oldest stock reservation for this checkout expires or null if no stock is reserved."""- taxCalculationStrategy: TaxCalculationStrategy+ stockReservationExpires: DateTime"""- Determines whether displayed prices should include taxes for this country.+ A list of checkout lines, each containing information about an item in the checkout.+ """+ lines: [CheckoutLine!]!++ """+ The price of the shipping, with all the taxes included. Set to 0 when no delivery method is selected.++ Triggers the following webhook events:+ - CHECKOUT_CALCULATE_TAXES (sync): Optionally triggered when checkout prices are expired.+ """+ shippingPrice: TaxedMoney! @webhookEventsInfo(asyncEvents: [], syncEvents: [CHECKOUT_CALCULATE_TAXES])++ """+ The delivery method selected for this checkout.++ Added in Saleor 3.23.+ """+ delivery: Delivery++ """+ The shipping method related with checkout.++ Triggers the following webhook events:+ - SHIPPING_LIST_METHODS_FOR_CHECKOUT (sync): Optionally triggered when cached external shipping methods are invalid.+ - CHECKOUT_FILTER_SHIPPING_METHODS (sync): Optionally triggered when cached filtered shipping methods are invalid.+ """+ shippingMethod: ShippingMethod @webhookEventsInfo(asyncEvents: [], syncEvents: [SHIPPING_LIST_METHODS_FOR_CHECKOUT, CHECKOUT_FILTER_SHIPPING_METHODS]) @deprecated(reason: "Use `delivery` instead.")++ """+ The delivery method selected for this checkout.++ Triggers the following webhook events:+ - SHIPPING_LIST_METHODS_FOR_CHECKOUT (sync): Optionally triggered when cached external shipping methods are invalid.+ - CHECKOUT_FILTER_SHIPPING_METHODS (sync): Optionally triggered when cached filtered shipping methods are invalid.+ """+ deliveryMethod: DeliveryMethod @webhookEventsInfo(asyncEvents: [], syncEvents: [SHIPPING_LIST_METHODS_FOR_CHECKOUT, CHECKOUT_FILTER_SHIPPING_METHODS]) @deprecated(reason: "Use `delivery` instead.")++ """+ The price of the checkout before shipping, with taxes included.++ Triggers the following webhook events:+ - CHECKOUT_CALCULATE_TAXES (sync): Optionally triggered when checkout prices are expired.+ """+ subtotalPrice: TaxedMoney! @webhookEventsInfo(asyncEvents: [], syncEvents: [CHECKOUT_CALCULATE_TAXES])++ """Returns True if checkout has to be exempt from taxes."""+ taxExemption: Boolean!++ """The checkout's token."""+ token: UUID!++ """+ The sum of the checkout line prices, with all the taxes,shipping costs, and discounts included.++ Triggers the following webhook events:+ - CHECKOUT_CALCULATE_TAXES (sync): Optionally triggered when checkout prices are expired."""+ totalPrice: TaxedMoney! @webhookEventsInfo(asyncEvents: [], syncEvents: [CHECKOUT_CALCULATE_TAXES])++ """+ The difference between the paid and the checkout total amount.++ Triggers the following webhook events:+ - CHECKOUT_CALCULATE_TAXES (sync): Optionally triggered when checkout prices are expired.+ """+ totalBalance: Money! @webhookEventsInfo(asyncEvents: [], syncEvents: [CHECKOUT_CALCULATE_TAXES])++ """Checkout language code."""+ languageCode: LanguageCodeEnum!++ """+ List of transactions for the checkout. Requires one of the following permissions: MANAGE_CHECKOUTS, HANDLE_PAYMENTS.+ """+ transactions: [TransactionItem!]++ """Determines whether displayed prices should include taxes."""displayGrossPrices: Boolean!"""- The tax app `App.identifier` that will be used to calculate the taxes for the given channel and country. If not provided, use the value from the channel's tax configuration.+ The authorize status of the checkout.++ Triggers the following webhook events:+ - CHECKOUT_CALCULATE_TAXES (sync): Optionally triggered when checkout prices are expired."""- taxAppId: String+ authorizeStatus: CheckoutAuthorizeStatusEnum! @webhookEventsInfo(asyncEvents: [], syncEvents: [CHECKOUT_CALCULATE_TAXES])"""- Determines whether to use weighted tax for shipping. When set to true, the tax rate for shipping will be calculated based on the weighted average of tax rates from the order or checkout lines.+ The charge status of the checkout.++ Triggers the following webhook events:+ - CHECKOUT_CALCULATE_TAXES (sync): Optionally triggered when checkout prices are expired."""- useWeightedTaxForShipping: Boolean+ chargeStatus: CheckoutChargeStatusEnum! @webhookEventsInfo(asyncEvents: [], syncEvents: [CHECKOUT_CALCULATE_TAXES])++ """+ List of user's stored payment methods that can be used in this checkout session. It uses the channel that the checkout was created in. When `amount` is not provided, `checkout.total` will be used as a default value.+ """+ storedPaymentMethods(+ """Amount that will be used to fetch stored payment methods."""+ amount: PositiveDecimal+ ): [StoredPaymentMethod!]++ """List of problems with the checkout."""+ problems: [CheckoutProblem!]}"""@@ -13887,6 +14004,91 @@ type PaymentSource @doc(category: "Payments") {metadata: [MetadataItem!]!}+"""+Represents a type of customer. It allows to segment users and defines what attributes are available to users of this type.++Added in Saleor 3.23.+"""+type CustomerType implements Node & ObjectWithMetadata @doc(category: "Users") {+ """The ID of the customer type."""+ id: ID!++ """List of private metadata items. Requires staff permissions to access."""+ privateMetadata: [MetadataItem!]!++ """+ A single key from private metadata. Requires staff permissions to access.++ Tip: Use GraphQL aliases to fetch multiple keys.+ """+ privateMetafield(key: String!): String++ """+ Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.+ """+ privateMetafields(keys: [String!]): Metadata++ """List of public metadata items. Can be accessed without permissions."""+ metadata: [MetadataItem!]!++ """+ A single key from public metadata.++ Tip: Use GraphQL aliases to fetch multiple keys.+ """+ metafield(key: String!): String++ """+ Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.+ """+ metafields(keys: [String!]): Metadata++ """Name of the customer type."""+ name: String!++ """Slug of the customer type."""+ slug: String!++ """+ Whether this is the default customer type. The default customer type is assigned to every newly created user and cannot be deleted.+ """+ isDefault: Boolean!++ """+ Customer attributes assigned to this customer type. Attributes that are not visible in the storefront require one of the following permissions to be included: MANAGE_USERS, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.+ """+ attributes: [Attribute!]++ """+ Customer attributes that can be assigned to the customer type.++ Requires one of the following permissions: MANAGE_USERS, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.+ """+ availableAttributes(+ """Where filtering options for attributes."""+ where: AttributeWhereInput++ """Search attributes."""+ search: String++ """Return the elements in the list that come before the specified cursor."""+ before: String++ """Return the elements in the list that come after the specified cursor."""+ after: String++ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int++ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): AttributeCountableConnection+}+"""Represents the app's brand data."""type AppBrand @doc(category: "Apps") {"""App's logos details."""@@ -14153,6 +14355,9 @@ enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {CUSTOMER_UPDATEDCUSTOMER_DELETEDCUSTOMER_METADATA_UPDATED+ CUSTOMER_TYPE_CREATED+ CUSTOMER_TYPE_UPDATED+ CUSTOMER_TYPE_DELETEDCOLLECTION_CREATEDCOLLECTION_UPDATEDCOLLECTION_DELETED@@ -17401,6 +17606,20 @@ input CustomerWhereInput @doc(category: "Users") {"""Filter by number of orders placed by the user."""numberOfOrders: IntFilterInput+ """+ Filter by customer type. Filtering by the default customer type also matches users without an explicitly assigned customer type.++ Added in Saleor 3.23.+ """+ customerType: GlobalIDFilterInput++ """+ Filter by attributes associated with the customer.++ Added in Saleor 3.23.+ """+ attributes: [AssignedAttributeWhereInput!]+"""List of conditions that must be met."""AND: [CustomerWhereInput!]@@ -17441,6 +17660,60 @@ enum UserSortField @doc(category: "Users") {RANK}+type CustomerTypeCountableConnection @doc(category: "Users") {+ """Pagination data for this connection."""+ pageInfo: PageInfo!+ edges: [CustomerTypeCountableEdge!]!++ """A total count of items in the collection."""+ totalCount: Int+}++type CustomerTypeCountableEdge @doc(category: "Users") {+ """The item at the end of the edge."""+ node: CustomerType!++ """A cursor for use in pagination."""+ cursor: String!+}++input CustomerTypeWhereInput @doc(category: "Users") {+ """Filter by metadata fields."""+ metadata: MetadataFilterInput+ ids: [ID!]++ """Filter by customer type name."""+ name: StringFilterInput++ """Filter by customer type slug."""+ slug: StringFilterInput++ """Filter by whether the customer type is the default one."""+ isDefault: Boolean++ """List of conditions that must be met."""+ AND: [CustomerTypeWhereInput!]++ """A list of conditions of which at least one must be met."""+ OR: [CustomerTypeWhereInput!]+}++input CustomerTypeSortingInput @doc(category: "Users") {+ """Specifies the direction in which to sort customer types."""+ direction: OrderDirection!++ """Sort customer types by the selected field."""+ field: CustomerTypeSortField!+}++enum CustomerTypeSortField @doc(category: "Users") {+ """Sort customer types by name."""+ NAME++ """Sort customer types by slug."""+ SLUG+}+type GroupCountableConnection @doc(category: "Users") {"""Pagination data for this connection."""pageInfo: PageInfo!@@ -21260,7 +21533,7 @@ type Mutation {"""Deletes an attribute.- Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+ Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_DELETED (async): An attribute was deleted.@@ -21276,7 +21549,7 @@ type Mutation {"""Updates attribute.- Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+ Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_UPDATED (async): An attribute was updated.@@ -21354,7 +21627,7 @@ type Mutation {"""Deletes attributes.- Requires one of the following permissions, depending on the type of each attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+ Requires one of the following permissions, depending on the type of each attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_DELETED (async): An attribute was deleted.@@ -21369,7 +21642,7 @@ type Mutation {"""Deletes values of attributes.- Requires one of the following permissions, depending on the type of each value's attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+ Requires one of the following permissions, depending on the type of each value's attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_VALUE_DELETED (async): An attribute value was deleted.@@ -21385,7 +21658,7 @@ type Mutation {"""Creates a value for an attribute.- Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+ Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_VALUE_CREATED (async): An attribute value was created.@@ -21402,7 +21675,7 @@ type Mutation {"""Deletes a value of an attribute.- Requires one of the following permissions, depending on the type of the value's attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+ Requires one of the following permissions, depending on the type of the value's attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_VALUE_DELETED (async): An attribute value was deleted.@@ -21419,7 +21692,7 @@ type Mutation {"""Updates value of an attribute.- Requires one of the following permissions, depending on the type of the value's attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+ Requires one of the following permissions, depending on the type of the value's attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_VALUE_UPDATED (async): An attribute value was updated.@@ -21468,7 +21741,7 @@ type Mutation {"""Reorder the values of an attribute.- Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+ Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_VALUE_UPDATED (async): An attribute value was updated.@@ -22151,6 +22424,110 @@ type Mutation {errorPolicy: ErrorPolicyEnum): CustomerBulkUpdate @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_UPDATED, CUSTOMER_METADATA_UPDATED], syncEvents: [])+ """+ Creates a new customer type.++ Added in Saleor 3.23.++ Requires one of the following permissions: MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.++ Triggers the following webhook events:+ - CUSTOMER_TYPE_CREATED (async): A new customer type was created.+ """+ customerTypeCreate(+ """Fields required to create a customer type."""+ input: CustomerTypeCreateInput!+ ): CustomerTypeCreate @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_TYPE_CREATED], syncEvents: [])++ """+ Updates a customer type.++ Added in Saleor 3.23.++ Requires one of the following permissions: MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.++ Triggers the following webhook events:+ - CUSTOMER_TYPE_UPDATED (async): A customer type was updated.+ """+ customerTypeUpdate(+ """ID of the customer type to update."""+ id: ID!++ """Fields required to update a customer type."""+ input: CustomerTypeUpdateInput!+ ): CustomerTypeUpdate @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_TYPE_UPDATED], syncEvents: [])++ """+ Deletes a customer type. Users of the deleted customer type are reassigned to the default customer type.++ Added in Saleor 3.23.++ Requires one of the following permissions: MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.++ Triggers the following webhook events:+ - CUSTOMER_TYPE_DELETED (async): A customer type was deleted.+ """+ customerTypeDelete(+ """ID of the customer type to delete."""+ id: ID!+ ): CustomerTypeDelete @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_TYPE_DELETED], syncEvents: [])++ """+ Assign attributes to a given customer type.++ Added in Saleor 3.23.++ Requires one of the following permissions: MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.++ Triggers the following webhook events:+ - CUSTOMER_TYPE_UPDATED (async): A customer type was updated.+ """+ customerTypeAssignAttributes(+ """The IDs of the attributes to assign. Maximum of 100 items."""+ attributeIds: [ID!]!++ """ID of the customer type to assign the attributes to."""+ customerTypeId: ID!+ ): CustomerTypeAssignAttributes @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_TYPE_UPDATED], syncEvents: [])++ """+ Unassign attributes from a given customer type. Values already assigned to users are kept in the database, but are hidden until the attribute is assigned to the user's customer type again.++ Added in Saleor 3.23.++ Requires one of the following permissions: MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.++ Triggers the following webhook events:+ - CUSTOMER_TYPE_UPDATED (async): A customer type was updated.+ """+ customerTypeUnassignAttributes(+ """The IDs of the attributes to unassign. Maximum of 100 items."""+ attributeIds: [ID!]!++ """+ ID of the customer type from which the attributes should be unassigned.+ """+ customerTypeId: ID!+ ): CustomerTypeUnassignAttributes @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_TYPE_UPDATED], syncEvents: [])++ """+ Reorder the attributes of a customer type.++ Added in Saleor 3.23.++ Requires one of the following permissions: MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.++ Triggers the following webhook events:+ - CUSTOMER_TYPE_UPDATED (async): A customer type was updated.+ """+ customerTypeReorderAttributes(+ """ID of a customer type."""+ customerTypeId: ID!++ """The list of attribute reordering operations."""+ moves: [ReorderInput!]!+ ): CustomerTypeReorderAttributes @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_TYPE_UPDATED], syncEvents: [])+"""Creates a new staff user. Apps are not allowed to perform this mutation.@@ -31712,7 +32089,7 @@ input AttributeValueCreateInput @doc(category: "Attributes") {"""Deletes an attribute.-Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_DELETED (async): An attribute was deleted.@@ -31726,7 +32103,7 @@ type AttributeDelete @doc(category: "Attributes") @webhookEventsInfo(asyncEvents"""Updates attribute.-Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_UPDATED (async): An attribute was updated.@@ -32005,7 +32382,7 @@ input AttributeBulkTranslateInput @doc(category: "Attributes") {"""Deletes attributes.-Requires one of the following permissions, depending on the type of each attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+Requires one of the following permissions, depending on the type of each attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_DELETED (async): An attribute was deleted.@@ -32020,7 +32397,7 @@ type AttributeBulkDelete @doc(category: "Attributes") @webhookEventsInfo(asyncEv"""Deletes values of attributes.-Requires one of the following permissions, depending on the type of each value's attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+Requires one of the following permissions, depending on the type of each value's attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_VALUE_DELETED (async): An attribute value was deleted.@@ -32036,7 +32413,7 @@ type AttributeValueBulkDelete @doc(category: "Attributes") @webhookEventsInfo(as"""Creates a value for an attribute.-Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_VALUE_CREATED (async): An attribute value was created.@@ -32053,7 +32430,7 @@ type AttributeValueCreate @doc(category: "Attributes") @webhookEventsInfo(asyncE"""Deletes a value of an attribute.-Requires one of the following permissions, depending on the type of the value's attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+Requires one of the following permissions, depending on the type of the value's attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_VALUE_DELETED (async): An attribute value was deleted.@@ -32070,7 +32447,7 @@ type AttributeValueDelete @doc(category: "Attributes") @webhookEventsInfo(asyncE"""Updates value of an attribute.-Requires one of the following permissions, depending on the type of the value's attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+Requires one of the following permissions, depending on the type of the value's attribute: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_VALUE_UPDATED (async): An attribute value was updated.@@ -32168,7 +32545,7 @@ type AttributeValueTranslate @doc(category: "Attributes") {"""Reorder the values of an attribute.-Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes.+Requires one of the following permissions, depending on the attribute type: MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES for `PRODUCT_TYPE` attributes, MANAGE_PAGE_TYPES_AND_ATTRIBUTES for `PAGE_TYPE` attributes, MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES for `CUSTOMER_TYPE` attributes.Triggers the following webhook events:- ATTRIBUTE_VALUE_UPDATED (async): An attribute value was updated.@@ -32714,6 +33091,13 @@ type AccountError @doc(category: "Users") {"""A type of address that causes the error."""addressType: AddressTypeEnum++ """+ List of attributes IDs which causes the error.++ Added in Saleor 3.23.+ """+ attributes: [ID!]}enum AccountErrorCode @doc(category: "Users") {@@ -33293,6 +33677,20 @@ input UserCreateInput @doc(category: "Users") {"""User account is confirmed."""isConfirmed: Boolean @deprecated(reason: "The user will be always set as unconfirmed. The confirmation will take place when the user sets the password.")+ """+ ID of the customer type to assign to the user. If not provided when creating a customer, the default customer type is assigned.++ Added in Saleor 3.23.+ """+ customerType: ID++ """+ List of attribute values to assign to the user. The attributes must belong to the customer type the user ends up with.++ Added in Saleor 3.23.+ """+ attributes: [AttributeValueInput!]+"""URL of a view where users should be redirected to set the password. URL in RFC 1808 format."""@@ -33363,6 +33761,20 @@ input CustomerInput @doc(category: "Users") {"""User account is confirmed."""isConfirmed: Boolean++ """+ ID of the customer type to assign to the user. If not provided when creating a customer, the default customer type is assigned.++ Added in Saleor 3.23.+ """+ customerType: ID++ """+ List of attribute values to assign to the user. The attributes must belong to the customer type the user ends up with.++ Added in Saleor 3.23.+ """+ attributes: [AttributeValueInput!]}"""@@ -33431,6 +33843,13 @@ type CustomerBulkUpdateError @doc(category: "Users") {"""The error code."""code: CustomerBulkUpdateErrorCode!++ """+ List of attributes IDs which causes the error.++ Added in Saleor 3.23.+ """+ attributes: [ID!]}enum CustomerBulkUpdateErrorCode @doc(category: "Users") {@@ -33455,6 +33874,256 @@ input CustomerBulkUpdateInput @doc(category: "Users") {input: CustomerInput!}+"""+Creates a new customer type.++Added in Saleor 3.23.++Requires one of the following permissions: MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.++Triggers the following webhook events:+- CUSTOMER_TYPE_CREATED (async): A new customer type was created.+"""+type CustomerTypeCreate @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_TYPE_CREATED], syncEvents: []) {+ errors: [CustomerTypeCreateError!]!+ customerType: CustomerType+}++type CustomerTypeCreateError @doc(category: "Users") {+ """+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.+ """+ field: String++ """The error message."""+ message: String++ """The error code."""+ code: CustomerTypeCreateErrorCode!+}++enum CustomerTypeCreateErrorCode @doc(category: "Users") {+ GRAPHQL_ERROR+ INVALID+ NOT_FOUND+ REQUIRED+ UNIQUE+}++input CustomerTypeCreateInput @doc(category: "Users") {+ """Name of the customer type."""+ name: String++ """+ Slug of the customer type. If not provided, it will be generated from the name.+ """+ slug: String++ """+ Determines if the customer type should become the default one, assigned to every newly created user. Passing `true` clears the flag on the current default customer type - exactly one default customer type always exists.+ """+ isDefault: Boolean+}++"""+Updates a customer type.++Added in Saleor 3.23.++Requires one of the following permissions: MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.++Triggers the following webhook events:+- CUSTOMER_TYPE_UPDATED (async): A customer type was updated.+"""+type CustomerTypeUpdate @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_TYPE_UPDATED], syncEvents: []) {+ errors: [CustomerTypeUpdateError!]!+ customerType: CustomerType+}++type CustomerTypeUpdateError @doc(category: "Users") {+ """+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.+ """+ field: String++ """The error message."""+ message: String++ """The error code."""+ code: CustomerTypeUpdateErrorCode!+}++enum CustomerTypeUpdateErrorCode @doc(category: "Users") {+ CANNOT_UNSET_DEFAULT+ GRAPHQL_ERROR+ INVALID+ NOT_FOUND+ REQUIRED+ UNIQUE+}++input CustomerTypeUpdateInput @doc(category: "Users") {+ """Name of the customer type."""+ name: String++ """+ Slug of the customer type. If not provided, it will be generated from the name.+ """+ slug: String++ """+ Determines if the customer type should become the default one, assigned to every newly created user. Passing `true` clears the flag on the current default customer type - exactly one default customer type always exists.+ """+ isDefault: Boolean+}++"""+Deletes a customer type. Users of the deleted customer type are reassigned to the default customer type.++Added in Saleor 3.23.++Requires one of the following permissions: MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.++Triggers the following webhook events:+- CUSTOMER_TYPE_DELETED (async): A customer type was deleted.+"""+type CustomerTypeDelete @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_TYPE_DELETED], syncEvents: []) {+ errors: [CustomerTypeDeleteError!]!+ customerType: CustomerType+}++type CustomerTypeDeleteError @doc(category: "Users") {+ """+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.+ """+ field: String++ """The error message."""+ message: String++ """The error code."""+ code: CustomerTypeDeleteErrorCode!+}++enum CustomerTypeDeleteErrorCode @doc(category: "Users") {+ CANNOT_DELETE_DEFAULT+ GRAPHQL_ERROR+ INVALID+ NOT_FOUND+}++"""+Assign attributes to a given customer type.++Added in Saleor 3.23.++Requires one of the following permissions: MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.++Triggers the following webhook events:+- CUSTOMER_TYPE_UPDATED (async): A customer type was updated.+"""+type CustomerTypeAssignAttributes @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_TYPE_UPDATED], syncEvents: []) {+ """The updated customer type."""+ customerType: CustomerType+ errors: [CustomerTypeAssignAttributesError!]!+}++type CustomerTypeAssignAttributesError @doc(category: "Users") {+ """+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.+ """+ field: String++ """The error message."""+ message: String++ """The error code."""+ code: CustomerTypeAssignAttributesErrorCode!++ """List of attributes IDs which causes the error."""+ attributes: [ID!]+}++enum CustomerTypeAssignAttributesErrorCode @doc(category: "Users") {+ ATTRIBUTE_ALREADY_ASSIGNED+ GRAPHQL_ERROR+ INVALID+ NOT_FOUND+}++"""+Unassign attributes from a given customer type. Values already assigned to users are kept in the database, but are hidden until the attribute is assigned to the user's customer type again.++Added in Saleor 3.23.++Requires one of the following permissions: MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.++Triggers the following webhook events:+- CUSTOMER_TYPE_UPDATED (async): A customer type was updated.+"""+type CustomerTypeUnassignAttributes @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_TYPE_UPDATED], syncEvents: []) {+ """The updated customer type."""+ customerType: CustomerType+ errors: [CustomerTypeUnassignAttributesError!]!+}++type CustomerTypeUnassignAttributesError @doc(category: "Users") {+ """+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.+ """+ field: String++ """The error message."""+ message: String++ """The error code."""+ code: CustomerTypeUnassignAttributesErrorCode!+}++enum CustomerTypeUnassignAttributesErrorCode @doc(category: "Users") {+ GRAPHQL_ERROR+ INVALID+ NOT_FOUND+}++"""+Reorder the attributes of a customer type.++Added in Saleor 3.23.++Requires one of the following permissions: MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES.++Triggers the following webhook events:+- CUSTOMER_TYPE_UPDATED (async): A customer type was updated.+"""+type CustomerTypeReorderAttributes @doc(category: "Users") @webhookEventsInfo(asyncEvents: [CUSTOMER_TYPE_UPDATED], syncEvents: []) {+ """Customer type from which attributes are reordered."""+ customerType: CustomerType+ errors: [CustomerTypeReorderAttributesError!]!+}++type CustomerTypeReorderAttributesError @doc(category: "Users") {+ """+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.+ """+ field: String++ """The error message."""+ message: String++ """The error code."""+ code: CustomerTypeReorderAttributesErrorCode!++ """List of attributes IDs which causes the error."""+ attributes: [ID!]+}++enum CustomerTypeReorderAttributesErrorCode @doc(category: "Users") {+ GRAPHQL_ERROR+ INVALID+ NOT_FOUND+}+"""Creates a new staff user. Apps are not allowed to perform this mutation.@@ -33486,6 +34155,13 @@ type StaffError @doc(category: "Users") {"""A type of address that causes the error."""addressType: AddressTypeEnum+ """+ List of attributes IDs which causes the error.++ Added in Saleor 3.23.+ """+ attributes: [ID!]+"""List of permissions which causes the error."""permissions: [PermissionEnum!]@@ -36398,6 +37074,72 @@ type CustomerMetadataUpdated implements Event @doc(category: "Users") {user: User}+"""+Event sent when new customer type is created.++Added in Saleor 3.23.+"""+type CustomerTypeCreated implements Event @doc(category: "Users") {+ """Time of the event."""+ issuedAt: DateTime++ """Saleor version that triggered the event."""+ version: String++ """The user or application that triggered the event."""+ issuingPrincipal: IssuingPrincipal++ """The application receiving the webhook."""+ recipient: App++ """The customer type the event relates to."""+ customerType: CustomerType+}++"""+Event sent when customer type is updated.++Added in Saleor 3.23.+"""+type CustomerTypeUpdated implements Event @doc(category: "Users") {+ """Time of the event."""+ issuedAt: DateTime++ """Saleor version that triggered the event."""+ version: String++ """The user or application that triggered the event."""+ issuingPrincipal: IssuingPrincipal++ """The application receiving the webhook."""+ recipient: App++ """The customer type the event relates to."""+ customerType: CustomerType+}++"""+Event sent when customer type is deleted.++Added in Saleor 3.23.+"""+type CustomerTypeDeleted implements Event @doc(category: "Users") {+ """Time of the event."""+ issuedAt: DateTime++ """Saleor version that triggered the event."""+ version: String++ """The user or application that triggered the event."""+ issuingPrincipal: IssuingPrincipal++ """The application receiving the webhook."""+ recipient: App++ """The customer type the event relates to."""+ customerType: CustomerType+}+"""Event sent when new collection is created."""type CollectionCreated implements Event @doc(category: "Products") {"""Time of the event."""diff --git a/saleor/graphql/tests/queries/fragments.py b/saleor/graphql/tests/queries/fragments.pyindex ec78f59e81..3a31bede39 100644--- a/saleor/graphql/tests/queries/fragments.py+++ b/saleor/graphql/tests/queries/fragments.py@@ -361,6 +361,16 @@ fragment ProductTypeDetails on ProductType{"""+CUSTOMER_TYPE_DETAILS = """+fragment CustomerTypeDetails on CustomerType{+ id+ name+ slug+ isDefault+}+"""++PERMISSION_GROUP_DETAILS = """fragment PermissionGroupDetails on Group{namediff --git a/saleor/graphql/translations/mutations/attribute_value_bulk_translate.py b/saleor/graphql/translations/mutations/attribute_value_bulk_translate.pyindex ad4aa3532f..d8ee1f97d7 100644--- a/saleor/graphql/translations/mutations/attribute_value_bulk_translate.py+++ b/saleor/graphql/translations/mutations/attribute_value_bulk_translate.py@@ -1,8 +1,9 @@import graphenefrom django.core.exceptions import ValidationError+from django.db.models import prefetch_related_objectsfrom graphql.error import GraphQLError-from ....attribute import AttributeInputType, models+from ....attribute import AttributeInputType, AttributeType, modelsfrom ....core.editorjs import editorjs_to_textfrom ....core.utils.text import safe_truncatefrom ....permission.enums import SitePermissions@@ -132,6 +133,32 @@ class AttributeValueBulkTranslate(BaseBulkTranslateMutation):return cleaned_inputs_map+ @classmethod+ def get_base_objects(cls, cleaned_inputs_map: dict):+ base_objects = super().get_base_objects(cleaned_inputs_map)+ prefetch_related_objects(base_objects, "attribute")+ return base_objects++ @classmethod+ def find_base_object(cls, pk, external_ref, base_objects, index_error_map, index):+ base_object = super().find_base_object(+ pk, external_ref, base_objects, index_error_map, index+ )+ # Customer attribute values are excluded from the translations domain:+ # they may be created per user and carry customer data (PII), which+ # must not be rewritten as a translation and echoed back through the+ # TRANSLATION_CREATED/TRANSLATION_UPDATED webhooks.+ if base_object and base_object.attribute.type == AttributeType.CUSTOMER_TYPE:+ index_error_map[index].append(+ AttributeValueBulkTranslateError(+ message="Values of customer attributes cannot be translated.",+ code=AttributeValueTranslateErrorCode.INVALID.value,+ path="id" if pk else "externalReference",+ )+ )+ return None+ return base_object+@classmethoddef pre_update_or_create(cls, instance, input_data):if input_data.get("name") is None:diff --git a/saleor/graphql/translations/mutations/attribute_value_translate.py b/saleor/graphql/translations/mutations/attribute_value_translate.pyindex e32b322523..2c64deb432 100644--- a/saleor/graphql/translations/mutations/attribute_value_translate.py+++ b/saleor/graphql/translations/mutations/attribute_value_translate.py@@ -1,6 +1,7 @@import graphene+from django.core.exceptions import ValidationError-from ....attribute import AttributeInputType+from ....attribute import AttributeInputType, AttributeTypefrom ....attribute import models as attribute_modelsfrom ....core.editorjs import editorjs_to_textfrom ....core.utils.text import safe_truncate@@ -8,7 +9,7 @@ from ....permission.enums import SitePermissionsfrom ...attribute.types import AttributeValuefrom ...core.context import ChannelContextfrom ...core.descriptions import RICH_CONTENT-from ...core.enums import LanguageCodeEnum+from ...core.enums import LanguageCodeEnum, TranslationErrorCodefrom ...core.fields import JSONStringfrom ...core.types import TranslationErrorfrom .utils import BaseTranslateMutation, NameTranslationInput@@ -43,6 +44,19 @@ class AttributeValueTranslate(BaseTranslateMutation):@classmethoddef pre_update_or_create(cls, instance, input_data, language_code):+ # Customer attribute values are excluded from the translations domain:+ # they may be created per user and carry customer data (PII), which+ # must not be rewritten as a translation and echoed back through the+ # TRANSLATION_CREATED/TRANSLATION_UPDATED webhooks.+ if instance.attribute.type == AttributeType.CUSTOMER_TYPE:+ raise ValidationError(+ {+ "id": ValidationError(+ "Values of customer attributes cannot be translated.",+ code=TranslationErrorCode.INVALID.value,+ )+ }+ )if "name" not in input_data.keys() or input_data["name"] is None:if instance.attribute.input_type == AttributeInputType.RICH_TEXT:input_data["name"] = safe_truncate(diff --git a/saleor/graphql/translations/resolvers.py b/saleor/graphql/translations/resolvers.pyindex fcb24789e8..78c5fcd0e5 100644--- a/saleor/graphql/translations/resolvers.py+++ b/saleor/graphql/translations/resolvers.py@@ -1,3 +1,4 @@+from ...attribute import AttributeTypefrom ...attribute import models as attribute_modelsfrom ...discount import models as discount_modelsfrom ...menu import models as menu_models@@ -63,9 +64,16 @@ def resolve_shipping_methods(info):def resolve_attribute_values(info):- return attribute_models.AttributeValue.objects.using(- get_database_connection_name(info.context)- ).all()+ # Customer attribute values are excluded from the translations domain:+ # they may be created per user and carry customer data (PII) that+ # MANAGE_TRANSLATIONS holders must not be able to read.+ return (+ attribute_models.AttributeValue.objects.using(+ get_database_connection_name(info.context)+ )+ .exclude(attribute__type=AttributeType.CUSTOMER_TYPE)+ .all()+ )def resolve_products(info):diff --git a/saleor/graphql/translations/schema.py b/saleor/graphql/translations/schema.pyindex b832b45e3a..0a2f9a0c79 100644--- a/saleor/graphql/translations/schema.py+++ b/saleor/graphql/translations/schema.py@@ -1,5 +1,6 @@import graphene+from ...attribute import AttributeTypefrom ...attribute.models import Attribute, AttributeValuefrom ...discount.models import Promotion, PromotionRule, Voucherfrom ...menu.models import MenuItem@@ -152,7 +153,6 @@ class TranslationQueries(graphene.ObjectType):TranslatableKinds.COLLECTION.value: Collection, # type: ignore[attr-defined] # noqa: E501TranslatableKinds.CATEGORY.value: Category, # type: ignore[attr-defined]TranslatableKinds.ATTRIBUTE.value: Attribute, # type: ignore[attr-defined]- TranslatableKinds.ATTRIBUTE_VALUE.value: AttributeValue, # type: ignore[attr-defined] # noqa: E501TranslatableKinds.VARIANT.value: ProductVariant, # type: ignore[attr-defined] # noqa: E501TranslatableKinds.PAGE.value: Page, # type: ignore[attr-defined]TranslatableKinds.SHIPPING_METHOD.value: ShippingMethod, # type: ignore[attr-defined] # noqa: E501@@ -167,6 +167,16 @@ class TranslationQueries(graphene.ObjectType):.filter(old_sale_id=kind_id).first())+ if kind == TranslatableKinds.ATTRIBUTE_VALUE.value: # type: ignore[attr-defined]+ # Customer attribute values are excluded from the translations+ # domain: they may be created per user and carry customer data+ # (PII) that MANAGE_TRANSLATIONS holders must not be able to read.+ return (+ AttributeValue.objects.using(get_database_connection_name(info.context))+ .exclude(attribute__type=AttributeType.CUSTOMER_TYPE)+ .filter(pk=kind_id)+ .first()+ )return (models[kind].objects.using(get_database_connection_name(info.context)) # type: ignore[attr-defined]diff --git a/saleor/graphql/translations/tests/mutations/test_attribute_value_bulk_transalte.py b/saleor/graphql/translations/tests/mutations/test_attribute_value_bulk_transalte.pyindex fc32335635..2db100ec98 100644--- a/saleor/graphql/translations/tests/mutations/test_attribute_value_bulk_transalte.py+++ b/saleor/graphql/translations/tests/mutations/test_attribute_value_bulk_transalte.py@@ -5,7 +5,12 @@ import grapheneimport pytestfrom .....tests.utils import dummy_editorjs-from ....core.enums import LanguageCodeEnum, TranslationErrorCode+from ....core.enums import (+ AttributeValueTranslateErrorCode,+ ErrorPolicyEnum,+ LanguageCodeEnum,+ TranslationErrorCode,+)from ....tests.utils import get_graphql_contentfrom ...mutations import AttributeValueBulkTranslate@@ -485,3 +490,78 @@ def test_attribute_value_bulk_translate_return_error_when_invalid_value_externalassert error["code"] == TranslationErrorCode.NOT_FOUND.nameassert error["message"] == messageassert error["path"] == "externalReference"+++@patch("saleor.plugins.manager.PluginsManager.translations_created")+def test_attribute_value_bulk_translate_rejects_customer_attribute_values(+ created_webhook_mock,+ staff_api_client,+ color_attribute,+ loyalty_customer_attribute,+ permission_manage_translations,+):+ # given+ mutation = """+ mutation AttributeValueBulkTranslate(+ $translations: [AttributeValueBulkTranslateInput!]!,+ $errorPolicy: ErrorPolicyEnum+ ) {+ attributeValueBulkTranslate(+ translations: $translations, errorPolicy: $errorPolicy+ ) {+ results {+ errors {+ path+ code+ message+ }+ translation {+ id+ name+ }+ }+ count+ }+ }+ """+ catalog_value = color_attribute.values.first()+ customer_value = loyalty_customer_attribute.values.first()+ translated_name = "Czerwony"+ translations = [+ {+ "id": graphene.Node.to_global_id("AttributeValue", catalog_value.id),+ "languageCode": LanguageCodeEnum.PL.name,+ "translationFields": {"name": translated_name},+ },+ {+ "id": graphene.Node.to_global_id("AttributeValue", customer_value.id),+ "languageCode": LanguageCodeEnum.PL.name,+ "translationFields": {"name": "Złoty"},+ },+ ]++ # when+ staff_api_client.user.user_permissions.add(permission_manage_translations)+ response = staff_api_client.post_graphql(+ mutation,+ {+ "translations": translations,+ "errorPolicy": ErrorPolicyEnum.REJECT_FAILED_ROWS.name,+ },+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeValueBulkTranslate"]++ # then+ assert data["count"] == 1+ assert not data["results"][0]["errors"]+ assert data["results"][0]["translation"]["name"] == translated_name+ assert data["results"][1]["translation"] is None+ errors = data["results"][1]["errors"]+ assert len(errors) == 1+ assert errors[0]["message"] == "Values of customer attributes cannot be translated."+ assert errors[0]["code"] == AttributeValueTranslateErrorCode.INVALID.name+ assert errors[0]["path"] == "id"+ assert catalog_value.translations.get().name == translated_name+ assert not customer_value.translations.exists()+ assert created_webhook_mock.call_count == 1diff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.pyindex c59ec9b2ee..44b41c453e 100644--- a/saleor/graphql/translations/tests/test_translations.py+++ b/saleor/graphql/translations/tests/test_translations.py@@ -14,7 +14,7 @@ from ....permission.models import Permissionfrom ....tests.utils import dummy_editorjsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.transport.asynchronous.transport import WebhookPayloadData-from ...core.enums import LanguageCodeEnum+from ...core.enums import LanguageCodeEnum, TranslationErrorCodefrom ...tests.utils import assert_no_permission, get_graphql_contentfrom ..schema import TranslatableKinds@@ -2644,6 +2644,61 @@ def test_plain_text_attribute_value_update_translation_name_null(assert data["attributeValue"]["translation"]["plainText"] == expected_text+ATTRIBUTE_VALUE_TRANSLATE_WITH_ERRORS_MUTATION = """+ mutation attributeValueTranslate(+ $attributeValueId: ID!,+ $input: AttributeValueTranslationInput!+ ) {+ attributeValueTranslate(+ id: $attributeValueId,+ languageCode: PL,+ input: $input+ ) {+ attributeValue {+ id+ }+ errors {+ field+ code+ message+ }+ }+ }+"""+++@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async_for_multiple_objects")+def test_attribute_value_translate_customer_attribute_value_rejected(+ mocked_webhook_trigger_for_multiple_objects,+ staff_api_client,+ loyalty_customer_attribute,+ permission_manage_translations,+ settings,+):+ # given+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ customer_value = loyalty_customer_attribute.values.first()+ attribute_value_id = graphene.Node.to_global_id("AttributeValue", customer_value.id)++ # when+ response = staff_api_client.post_graphql(+ ATTRIBUTE_VALUE_TRANSLATE_WITH_ERRORS_MUTATION,+ {"attributeValueId": attribute_value_id, "input": {"name": "Złoty"}},+ permissions=[permission_manage_translations],+ )++ # then+ data = get_graphql_content(response)["data"]["attributeValueTranslate"]+ assert data["attributeValue"] is None+ assert len(data["errors"]) == 1+ error = data["errors"][0]+ assert error["field"] == "id"+ assert error["code"] == TranslationErrorCode.INVALID.name+ assert error["message"] == "Values of customer attributes cannot be translated."+ assert not customer_value.translations.exists()+ mocked_webhook_trigger_for_multiple_objects.assert_not_called()++SHIPPING_PRICE_TRANSLATE = """mutation shippingPriceTranslate($shippingMethodId: ID!, $input: ShippingPriceTranslationInput!@@ -3378,6 +3433,78 @@ def test_translation_query_attribute_value(assert data["translation"]["name"] == translated_attribute_value.name+def test_translation_query_customer_attribute_value_returns_null(+ staff_api_client,+ loyalty_customer_attribute,+ permission_manage_translations,+):+ # given+ customer_value = loyalty_customer_attribute.values.first()+ variables = {+ "id": graphene.Node.to_global_id("AttributeValue", customer_value.id),+ "kind": TranslatableKinds.ATTRIBUTE_VALUE.name,+ "languageCode": LanguageCodeEnum.PL.name,+ }++ # when+ response = staff_api_client.post_graphql(+ QUERY_TRANSLATION_ATTRIBUTE_VALUE,+ variables,+ permissions=[permission_manage_translations],+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["translation"] is None+++def test_translations_query_excludes_customer_attribute_values(+ staff_api_client,+ pink_attribute_value,+ loyalty_customer_attribute,+ permission_manage_translations,+):+ # given the values of a catalog attribute and of a customer attribute+ catalog_value_ids = {+ graphene.Node.to_global_id("AttributeValueTranslatableContent", pk)+ for pk in pink_attribute_value.attribute.values.values_list("pk", flat=True)+ }+ customer_value_ids = {+ graphene.Node.to_global_id("AttributeValueTranslatableContent", pk)+ for pk in loyalty_customer_attribute.values.values_list("pk", flat=True)+ }+ assert catalog_value_ids+ assert customer_value_ids+ query = """+ query TranslationsQuery($kind: TranslatableKinds!) {+ translations(kind: $kind, first: 100) {+ edges {+ node {+ ... on AttributeValueTranslatableContent {+ id+ }+ }+ }+ totalCount+ }+ }+ """++ # when+ response = staff_api_client.post_graphql(+ query,+ {"kind": TranslatableKinds.ATTRIBUTE_VALUE.name},+ permissions=[permission_manage_translations],+ )++ # then exactly the catalog values are listed, the customer values are not+ data = get_graphql_content(response)["data"]["translations"]+ returned_ids = {edge["node"]["id"] for edge in data["edges"]}+ assert returned_ids == catalog_value_ids+ assert returned_ids.isdisjoint(customer_value_ids)+ assert data["totalCount"] == len(catalog_value_ids)++QUERY_TRANSLATION_VARIANT = """query translation($kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum!diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.pyindex 6c79a79ff3..a261353363 100644--- a/saleor/graphql/webhook/enums.py+++ b/saleor/graphql/webhook/enums.py@@ -2,6 +2,7 @@ import graphenefrom ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ..core.descriptions import (+ ADDED_IN_323,DEFAULT_DEPRECATION_REASON,DEPRECATED_LEGACY_PAYMENTS,)@@ -87,6 +88,12 @@ WEBHOOK_EVENT_DESCRIPTION = {WebhookEventAsyncType.CUSTOMER_UPDATED: "A customer account is updated.",WebhookEventAsyncType.CUSTOMER_DELETED: "A customer account is deleted.",WebhookEventAsyncType.CUSTOMER_METADATA_UPDATED: "A customer account metadata is updated.",+ WebhookEventAsyncType.CUSTOMER_TYPE_CREATED: "A new customer type is created."+ + ADDED_IN_323,+ WebhookEventAsyncType.CUSTOMER_TYPE_UPDATED: "A customer type is updated."+ + ADDED_IN_323,+ WebhookEventAsyncType.CUSTOMER_TYPE_DELETED: "A customer type is deleted."+ + ADDED_IN_323,WebhookEventAsyncType.GIFT_CARD_CREATED: "A new gift card created.",WebhookEventAsyncType.GIFT_CARD_UPDATED: "A gift card is updated.",WebhookEventAsyncType.GIFT_CARD_DELETED: "A gift card is deleted.",diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex e87010d48d..b64ed9367f 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -1649,6 +1649,42 @@ class CustomerDeleted(SubscriptionObjectType, UserBase):description = "Event sent when customer user is deleted." + ADDED_IN_323+class CustomerTypeBase(AbstractType):+ customer_type = graphene.Field(+ "saleor.graphql.account.types.CustomerType",+ description="The customer type the event relates to.",+ )++ @staticmethod+ def resolve_customer_type(root, _info: ResolveInfo):+ _, customer_type = root+ return customer_type+++class CustomerTypeCreated(SubscriptionObjectType, CustomerTypeBase):+ class Meta:+ root_type = "CustomerType"+ enable_dry_run = True+ interfaces = (Event,)+ description = "Event sent when new customer type is created." + ADDED_IN_323+++class CustomerTypeUpdated(SubscriptionObjectType, CustomerTypeBase):+ class Meta:+ root_type = "CustomerType"+ enable_dry_run = True+ interfaces = (Event,)+ description = "Event sent when customer type is updated." + ADDED_IN_323+++class CustomerTypeDeleted(SubscriptionObjectType, CustomerTypeBase):+ class Meta:+ root_type = "CustomerType"+ enable_dry_run = True+ interfaces = (Event,)+ description = "Event sent when customer type is deleted." + ADDED_IN_323++class CollectionBase(AbstractType):collection = graphene.Field("saleor.graphql.product.types.collections.Collection",@@ -3283,6 +3319,9 @@ ASYNC_WEBHOOK_TYPES_MAP = {WebhookEventAsyncType.CUSTOMER_UPDATED: CustomerUpdated,WebhookEventAsyncType.CUSTOMER_DELETED: CustomerDeleted,WebhookEventAsyncType.CUSTOMER_METADATA_UPDATED: CustomerMetadataUpdated,+ WebhookEventAsyncType.CUSTOMER_TYPE_CREATED: CustomerTypeCreated,+ WebhookEventAsyncType.CUSTOMER_TYPE_UPDATED: CustomerTypeUpdated,+ WebhookEventAsyncType.CUSTOMER_TYPE_DELETED: CustomerTypeDeleted,WebhookEventAsyncType.COLLECTION_CREATED: CollectionCreated,WebhookEventAsyncType.COLLECTION_UPDATED: CollectionUpdated,WebhookEventAsyncType.COLLECTION_DELETED: CollectionDeleted,diff --git a/saleor/permission/enums.py b/saleor/permission/enums.pyindex fac96c66ca..0d337c1177 100644--- a/saleor/permission/enums.py+++ b/saleor/permission/enums.py@@ -28,6 +28,12 @@ class ChannelPermissions(BasePermissionEnum):MANAGE_CHANNELS = "channel.manage_channels"+class CustomerTypePermissions(BasePermissionEnum):+ MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES = (+ "account.manage_customer_types_and_attributes"+ )++class DiscountPermissions(BasePermissionEnum):MANAGE_DISCOUNTS = "discount.manage_discounts"@@ -90,6 +96,7 @@ PERMISSIONS_ENUMS = [AppPermission,CheckoutPermissions,ChannelPermissions,+ CustomerTypePermissions,DiscountPermissions,GiftcardPermissions,MenuPermissions,diff --git a/saleor/permission/tests/fixtures/permission.py b/saleor/permission/tests/fixtures/permission.pyindex 6675a150f0..8e94cb2455 100644--- a/saleor/permission/tests/fixtures/permission.py+++ b/saleor/permission/tests/fixtures/permission.py@@ -83,6 +83,11 @@ def permission_manage_users():return Permission.objects.get(codename="manage_users")+def permission_manage_customer_types_and_attributes():+ return Permission.objects.get(codename="manage_customer_types_and_attributes")++@pytest.fixturedef permission_impersonate_user():return Permission.objects.get(codename="impersonate_user")diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex d30db123df..b821b8ef88 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -34,7 +34,7 @@ from ..thumbnail.models import Thumbnailfrom .models import PluginConfigurationif TYPE_CHECKING:- from ..account.models import Address, Group, User+ from ..account.models import Address, CustomerType, Group, Userfrom ..app.models import Appfrom ..attribute.models import Attribute, AttributeValuefrom ..channel.models import Channel@@ -630,6 +630,24 @@ class BasePlugin:# Webhook-related functionality will be moved from the plugin to core modules.customer_metadata_updated: Callable[["User", Any, None], Any]+ # Trigger when customer type is created.+ #+ # Overwrite this method if you need to trigger specific logic after a customer+ # type is created.+ customer_type_created: Callable[["CustomerType", Any], Any]++ # Trigger when customer type is updated.+ #+ # Overwrite this method if you need to trigger specific logic after a customer+ # type is updated.+ customer_type_updated: Callable[["CustomerType", Any], Any]++ # Trigger when customer type is deleted.+ #+ # Overwrite this method if you need to trigger specific logic after a customer+ # type is deleted.+ customer_type_deleted: Callable[["CustomerType", Any, None], Any]+# Handle authentication request.## Overwrite this method if the plugin handles authentication flow.diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex bc057c652d..f222f9b622 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -53,7 +53,7 @@ from .base_plugin import ExternalAccessTokensfrom .models import PluginConfigurationif TYPE_CHECKING:- from ..account.models import Address, Group, User+ from ..account.models import Address, CustomerType, Group, Userfrom ..app.models import Appfrom ..attribute.models import Attribute, AttributeValuefrom ..checkout.fetch import CheckoutInfo, CheckoutLineInfo@@ -714,6 +714,28 @@ class PluginsManager(PaymentInterface):channel_slug=None,)+ def customer_type_created(self, customer_type: "CustomerType"):+ default_value = None+ return self.__run_method_on_plugins(+ "customer_type_created", default_value, customer_type, channel_slug=None+ )++ def customer_type_updated(self, customer_type: "CustomerType"):+ default_value = None+ return self.__run_method_on_plugins(+ "customer_type_updated", default_value, customer_type, channel_slug=None+ )++ def customer_type_deleted(self, customer_type: "CustomerType", webhooks=None):+ default_value = None+ return self.__run_method_on_plugins(+ "customer_type_deleted",+ default_value,+ customer_type,+ webhooks=webhooks,+ channel_slug=None,+ )+# Note: this method is deprecated and will be removed in a future release.# Webhook-related functionality will be moved from plugin to core modules.def collection_created(self, collection: "Collection"):diff --git a/saleor/plugins/openid_connect/tests/test_utils.py b/saleor/plugins/openid_connect/tests/test_utils.pyindex 6d9f93756d..47f99fd3e2 100644--- a/saleor/plugins/openid_connect/tests/test_utils.py+++ b/saleor/plugins/openid_connect/tests/test_utils.py@@ -1347,3 +1347,25 @@ def test_update_user_details_nothing_changed(assert customer_user.first_name == first_nameassert updated is Falseupdate_user_search_vector_mock.assert_not_called()++[email protected]("saleor.plugins.openid_connect.utils.cache.set")[email protected]("saleor.plugins.openid_connect.utils.cache.get")+def test_get_or_create_user_from_payload_assigns_default_customer_type(+ mocked_cache_get, mocked_cache_set, default_customer_type+):+ # given+ oauth_url = "https://saleor.io/oauth"+ sub_id = "oauth|1234"+ customer_email = "[email protected]"+ mocked_cache_get.side_effect = lambda cache_key: None++ # when+ user_from_payload, created, _ = get_or_create_user_from_payload(+ payload={"sub": sub_id, "email": customer_email},+ oauth_url=oauth_url,+ )++ # then+ assert created is True+ assert user_from_payload.customer_type == default_customer_typediff --git a/saleor/plugins/openid_connect/utils.py b/saleor/plugins/openid_connect/utils.pyindex a5c8844836..e8c6a7f4d9 100644--- a/saleor/plugins/openid_connect/utils.py+++ b/saleor/plugins/openid_connect/utils.py@@ -18,7 +18,11 @@ from jwt import PyJWTErrorfrom ...account.models import Group, Userfrom ...account.search import update_user_search_vector-from ...account.utils import get_user_groups_permissions, send_user_event+from ...account.utils import (+ get_default_customer_type,+ get_user_groups_permissions,+ send_user_event,+)from ...core.http_client import HTTPClientfrom ...core.jwt import (JWT_ACCESS_TYPE,@@ -464,6 +468,7 @@ def get_or_create_user_from_payload(**get_kwargs)except User.DoesNotExist:+ defaults_create["customer_type"] = get_default_customer_type()user, created = User.objects.get_or_create(email=user_email,defaults=defaults_create,@@ -474,6 +479,7 @@ def get_or_create_user_from_payload(except User.MultipleObjectsReturned:logger.warning("Multiple users returned for single OIDC sub ID")+ defaults_create["customer_type"] = get_default_customer_type()user, created = User.objects.get_or_create(email=user_email,defaults=defaults_create,diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex b105010e98..ee226c18db 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -126,7 +126,7 @@ from ...webhook.utils import (from ..base_plugin import BasePluginif TYPE_CHECKING:- from ...account.models import Address, Group, User+ from ...account.models import Address, CustomerType, Group, Userfrom ...attribute.models import Attribute, AttributeValuefrom ...core.utils.translations import Translationfrom ...csv.models import ExportFile@@ -1709,6 +1709,52 @@ class WebhookPlugin(BasePlugin):)return previous_value+ def _trigger_customer_type_event(self, event_type, customer_type, webhooks=None):+ if webhooks := self._get_webhooks_for_event(event_type, webhooks):+ payload = self._serialize_payload(+ {+ "id": graphene.Node.to_global_id("CustomerType", customer_type.id),+ "name": customer_type.name,+ "slug": customer_type.slug,+ "meta": self._generate_meta(),+ }+ )+ self.trigger_webhooks_async(+ payload, event_type, webhooks, customer_type, self.requestor+ )++ def customer_type_created(+ self, customer_type: "CustomerType", previous_value: None+ ) -> None:+ if not self.active:+ return previous_value+ self._trigger_customer_type_event(+ WebhookEventAsyncType.CUSTOMER_TYPE_CREATED, customer_type+ )+ return previous_value++ def customer_type_updated(+ self, customer_type: "CustomerType", previous_value: None+ ) -> None:+ if not self.active:+ return previous_value+ self._trigger_customer_type_event(+ WebhookEventAsyncType.CUSTOMER_TYPE_UPDATED, customer_type+ )+ return previous_value++ def customer_type_deleted(+ self, customer_type: "CustomerType", previous_value: None, webhooks=None+ ) -> None:+ if not self.active:+ return previous_value+ self._trigger_customer_type_event(+ WebhookEventAsyncType.CUSTOMER_TYPE_DELETED,+ customer_type,+ webhooks=webhooks,+ )+ return previous_value+def collection_created(self, collection: "Collection", previous_value: None) -> None:diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex f4f4ca6c32..f8887f3f04 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -1224,6 +1224,9 @@ def async_subscription_webhooks_with_root_objects(subscription_page_type_created_webhook,subscription_page_type_updated_webhook,subscription_page_type_deleted_webhook,+ subscription_customer_type_created_webhook,+ subscription_customer_type_updated_webhook,+ subscription_customer_type_deleted_webhook,subscription_permission_group_created_webhook,subscription_permission_group_updated_webhook,subscription_permission_group_deleted_webhook,@@ -1259,6 +1262,7 @@ def async_subscription_webhooks_with_root_objects(fulfillment,stock,customer_user,+ customer_type,collection,checkout,page,@@ -1519,6 +1523,18 @@ def async_subscription_webhooks_with_root_objects(events.PAGE_TYPE_CREATED: [subscription_page_type_created_webhook, page_type],events.PAGE_TYPE_UPDATED: [subscription_page_type_updated_webhook, page_type],events.PAGE_TYPE_DELETED: [subscription_page_type_deleted_webhook, page_type],+ events.CUSTOMER_TYPE_CREATED: [+ subscription_customer_type_created_webhook,+ customer_type,+ ],+ events.CUSTOMER_TYPE_UPDATED: [+ subscription_customer_type_updated_webhook,+ customer_type,+ ],+ events.CUSTOMER_TYPE_DELETED: [+ subscription_customer_type_deleted_webhook,+ customer_type,+ ],events.PERMISSION_GROUP_CREATED: [subscription_permission_group_created_webhook,permission_group_manage_users,diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex b18aa97abb..3b870e15b6 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -6,6 +6,7 @@ from ..permission.enums import (BasePermissionEnum,ChannelPermissions,CheckoutPermissions,+ CustomerTypePermissions,DiscountPermissions,GiftcardPermissions,MenuPermissions,@@ -120,6 +121,10 @@ class WebhookEventAsyncType:CUSTOMER_DELETED = "customer_deleted"CUSTOMER_METADATA_UPDATED = "customer_metadata_updated"+ CUSTOMER_TYPE_CREATED = "customer_type_created"+ CUSTOMER_TYPE_UPDATED = "customer_type_updated"+ CUSTOMER_TYPE_DELETED = "customer_type_deleted"+COLLECTION_CREATED = "collection_created"COLLECTION_UPDATED = "collection_updated"COLLECTION_DELETED = "collection_deleted"@@ -556,6 +561,24 @@ class WebhookEventAsyncType:"name": "Customer metadata updated","permission": AccountPermissions.MANAGE_USERS,},+ CUSTOMER_TYPE_CREATED: {+ "name": "Customer type created",+ "permission": (+ CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES+ ),+ },+ CUSTOMER_TYPE_UPDATED: {+ "name": "Customer type updated",+ "permission": (+ CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES+ ),+ },+ CUSTOMER_TYPE_DELETED: {+ "name": "Customer type deleted",+ "permission": (+ CustomerTypePermissions.MANAGE_CUSTOMER_TYPES_AND_ATTRIBUTES+ ),+ },COLLECTION_CREATED: {"name": "Collection created","permission": ProductPermissions.MANAGE_PRODUCTS,diff --git a/saleor/webhook/tests/fixtures/subscription_webhooks.py b/saleor/webhook/tests/fixtures/subscription_webhooks.pyindex c6f485b0bb..b967473fd1 100644--- a/saleor/webhook/tests/fixtures/subscription_webhooks.py+++ b/saleor/webhook/tests/fixtures/subscription_webhooks.py@@ -879,6 +879,27 @@ def subscription_page_type_deleted_webhook(subscription_webhook):)+def subscription_customer_type_created_webhook(subscription_webhook):+ return subscription_webhook(+ queries.CUSTOMER_TYPE_CREATED, WebhookEventAsyncType.CUSTOMER_TYPE_CREATED+ )+++def subscription_customer_type_updated_webhook(subscription_webhook):+ return subscription_webhook(+ queries.CUSTOMER_TYPE_UPDATED, WebhookEventAsyncType.CUSTOMER_TYPE_UPDATED+ )+++def subscription_customer_type_deleted_webhook(subscription_webhook):+ return subscription_webhook(+ queries.CUSTOMER_TYPE_DELETED, WebhookEventAsyncType.CUSTOMER_TYPE_DELETED+ )++@pytest.fixturedef subscription_product_type_created_webhook(subscription_webhook):return subscription_webhook(diff --git a/saleor/webhook/tests/subscription_webhooks/payloads.py b/saleor/webhook/tests/subscription_webhooks/payloads.pyindex 7e33b8c65f..f35246f3fe 100644--- a/saleor/webhook/tests/subscription_webhooks/payloads.py+++ b/saleor/webhook/tests/subscription_webhooks/payloads.py@@ -304,6 +304,22 @@ def generate_page_type_payload(page_type, app):}+def generate_customer_type_payload(customer_type, app):+ customer_type_id = graphene.Node.to_global_id("CustomerType", customer_type.pk)+ return {+ "recipient": {+ "id": graphene.Node.to_global_id("App", app.pk),+ "name": app.name,+ },+ "customerType": {+ "id": customer_type_id,+ "name": customer_type.name,+ "slug": customer_type.slug,+ "isDefault": customer_type.is_default,+ },+ }++def generate_product_type_payload(product_type, app):return {"recipient": {diff --git a/saleor/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/webhook/tests/subscription_webhooks/subscription_queries.pyindex d46e81eacb..79006bb452 100644--- a/saleor/webhook/tests/subscription_webhooks/subscription_queries.py+++ b/saleor/webhook/tests/subscription_webhooks/subscription_queries.py@@ -2283,6 +2283,63 @@ PAGE_TYPE_DELETED = (""")+CUSTOMER_TYPE_CREATED = (+ fragments.CUSTOMER_TYPE_DETAILS+ + fragments.RECIPIENT_APP_DETAILS+ + """+ subscription{+ event{+ recipient{+ ...Recipient+ }+ ...on CustomerTypeCreated{+ customerType{+ ...CustomerTypeDetails+ }+ }+ }+ }+"""+)++CUSTOMER_TYPE_UPDATED = (+ fragments.CUSTOMER_TYPE_DETAILS+ + fragments.RECIPIENT_APP_DETAILS+ + """+ subscription{+ event{+ recipient{+ ...Recipient+ }+ ...on CustomerTypeUpdated{+ customerType{+ ...CustomerTypeDetails+ }+ }+ }+ }+"""+)++CUSTOMER_TYPE_DELETED = (+ fragments.CUSTOMER_TYPE_DETAILS+ + fragments.RECIPIENT_APP_DETAILS+ + """+ subscription{+ event{+ recipient{+ ...Recipient+ }+ ...on CustomerTypeDeleted{+ customerType{+ ...CustomerTypeDetails+ }+ }+ }+ }+"""+)+PRODUCT_TYPE_CREATED = (fragments.PRODUCT_TYPE_DETAILS+ fragments.RECIPIENT_APP_DETAILSdiff --git a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.pyindex 95d187d766..9b6db04f15 100644--- a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py+++ b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py@@ -34,6 +34,7 @@ from .payloads import (generate_category_payload,generate_collection_payload,generate_customer_payload,+ generate_customer_type_payload,generate_export_payload,generate_fulfillment_payload,generate_gift_card_payload,@@ -2577,6 +2578,73 @@ def test_page_type_deleted(page_type, subscription_page_type_deleted_webhook):assert deliveries[0].webhook == webhooks[0]+def test_customer_type_created(+ customer_type, subscription_customer_type_created_webhook+):+ # given+ webhooks = [subscription_customer_type_created_webhook]+ event_type = WebhookEventAsyncType.CUSTOMER_TYPE_CREATED+ expected_payload = generate_customer_type_payload(+ customer_type, subscription_customer_type_created_webhook.app+ )++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, customer_type, webhooks+ )++ # then+ assert json.loads(deliveries[0].payload.get_payload()) == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_customer_type_updated(+ customer_type, subscription_customer_type_updated_webhook+):+ # given+ webhooks = [subscription_customer_type_updated_webhook]+ event_type = WebhookEventAsyncType.CUSTOMER_TYPE_UPDATED+ expected_payload = generate_customer_type_payload(+ customer_type, subscription_customer_type_updated_webhook.app+ )++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, customer_type, webhooks+ )++ # then+ assert json.loads(deliveries[0].payload.get_payload()) == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_customer_type_deleted(+ customer_type, subscription_customer_type_deleted_webhook+):+ # given+ customer_type_pk = customer_type.pk+ customer_type.delete()+ customer_type.pk = customer_type_pk++ webhooks = [subscription_customer_type_deleted_webhook]+ event_type = WebhookEventAsyncType.CUSTOMER_TYPE_DELETED+ expected_payload = generate_customer_type_payload(+ customer_type, subscription_customer_type_deleted_webhook.app+ )++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, customer_type, webhooks+ )++ # then+ assert json.loads(deliveries[0].payload.get_payload()) == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]++def test_product_type_created(product_type, subscription_product_type_created_webhook):# givenwebhooks = [subscription_product_type_created_webhook]