Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Merge branch 'master' into feature/convert_service_account_into_app
Maciej Korycinski731e28e65710
diff --cc saleor/account/migrations/0043_rename_service_account_to_app.pyindex 6f86f153ad,0000000000..fa2e5562d9mode 100644,000000..100644--- a/saleor/account/migrations/0043_rename_service_account_to_app.py+++ b/saleor/account/migrations/0043_rename_service_account_to_app.py@@@ -1,37 -1,0 +1,37 @@@+# Generated by Django 3.0.5 on 2020-04-16 06:00++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("core", "0001_migrate_metadata"),+ ("auth", "0011_update_proxy_permissions"),+ ("webhook", "0002_webhook_name"),- ("account", "0041_permissions_to_groups"),++ ("account", "0042_merge_20200422_0555"),+ ]++ operations = [+ migrations.RenameModel(old_name="ServiceAccount", new_name="App",),+ migrations.RenameModel(old_name="ServiceAccountToken", new_name="AppToken",),+ migrations.AlterModelTable(name="app", table="app_app",),+ migrations.AlterModelTable(name="apptoken", table="app_apptoken",),+ migrations.RenameField(+ model_name="apptoken", old_name="service_account", new_name="app",+ ),+ migrations.AlterModelOptions(+ name="app", options={"permissions": (("manage_apps", "Manage apps"),)},+ ),+ migrations.AlterField(+ model_name="app",+ name="permissions",+ field=models.ManyToManyField(+ blank=True,+ help_text="Specific permissions for this app.",+ related_name="app_set",+ related_query_name="app",+ to="auth.Permission",+ ),+ ),+ ]diff --cc saleor/account/migrations/0044_unmount_app_and_app_token.pyindex 6e916dc5cf,0000000000..6cb48def17mode 100644,000000..100644--- a/saleor/account/migrations/0044_unmount_app_and_app_token.py+++ b/saleor/account/migrations/0044_unmount_app_and_app_token.py@@@ -1,21 -1,0 +1,21 @@@+# Generated by Django 3.0.5 on 2020-04-16 06:07++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [- ("account", "0042_rename_service_account_to_app"),++ ("account", "0043_rename_service_account_to_app"),+ ("webhook", "0003_unmount_service_account"),+ ]++ state_operations = [+ migrations.RemoveField(model_name="apptoken", name="app",),+ migrations.DeleteModel(name="App",),+ migrations.DeleteModel(name="AppToken",),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(state_operations=state_operations)+ ]diff --cc saleor/app/migrations/0001_initial.pyindex 7e7a6b95cd,0000000000..01057d94b8mode 100644,000000..100644--- a/saleor/app/migrations/0001_initial.py+++ b/saleor/app/migrations/0001_initial.py@@@ -1,156 -1,0 +1,157 @@@+# Generated by Django 3.0.5 on 2020-04-15 06:21++import django.contrib.postgres.fields.jsonb+import django.db.models.deletion+import oauthlib.common+from django.db import migrations, models++import saleor.core.utils.json_serializer+++def update_contentypes(apps, schema_editor):+ """Update content types.++ We want to have the same content type id, when the model is moved.+ """+ ContentType = apps.get_model("contenttypes", "ContentType")+ db_alias = schema_editor.connection.alias+ # Move the ServiceAccount to app module+ qs = ContentType.objects.using(db_alias).filter(app_label="account", model="app")+ qs.update(app_label="app")++ # Move the ServiceAccountToken to app module+ qs = ContentType.objects.using(db_alias).filter(+ app_label="account", model="apptoken"+ )+ qs.update(app_label="app")+++def update_contentypes_reverse(apps, schema_editor):+ """Revert changes in content types."""+ ContentType = apps.get_model("contenttypes", "ContentType")+ db_alias = schema_editor.connection.alias++ qs = ContentType.objects.using(db_alias).filter(app_label="app", model="app")+ qs.update(app_label="account")++ qs = ContentType.objects.using(db_alias).filter(app_label="app", model="apptoken")+ qs.update(app_label="account")+++def convert_service_account_permissions_to_app_permissions(apps, schema_editor):+ Permission = apps.get_model("auth", "Permission")+ service_account_permission = Permission.objects.filter(+ codename="manage_service_accounts", content_type__app_label="app"+ ).first()+ if service_account_permission:+ service_account_permission.codename = "manage_apps"+ service_account_permission.name = "Manage apps"+ service_account_permission.save()+++class Migration(migrations.Migration):++ initial = True++ dependencies = [+ ("auth", "0011_update_proxy_permissions"),- ("account", "0043_unmount_app_and_app_token"),++ ("account", "0044_unmount_app_and_app_token"),+ ]++ state_operations = [+ migrations.CreateModel(+ name="App",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("name", models.CharField(max_length=60)),+ ("created", models.DateTimeField(auto_now_add=True)),+ ("is_active", models.BooleanField(default=True)),+ (+ "permissions",+ models.ManyToManyField(+ blank=True,+ help_text="Specific permissions for this app.",+ related_name="app_set",+ related_query_name="app",+ to="auth.Permission",+ ),+ ),+ (+ "metadata",+ django.contrib.postgres.fields.jsonb.JSONField(+ blank=True,+ default=dict,+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,+ null=True,+ ),+ ),+ (+ "private_metadata",+ django.contrib.postgres.fields.jsonb.JSONField(+ blank=True,+ default=dict,+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,+ null=True,+ ),+ ),+ ],+ options={+ "db_table": "app_app",++ "ordering": ("name", "pk"),+ "permissions": (("manage_apps", "Manage apps"),),+ },+ ),+ migrations.CreateModel(+ name="AppToken",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("name", models.CharField(blank=True, default="", max_length=128)),+ (+ "auth_token",+ models.CharField(+ default=oauthlib.common.generate_token,+ max_length=30,+ unique=True,+ ),+ ),+ (+ "app",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="tokens",+ to="app.App",+ ),+ ),+ ],+ options={"db_table": "app_apptoken"},+ ),+ ]++ database_operations = [+ migrations.RunPython(update_contentypes, update_contentypes_reverse),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=state_operations, database_operations=database_operations+ ),+ migrations.AlterModelTable(name="app", table=None,),+ migrations.AlterModelTable(name="apptoken", table=None,),+ migrations.RunPython(convert_service_account_permissions_to_app_permissions),+ ]diff --cc saleor/app/models.pyindex 1cff6bd231,0000000000..3456e1bb9amode 100644,000000..100644--- a/saleor/app/models.py+++ b/saleor/app/models.py@@@ -1,62 -1,0 +1,59 @@@+from typing import Set++from django.contrib.auth.models import Permission+from django.db import models+from oauthlib.common import generate_token++from ..core.models import ModelWithMetadata+from ..core.permissions import AppPermission+- #-++class App(ModelWithMetadata):+ name = models.CharField(max_length=60)+ created = models.DateTimeField(auto_now_add=True)+ is_active = models.BooleanField(default=True)+ permissions = models.ManyToManyField(+ Permission,+ blank=True,+ help_text="Specific permissions for this app.",+ related_name="app_set",+ related_query_name="app",+ )++ class Meta:++ ordering = ("name", "pk")+ permissions = ((AppPermission.MANAGE_APPS.codename, "Manage apps",),)++ def _get_permissions(self) -> Set[str]:+ """Return the permissions of the app."""+ if not self.is_active:+ return set()+ perm_cache_name = "_app_perm_cache"+ if not hasattr(self, perm_cache_name):+ perms = self.permissions.all()+ perms = perms.values_list("content_type__app_label", "codename").order_by()+ setattr(self, perm_cache_name, {f"{ct}.{name}" for ct, name in perms})+ return getattr(self, perm_cache_name)++ def has_perms(self, perm_list):+ """Return True if the app has each of the specified permissions."""+ if not self.is_active:+ return False++ wanted_perms = {perm.value for perm in perm_list}+ actual_perms = self._get_permissions()++ return (wanted_perms & actual_perms) == wanted_perms++ def has_perm(self, perm):+ """Return True if the app has the specified permission."""+ if not self.is_active:+ return False++ return perm.value in self._get_permissions()++- #- #+class AppToken(models.Model):+ app = models.ForeignKey(App, on_delete=models.CASCADE, related_name="tokens")+ name = models.CharField(blank=True, default="", max_length=128)+ auth_token = models.CharField(default=generate_token, unique=True, max_length=30)diff --cc saleor/graphql/account/deprecated/resolvers.pyindex 73007fa39f,0000000000..2936362d80mode 100644,000000..100644--- a/saleor/graphql/account/deprecated/resolvers.py+++ b/saleor/graphql/account/deprecated/resolvers.py@@@ -1,11 -1,0 +1,8 @@@+import graphene_django_optimizer as gql_optimizer++from ....app.models import App- from ...utils import sort_queryset- from ..deprecated.sorters import ServiceAccountSortField++- def resolve_service_accounts(info, sort_by=None, **_kwargs):++def resolve_service_accounts(info, **_kwargs):+ qs = App.objects.all()- qs = sort_queryset(qs, sort_by, ServiceAccountSortField)+ return gql_optimizer.query(qs, info)diff --cc saleor/graphql/account/deprecated/sorters.pyindex 6fc3775a7d,0000000000..b2cfeb74cemode 100644,000000..100644--- a/saleor/graphql/account/deprecated/sorters.py+++ b/saleor/graphql/account/deprecated/sorters.py@@@ -1,25 -1,0 +1,25 @@@+import graphene++from ...core.types import SortInputObjectType+++class ServiceAccountSortField(graphene.Enum):- NAME = "name"- CREATION_DATE = "created"++ NAME = ["name", "pk"]++ CREATION_DATE = ["created", "name", "pk"]++ @property+ def description(self):+ # pylint: disable=no-member+ if self in [+ ServiceAccountSortField.NAME,+ ServiceAccountSortField.CREATION_DATE,+ ]:+ sort_name = self.name.lower().replace("_", " ")+ return f"Sort service accounts by {sort_name}."+ raise ValueError("Unsupported enum value: %s" % self.value)+++class ServiceAccountSortingInput(SortInputObjectType):+ class Meta:+ sort_enum = ServiceAccountSortField+ type_name = "service accounts"diff --cc saleor/graphql/account/resolvers.pyindex 81bf32fafa,3cb70f947d..2632fc3177--- a/saleor/graphql/account/resolvers.py+++ b/saleor/graphql/account/resolvers.py@@@ -15,10 -14,8 +14,8 @@@ from ...payment.utils import fetch_custfrom ..utils import (filter_by_query_param,format_permissions_for_display,- get_user_or_service_account_from_context,+ get_user_or_app_from_context,- sort_queryset,)- from .sorters import PermissionGroupSortingInput, UserSortField, UserSortingInputfrom .types import AddressValidationData, ChoiceValuefrom .utils import (get_allowed_fields_camel_case,diff --cc saleor/graphql/account/sorters.pyindex aa54e0db22,e7dcbf9798..a298c16ccd--- a/saleor/graphql/account/sorters.py+++ b/saleor/graphql/account/sorters.py@@@ -4,11 -4,33 +4,11 @@@ from django.db.models import Count, Quefrom ..core.types import SortInputObjectType-class ServiceAccountSortField(graphene.Enum):- NAME = ["name", "pk"]- CREATION_DATE = ["created", "name", "pk"]-- @property- def description(self):- # pylint: disable=no-member- if self in [- ServiceAccountSortField.NAME,- ServiceAccountSortField.CREATION_DATE,- ]:- sort_name = self.name.lower().replace("_", " ")- return f"Sort service accounts by {sort_name}."- raise ValueError("Unsupported enum value: %s" % self.value)---class ServiceAccountSortingInput(SortInputObjectType):- class Meta:- sort_enum = ServiceAccountSortField- type_name = "service accounts"--class UserSortField(graphene.Enum):- FIRST_NAME = "first_name"- LAST_NAME = "last_name"- EMAIL = "email"- ORDER_COUNT = "order_count"+ FIRST_NAME = ["first_name", "last_name", "pk"]+ LAST_NAME = ["last_name", "first_name", "pk"]+ EMAIL = ["email"]+ ORDER_COUNT = ["order_count", "email"]@propertydef description(self):diff --cc saleor/graphql/app/resolvers.pyindex f12e77f08e,0000000000..32a8b07239mode 100644,000000..100644--- a/saleor/graphql/app/resolvers.py+++ b/saleor/graphql/app/resolvers.py@@@ -1,11 -1,0 +1,8 @@@+import graphene_django_optimizer as gql_optimizer++from ...app import models- from ..utils import sort_queryset- from .sorters import AppSortField++- def resolve_apps(info, sort_by=None, **_kwargs):++def resolve_apps(info, **_kwargs):+ qs = models.App.objects.all()- qs = sort_queryset(qs, sort_by, AppSortField)+ return gql_optimizer.query(qs, info)diff --cc saleor/graphql/app/sorters.pyindex 3d0276aa20,0000000000..2f1c6e9b02mode 100644,000000..100644--- a/saleor/graphql/app/sorters.py+++ b/saleor/graphql/app/sorters.py@@@ -1,25 -1,0 +1,25 @@@+import graphene++from ..core.types import SortInputObjectType+++class AppSortField(graphene.Enum):- NAME = "name"- CREATION_DATE = "created"++ NAME = ["name", "pk"]++ CREATION_DATE = ["created", "name", "pk"]++ @property+ def description(self):+ # pylint: disable=no-member+ if self in [+ AppSortField.NAME,+ AppSortField.CREATION_DATE,+ ]:+ sort_name = self.name.lower().replace("_", " ")+ return f"Sort apps by {sort_name}."+ raise ValueError("Unsupported enum value: %s" % self.value)+++class AppSortingInput(SortInputObjectType):+ class Meta:+ sort_enum = AppSortField+ type_name = "apps"diff --cc saleor/graphql/product/resolvers.pyindex 32cb62ec4a,0e262204da..9297bff10b--- a/saleor/graphql/product/resolvers.py+++ b/saleor/graphql/product/resolvers.py@@@ -5,57 -3,19 +3,15 @@@ from django.db.models import Sufrom ...order import OrderStatusfrom ...product import models- from ...search.backends import picker- from ..core.enums import OrderDirection--from ..utils import (-- filter_by_period,- filter_by_query_param,-- get_database_id,- get_nodes,- get_user_or_app_from_context,- sort_queryset,- get_user_or_service_account_from_context,--)++from ..utils import filter_by_period, get_database_id, get_user_or_app_from_contextfrom .filters import (filter_attributes_by_product_types,- filter_products_by_attributes,- filter_products_by_categories,- filter_products_by_collections,- filter_products_by_minimal_price,- filter_products_by_price,filter_products_by_stock_availability,)- from .sorters import (- AttributeSortField,- CategorySortField,- CollectionSortField,- ProductOrder,- ProductOrderField,- ProductTypeSortField,- )- if TYPE_CHECKING:- from django.db.models.query import QuerySet-- PRODUCT_SEARCH_FIELDS = ("name", "description")- PRODUCT_TYPE_SEARCH_FIELDS = ("name",)- CATEGORY_SEARCH_FIELDS = ("name", "slug", "description", "parent__name")- COLLECTION_SEARCH_FIELDS = ("name", "slug")- ATTRIBUTES_SEARCH_FIELDS = ("name", "slug")--- def resolve_attributes(- info,- qs=None,- in_category=None,- in_collection=None,- query=None,- sort_by=None,- **_kwargs,- ):++ def resolve_attributes(info, qs=None, in_category=None, in_collection=None, **_kwargs):qs = qs or models.Attribute.objects.get_visible_to_user(info.context.user)- qs = filter_by_query_param(qs, query, ATTRIBUTES_SEARCH_FIELDS)if in_category:qs = filter_attributes_by_product_types(qs, "in_category", in_category)@@@ -95,74 -46,10 +42,10 @@@ def resolve_digital_contents(info)return gql_optimizer.query(qs, info)- def sort_products(qs: models.ProductsQueryset, sort_by: ProductOrder) -> "QuerySet":- if sort_by is None:- return qs-- # Check if one of the required fields was provided- if sort_by.field and sort_by.attribute_id:- raise GraphQLError(- "You must provide either `field` or `attributeId` to sort the products."- )-- if not sort_by.field and not sort_by.attribute_id:- return qs-- if sort_by.field:- return sort_queryset(qs, sort_by, ProductOrderField)- return sort_products_by_attribute(qs, sort_by)--- def sort_products_by_attribute(- qs: models.ProductsQueryset, sort_by: ProductOrder- ) -> models.ProductsQueryset:- direction = sort_by.direction-- # If an attribute ID was passed, attempt to convert it- if sort_by.attribute_id:- graphene_type, attribute_pk = from_global_id(sort_by.attribute_id)- is_ascending = direction == OrderDirection.ASC-- # If the passed attribute ID is valid, execute the sorting- if attribute_pk.isnumeric() and graphene_type == "Attribute":- qs = qs.sort_by_attribute(attribute_pk, ascending=is_ascending)-- return qs--- def resolve_products(- info,- attributes=None,- categories=None,- collections=None,- price_lte=None,- price_gte=None,- minimal_price_lte=None,- minimal_price_gte=None,- sort_by=None,- stock_availability=None,- query=None,- **_kwargs,- ):+ def resolve_products(info, stock_availability=None, **_kwargs):- user = get_user_or_service_account_from_context(info.context)+ user = get_user_or_app_from_context(info.context)qs = models.Product.objects.visible_to_user(user)- qs = sort_products(qs, sort_by)-- if query:- search = picker.pick_backend()- qs &= search(query)-- if attributes:- qs = filter_products_by_attributes(qs, attributes)-- if categories:- categories = get_nodes(categories, "Category", models.Category)- qs = filter_products_by_categories(qs, categories)-- if collections:- collections = get_nodes(collections, "Collection", models.Collection)- qs = filter_products_by_collections(qs, collections)if stock_availability:qs = filter_products_by_stock_availability(qs, stock_availability)diff --cc saleor/graphql/webhook/resolvers.pyindex fbff72d9e5,547191a82e..a51a5ba416--- a/saleor/graphql/webhook/resolvers.py+++ b/saleor/graphql/webhook/resolvers.py@@@ -7,12 -7,10 +7,10 @@@ from ...webhook.event_types import Webhfrom .types import Webhook, WebhookEvent- def resolve_webhooks(info, sort_by=None, **_kwargs):+ def resolve_webhooks(info, **_kwargs):- service_account = info.context.service_account- if service_account:- qs = models.Webhook.objects.filter(service_account=service_account)+ app = info.context.app+ if app:+ qs = models.Webhook.objects.filter(app=app)else:user = info.context.userif not user.has_perm(WebhookPermissions.MANAGE_WEBHOOKS):diff --cc saleor/graphql/webhook/sorters.pyindex bd190d9223,0c8eacea12..2c8b02fc1f--- a/saleor/graphql/webhook/sorters.py+++ b/saleor/graphql/webhook/sorters.py@@@ -4,10 -4,9 +4,10 @@@ from ..core.types import SortInputObjecclass WebhookSortField(graphene.Enum):- NAME = "name"- SERVICE_ACCOUNT = "app__name"- TARGET_URL = "target_url"- APP = "app__name"+ NAME = ["name", "pk"]- SERVICE_ACCOUNT = ["service_account__name", "name", "pk"]++ SERVICE_ACCOUNT = ["app__name", "name", "pk"]+ TARGET_URL = ["target_url", "name", "pk"]++ APP = ["app__name", "name", "pk"]@propertydef description(self):diff --cc saleor/webhook/migrations/0003_unmount_service_account.pyindex 5543291fbd,0000000000..8f90f50710mode 100644,000000..100644--- a/saleor/webhook/migrations/0003_unmount_service_account.py+++ b/saleor/webhook/migrations/0003_unmount_service_account.py@@@ -1,22 -1,0 +1,22 @@@+# Generated by Django 3.0.5 on 2020-04-16 06:01++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("webhook", "0002_webhook_name"),- ("account", "0042_rename_service_account_to_app"),++ ("account", "0043_rename_service_account_to_app"),+ ]++ state_operations = [+ migrations.RemoveField(model_name="webhook", name="app",),+ ]++ operations = [+ migrations.RenameField(+ model_name="webhook", old_name="service_account", new_name="app"+ ),+ migrations.SeparateDatabaseAndState(state_operations=state_operations),+ ]diff --cc tests/api/pagination/test_app.pyindex 4e8101d1b2,0000000000..254f565792mode 100644,000000..100644--- a/tests/api/pagination/test_app.py+++ b/tests/api/pagination/test_app.py@@@ -1,97 -1,0 +1,97 @@@+import pytest++from saleor.app.models import App++from ..utils import get_graphql_content+++def apps_for_pagination():+ apps = App.objects.bulk_create(+ [+ App(name="Account1", is_active=True),+ App(name="AccountAccount1", is_active=True),+ App(name="AccountAccount2", is_active=True),+ App(name="Account2", is_active=True),+ App(name="Account3", is_active=True),+ ]+ )+ return apps+++QUERY_APP_PAGINATION = """+ query (+ $first: Int, $last: Int, $after: String, $before: String,+ $sortBy: AppSortingInput, $filter: AppFilterInput+ ){+ apps(+ first: $first, last: $last, after: $after, before: $before,+ sortBy: $sortBy, filter: $filter+ ) {+ edges{+ node{+ name+ }+ }+ pageInfo{+ startCursor+ endCursor+ hasNextPage+ hasPreviousPage+ }+ }+ }+"""+++ "sort_by, apps_order",+ [+ ({"field": "NAME", "direction": "ASC"}, ["Account1", "Account2", "Account3"]),+ (+ {"field": "NAME", "direction": "DESC"},+ ["AccountAccount2", "AccountAccount1", "Account3"],+ ),+ ],+)+def test_apps_pagination_with_sorting(+ sort_by, apps_order, staff_api_client, apps_for_pagination, permission_manage_apps,+):+ staff_api_client.user.user_permissions.add(permission_manage_apps)+ page_size = 3+ variables = {"first": page_size, "after": None, "sortBy": sort_by}+ response = staff_api_client.post_graphql(QUERY_APP_PAGINATION, variables,)+ content = get_graphql_content(response)+ nodes = content["data"]["apps"]["edges"]+ assert apps_order[0] == nodes[0]["node"]["name"]+ assert apps_order[1] == nodes[1]["node"]["name"]+ assert apps_order[2] == nodes[2]["node"]["name"]+ assert len(nodes) == page_size+++ "filter_by, apps_order",+ [- ({"search": "Account"}, ["Account1", "AccountAccount1"]),++ ({"search": "Account"}, ["Account1", "Account2"]),+ ({"search": "AccountAccount"}, ["AccountAccount1", "AccountAccount2"]),+ ({"search": "accountaccount"}, ["AccountAccount1", "AccountAccount2"]),+ ({"search": "Account1"}, ["Account1", "AccountAccount1"]),+ ],+)+def test_apps_pagination_with_filtering(+ filter_by,+ apps_order,+ staff_api_client,+ apps_for_pagination,+ permission_manage_apps,+):+ staff_api_client.user.user_permissions.add(permission_manage_apps)+ page_size = 2+ variables = {"first": page_size, "after": None, "filter": filter_by}+ response = staff_api_client.post_graphql(QUERY_APP_PAGINATION, variables,)+ content = get_graphql_content(response)++ nodes = content["data"]["apps"]["edges"]+ assert apps_order[0] == nodes[0]["node"]["name"]+ assert apps_order[1] == nodes[1]["node"]["name"]+ assert len(nodes) == page_sizediff --cc tests/api/pagination/test_webhook.pyindex 27af3a2ad5,fa99989cd0..1ce72fda13--- a/tests/api/pagination/test_webhook.py+++ b/tests/api/pagination/test_webhook.py@@@ -76,9 -81,9 +76,13 @@@ QUERY_WEBHOOKS_PAGINATION = ""{"field": "NAME", "direction": "DESC"},["WebhookWebhook2", "WebhookWebhook1", "Webhook3"],),+ (+ {"field": "APP", "direction": "ASC"},- ["Webhook3", "WebhookWebhook1", "Webhook2"],++ ["Webhook3", "WebhookWebhook1", "Webhook1"],++ ),+ (+ {"field": "SERVICE_ACCOUNT", "direction": "ASC"},+ ["Webhook3", "WebhookWebhook1", "Webhook1"],),({"field": "TARGET_URL", "direction": "ASC"},diff --cc tests/api/test_webhook.pyindex 038fe4d273,65b7af1eb5..bb0b902a38--- a/tests/api/test_webhook.py+++ b/tests/api/test_webhook.py@@@ -412,8 -445,14 +412,8 @@@ QUERY_WEBHOOKS_WITH_SORT = ""[({"field": "NAME", "direction": "ASC"}, ["backup", "hook1", "hook2"]),({"field": "NAME", "direction": "DESC"}, ["hook2", "hook1", "backup"]),- (- {"field": "SERVICE_ACCOUNT", "direction": "ASC"},- ["hook2", "backup", "hook1"],- ),- (- {"field": "SERVICE_ACCOUNT", "direction": "DESC"},- ["hook1", "backup", "hook2"],- ),+ ({"field": "APP", "direction": "ASC"}, ["hook2", "backup", "hook1"],),- ({"field": "APP", "direction": "DESC"}, ["backup", "hook1", "hook2"],),++ ({"field": "APP", "direction": "DESC"}, ["hook1", "backup", "hook2"],),({"field": "TARGET_URL", "direction": "ASC"}, ["hook2", "hook1", "backup"]),({"field": "TARGET_URL", "direction": "DESC"}, ["backup", "hook1", "hook2"]),],@@@ -439,7 -486,7 +439,6 @@@ def test_query_webhooks_with_sortresponse = staff_api_client.post_graphql(QUERY_WEBHOOKS_WITH_SORT, variables)content = get_graphql_content(response)webhooks = content["data"]["webhooks"]["edges"]--for order, webhook_name in enumerate(result_order):assert webhooks[order]["node"]["name"] == webhook_namediff --cc tests/api/test_webhook_deprecated_service_account.pyindex 646d492519,0000000000..2f5eaaecf8mode 100644,000000..100644--- a/tests/api/test_webhook_deprecated_service_account.py+++ b/tests/api/test_webhook_deprecated_service_account.py@@@ -1,113 -1,0 +1,113 @@@+import graphene+import pytest++from saleor.app.models import App+from saleor.graphql.webhook.enums import WebhookEventTypeEnum+from saleor.webhook.models import Webhook++from .test_webhook import QUERY_WEBHOOKS_WITH_SORT+from .utils import assert_no_permission, get_graphql_content++WEBHOOK_CREATE_BY_STAFF = """+ mutation webhookCreate(+ $target_url: String, $events: [WebhookEventTypeEnum], $service_account: ID){+ webhookCreate(input:{+ targetUrl:$target_url, events:$events, serviceAccount: $service_account}){+ errors{+ field+ message+ }+ webhook{+ id+ }+ }+ }+"""+++def test_webhook_create_by_staff_and_service_account(+ staff_api_client, app, permission_manage_webhooks, permission_manage_orders,+):+ query = WEBHOOK_CREATE_BY_STAFF+ app.permissions.add(permission_manage_orders)+ service_account_id = graphene.Node.to_global_id("ServiceAccount", app.pk)+ variables = {+ "target_url": "https://www.example.com",+ "events": [WebhookEventTypeEnum.ORDER_CREATED.name],+ "service_account": service_account_id,+ }+ staff_api_client.user.user_permissions.add(permission_manage_webhooks)+ response = staff_api_client.post_graphql(query, variables=variables)+ get_graphql_content(response)+ new_webhook = Webhook.objects.get()+ assert new_webhook.target_url == "https://www.example.com"+ assert new_webhook.app == app+ events = new_webhook.events.all()+ assert len(events) == 1+ assert events[0].event_type == WebhookEventTypeEnum.ORDER_CREATED.value+++def test_webhook_create_by_staff_with_inactive_service_account(staff_api_client, app):+ app.is_active = False+ query = WEBHOOK_CREATE_BY_STAFF+ service_account_id = graphene.Node.to_global_id("ServiceAccount", app.pk)+ variables = {+ "target_url": "https://www.example.com",+ "events": [WebhookEventTypeEnum.ORDER_CREATED.name],+ "service_account": service_account_id,+ }+ response = staff_api_client.post_graphql(query, variables=variables)+ assert_no_permission(response)+ assert Webhook.objects.count() == 0+++def test_webhook_create_by_staff_for_sa_without_permission(staff_api_client, app):+ query = WEBHOOK_CREATE_BY_STAFF+ service_account_id = graphene.Node.to_global_id("ServiceAccount", app.pk)+ variables = {+ "target_url": "https://www.example.com",+ "events": [WebhookEventTypeEnum.ORDER_CREATED.name],+ "service_account": service_account_id,+ }+ response = staff_api_client.post_graphql(query, variables=variables)+ assert_no_permission(response)+ assert Webhook.objects.count() == 0+++ "webhooks_sort, result_order",+ [+ (+ {"field": "SERVICE_ACCOUNT", "direction": "ASC"},+ ["hook2", "backup", "hook1"],+ ),+ (+ {"field": "SERVICE_ACCOUNT", "direction": "DESC"},- ["backup", "hook1", "hook2"],++ ["hook1", "backup", "hook2"],+ ),+ ],+)+def test_query_webhooks_with_sort(+ webhooks_sort, result_order, staff_api_client, permission_manage_webhooks+):+ backupApp = App.objects.create(name="backupApp", is_active=True)+ app = App.objects.create(name="app", is_active=True)+ Webhook.objects.bulk_create(+ [+ Webhook(+ name="hook1", app=backupApp, target_url="http://example.com/activate2",+ ),+ Webhook(name="hook2", app=app, target_url="http://example.com/activate",),+ Webhook(+ name="backup", app=backupApp, target_url="http://example.com/backup",+ ),+ ]+ )+ variables = {"sort_by": webhooks_sort}+ staff_api_client.user.user_permissions.add(permission_manage_webhooks)+ response = staff_api_client.post_graphql(QUERY_WEBHOOKS_WITH_SORT, variables)+ content = get_graphql_content(response)+ webhooks = content["data"]["webhooks"]["edges"]++ for order, webhook_name in enumerate(result_order):+ assert webhooks[order]["node"]["name"] == webhook_name