Skip to content

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

[RFC] Channel permissions (#10423)

Filip Owczarek5a5cd315917c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dd41f3c95a..e3f9f95777 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,8 +20,15 @@ All notable, unreleased changes to this project will be documented in this file.
- `accountUpdate`
- `customerBulkUpdate`
- Allow setting metadata during invoice creating and updating - #12641 by @IKarbowiak
+- Introduce channel permissions - #10423 by @IKarbowiak
+ - Limit staff users to access only certain channels. Granted permissions only apply to channels that the user has already been given access to.
### Saleor Apps
+- Introduce channel permissions - #10423 by @IKarbowiak
+ - Extend the OpenID connect configuration with `Staff user domains` and `Default permission group name for new staff users`.
+ - When the OpenID plugin is active, the default staff permission group is created and all staff users are assigned to it.
+ - To ensure the proper functioning of OAuth permissions, ensure that the
+ `Default permission group name for new staff users` is set to a permission group with no channel restrictions.
### Other changes
- Fix saving `description_plaintext` for product - #12586 by @SzymJ
diff --git a/saleor/account/error_codes.py b/saleor/account/error_codes.py
index b8df987ae8..c5a10b62af 100644
--- a/saleor/account/error_codes.py
+++ b/saleor/account/error_codes.py
@@ -50,11 +50,12 @@ class CustomerBulkUpdateErrorCode(Enum):
class PermissionGroupErrorCode(Enum):
+ REQUIRED = "required"
+ UNIQUE = "unique"
ASSIGN_NON_STAFF_MEMBER = "assign_non_staff_member"
DUPLICATED_INPUT_ITEM = "duplicated_input_item"
CANNOT_REMOVE_FROM_LAST_GROUP = "cannot_remove_from_last_group"
LEFT_NOT_MANAGEABLE_PERMISSION = "left_not_manageable_permission"
OUT_OF_SCOPE_PERMISSION = "out_of_scope_permission"
OUT_OF_SCOPE_USER = "out_of_scope_user"
- REQUIRED = "required"
- UNIQUE = "unique"
+ OUT_OF_SCOPE_CHANNEL = "out_of_scope_channel"
diff --git a/saleor/account/migrations/0078_add_group_channels_conf.py b/saleor/account/migrations/0078_add_group_channels_conf.py
new file mode 100644
index 0000000000..cbb7c3f44a
--- /dev/null
+++ b/saleor/account/migrations/0078_add_group_channels_conf.py
@@ -0,0 +1,30 @@
+# Generated by Django 3.2.18 on 2023-03-09 15:40
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("channel", "0008_update_null_order_settings"),
+ ("account", "0077_merge_20230310_1107"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="group",
+ name="channels",
+ field=models.ManyToManyField(blank=True, to="channel.Channel"),
+ ),
+ migrations.AddField(
+ model_name="group",
+ name="restricted_access_to_channels",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE account_group
+ ALTER COLUMN restricted_access_to_channels
+ SET DEFAULT false;
+ """
+ ),
+ ]
diff --git a/saleor/account/migrations/0079_full_channel_access_group_for_openid.py b/saleor/account/migrations/0079_full_channel_access_group_for_openid.py
new file mode 100644
index 0000000000..8608478a09
--- /dev/null
+++ b/saleor/account/migrations/0079_full_channel_access_group_for_openid.py
@@ -0,0 +1,93 @@
+# Generated by Django 3.2.18 on 2023-03-24 14:14
+
+from django.db import migrations
+from django.db.models import OuterRef, Exists, Q
+from django.apps import apps as registry
+from django.db.models.signals import post_migrate
+
+OPENID_ID = "mirumee.authentication.openidconnect"
+
+# The batch of size 5000 took about 0.5 s to assign users to groups
+BATCH_SIZE = 5000
+
+
+def create_full_channel_access_group_for_openid(apps, schema_editor):
+ group_name = "OpenID default group"
+ User = apps.get_model("account", "User")
+ Group = apps.get_model("account", "Group")
+
+ def on_migrations_complete(sender=None, **kwargs):
+ create_full_channel_access_group_task(User, Group, group_name)
+
+ PluginConfiguration = apps.get_model("plugins", "PluginConfiguration")
+ plugin_conf = PluginConfiguration.objects.filter(
+ active=True, identifier=OPENID_ID
+ ).first()
+ if plugin_conf:
+ Group = apps.get_model("account", "Group")
+ Group.objects.get_or_create(
+ name=group_name, restricted_access_to_channels=False
+ )
+ update_plugin_default_group_name(plugin_conf, group_name)
+
+ sender = registry.get_app_config("account")
+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+
+
+def update_plugin_default_group_name(plugin_conf, group_name):
+ default_group_name_field = "default_group_name_for_new_staff_users"
+ for conf in plugin_conf.configuration:
+ if conf["name"] == default_group_name_field:
+ conf.update([("value", group_name)])
+ plugin_conf.save(update_fields=["configuration"])
+ return
+
+ group_conf = {"name": default_group_name_field, "value": group_name}
+ plugin_conf.configuration.append(group_conf)
+ plugin_conf.save(update_fields=["configuration"])
+
+
+def create_full_channel_access_group_task(User, Group, group_name):
+ full_channel_access_group, _ = Group.objects.get_or_create(
+ name=group_name, defaults={"restricted_access_to_channels": False}
+ )
+ GroupUser = User.groups.through
+ group_users = GroupUser.objects.filter(group_id=full_channel_access_group.id)
+ users = User.objects.filter(
+ Q(is_staff=True) & ~Exists(group_users.filter(user_id=OuterRef("id")))
+ )
+ for user_ids in queryset_in_batches(users):
+ if user_ids:
+ full_channel_access_group.user_set.add(*user_ids)
+
+
+def queryset_in_batches(queryset):
+ """Slice a queryset into batches.
+
+ Input queryset should be sorted be pk.
+ """
+ start_pk = 0
+
+ while True:
+ qs = queryset.order_by("pk").filter(pk__gt=start_pk)[:BATCH_SIZE]
+ pks = list(qs.values_list("pk", flat=True))
+
+ if not pks:
+ break
+
+ yield pks
+
+ start_pk = pks[-1]
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("account", "0078_add_group_channels_conf"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ create_full_channel_access_group_for_openid,
+ reverse_code=migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/account/models.py b/saleor/account/models.py
index 1fc940facf..a92e80ce4c 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -396,6 +396,8 @@ class Group(models.Model):
verbose_name="permissions",
blank=True,
)
+ restricted_access_to_channels = models.BooleanField(default=False)
+ channels = models.ManyToManyField("channel.Channel", blank=True)
objects = GroupManager()
diff --git a/saleor/account/tests/test_utils.py b/saleor/account/tests/test_utils.py
index f3f9f5af68..b8bc0d6aeb 100644
--- a/saleor/account/tests/test_utils.py
+++ b/saleor/account/tests/test_utils.py
@@ -8,6 +8,7 @@ from ...checkout import AddressType
from ...plugins.manager import get_plugins_manager
from ..models import Address, User
from ..utils import (
+ get_user_groups_permissions,
is_user_address_limit_reached,
remove_staff_member,
remove_the_oldest_user_address,
@@ -231,3 +232,26 @@ def test_email_case_sensitivity(email, expected_user, users_with_similar_emails)
user = retrieve_user_by_email(email=email)
# then
assert user == users[expected_user] if expected_user is not None else user is None
+
+
+def get_user_groups_permissions_user_without_any_group(staff_user):
+ # when
+ permissions = get_user_groups_permissions(staff_user)
+
+ # then
+ assert not permissions
+
+
+def get_user_groups_permissions_user(
+ staff_user, permission_group_manage_orders, permission_group_manage_shipping
+):
+ # given
+ staff_user.groups.add(
+ permission_group_manage_orders, permission_group_manage_shipping
+ )
+
+ # when
+ permissions = get_user_groups_permissions(staff_user)
+
+ # then
+ assert permissions.count() == 2
diff --git a/saleor/account/utils.py b/saleor/account/utils.py
index de823e2f97..87496f877f 100644
--- a/saleor/account/utils.py
+++ b/saleor/account/utils.py
@@ -1,9 +1,11 @@
from typing import TYPE_CHECKING
from django.conf import settings
+from django.db.models import Exists, OuterRef
from ..checkout import AddressType
-from .models import User
+from ..permission.models import Permission
+from .models import Group, User
if TYPE_CHECKING:
from ..plugins.manager import PluginsManager
@@ -129,3 +131,15 @@ def retrieve_user_by_email(email):
if users:
return users[0]
return None
+
+
+def get_user_groups_permissions(user: User):
+ GroupUser = User.groups.through
+ group_users = GroupUser.objects.filter(user_id=user.id).values("group_id")
+ GroupPermissions = Group.permissions.through
+ group_permissions = GroupPermissions.objects.filter(
+ Exists(group_users.filter(group_id=OuterRef("group_id")))
+ ).values("permission_id")
+ return Permission.objects.filter(
+ Exists(group_permissions.filter(permission_id=OuterRef("id")))
+ )
diff --git a/saleor/graphql/account/dataloaders.py b/saleor/graphql/account/dataloaders.py
index 0a4996e009..72d79f7eb9 100644
--- a/saleor/graphql/account/dataloaders.py
+++ b/saleor/graphql/account/dataloaders.py
@@ -1,7 +1,8 @@
from collections import defaultdict
-from typing import DefaultDict, Iterable, Optional, Tuple, cast
+from typing import DefaultDict, Iterable, List, Optional, Set, Tuple, cast
-from ...account.models import Address, CustomerEvent, User
+from ...account.models import Address, CustomerEvent, Group, User
+from ...channel.models import Channel
from ...permission.models import Permission
from ...thumbnail.models import Thumbnail
from ...thumbnail.utils import get_thumbnail_format
@@ -80,3 +81,104 @@ class PermissionByCodenameLoader(DataLoader):
.in_bulk(field_name="codename")
)
return [permission_map.get(codename) for codename in keys]
+
+
+class BaseAccessibleChannels(DataLoader):
+ def get_group_to_channels_map(self, group_ids):
+ groups_with_no_channel_restriction = Group.objects.using(
+ self.database_connection_name
+ ).filter(id__in=group_ids, restricted_access_to_channels=False)
+ groups_with_channel_restriction = Group.objects.using(
+ self.database_connection_name
+ ).filter(id__in=group_ids, restricted_access_to_channels=True)
+
+ group_to_channels: DefaultDict[int, List["Channel"]] = defaultdict(list)
+ if groups_with_channel_restriction:
+ group_to_channels = self.get_group_channels(
+ groups_with_channel_restriction.values("id"),
+ group_to_channels,
+ )
+
+ if groups_with_no_channel_restriction:
+ channels = list(Channel.objects.using(self.database_connection_name).all())
+ for group_id in groups_with_no_channel_restriction.values_list(
+ "id", flat=True
+ ):
+ group_to_channels[group_id] = channels
+
+ return group_to_channels
+
+ def get_group_channels(self, group_ids, group_to_channels):
+ GroupChannels = Group.channels.through
+ group_channels = GroupChannels.objects.using(
+ self.database_connection_name
+ ).filter(group_id__in=group_ids)
+ channels_in_bulk = Channel.objects.using(self.database_connection_name).in_bulk(
+ list(group_channels.values_list("channel_id", flat=True))
+ )
+
+ for group_id, channel_id in group_channels.values_list(
+ "group_id", "channel_id"
+ ):
+ group_to_channels[group_id].append(channels_in_bulk[channel_id])
+
+ return group_to_channels
+
+
+class AccessibleChannelsByGroupIdLoader(BaseAccessibleChannels):
+ context_key = "accessiblechannels_by_group"
+
+ def batch_load(self, keys):
+ group_to_channels = self.get_group_to_channels_map(keys)
+ return [group_to_channels.get(group_id, []) for group_id in keys]
+
+
+class AccessibleChannelsByUserIdLoader(BaseAccessibleChannels):
+ context_key = "accessiblechannels_by_user"
+
+ def batch_load(self, keys):
+ UserGroup = User.groups.through
+ user_groups = UserGroup.objects.using(self.database_connection_name).filter(
+ user_id__in=keys
+ )
+ groups = Group.objects.using(self.database_connection_name).filter(
+ id__in=user_groups.values("group_id")
+ )
+
+ group_to_channels = self.get_group_to_channels_map(
+ groups.values_list("id", flat=True)
+ )
+
+ user_to_channels: DefaultDict[int, Set["Channel"]] = defaultdict(set)
+ for user_id, group_id in user_groups.values_list("user_id", "group_id"):
+ user_to_channels[user_id].update(group_to_channels[group_id])
+
+ return [list(user_to_channels[user_id]) for user_id in keys]
+
+
+class RestrictedChannelAccessByUserIdLoader(DataLoader):
+ context_key = "restrictedchannelaccess_by_user"
+
+ def batch_load(self, keys):
+ UserGroup = User.groups.through
+ user_groups = UserGroup.objects.using(self.database_connection_name).filter(
+ user_id__in=keys
+ )
+ groups = Group.objects.using(self.database_connection_name).filter(
+ id__in=user_groups.values("group_id")
+ )
+
+ group_id_to_restricted_access = {
+ group_id: restricted_access
+ for group_id, restricted_access in groups.values_list(
+ "id", "restricted_access_to_channels"
+ )
+ }
+
+ user_to_restricted_access: DefaultDict[int, bool] = defaultdict(lambda: True)
+ for user_id, group_id in user_groups.values_list("user_id", "group_id"):
+ user_to_restricted_access[user_id] &= group_id_to_restricted_access[
+ group_id
+ ]
+
+ return [user_to_restricted_access[user_id] for user_id in keys]
diff --git a/saleor/graphql/account/mutations/permission_group.py b/saleor/graphql/account/mutations/permission_group.py
index 9466898a68..86ebd136ab 100644
--- a/saleor/graphql/account/mutations/permission_group.py
+++ b/saleor/graphql/account/mutations/permission_group.py
@@ -7,25 +7,30 @@ from django.core.exceptions import ValidationError
from ....account import models
from ....account.error_codes import PermissionGroupErrorCode
from ....account.models import User
+from ....channel.models import Channel
from ....core.exceptions import PermissionDenied
from ....core.tracing import traced_atomic_transaction
from ....permission.enums import AccountPermissions, get_permissions
from ...account.utils import (
- can_user_manage_group,
+ can_user_manage_group_channels,
+ can_user_manage_group_permissions,
get_not_manageable_permissions_after_group_deleting,
get_not_manageable_permissions_after_removing_perms_from_group,
get_not_manageable_permissions_after_removing_users_from_group,
get_out_of_scope_permissions,
get_out_of_scope_users,
+ get_user_accessible_channels,
)
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
+from ...core.descriptions import ADDED_IN_314, PREVIEW_FEATURE
from ...core.doc_category import DOC_CATEGORY_USERS
from ...core.enums import PermissionEnum
from ...core.mutations import ModelDeleteMutation, ModelMutation
from ...core.types import BaseInputObjectType, NonNullList, PermissionGroupError
from ...plugins.dataloaders import get_plugin_manager_promise
from ...utils.validators import check_for_duplicates
+from ..dataloaders import AccessibleChannelsByGroupIdLoader
from ..types import Group
@@ -40,6 +45,12 @@ class PermissionGroupInput(BaseInputObjectType):
description="List of users to assign to this group.",
required=False,
)
+ add_channels = NonNullList(
+ graphene.ID,
+ description="List of channels to assign to this group."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE,
+ )
class Meta:
doc_category = DOC_CATEGORY_USERS
@@ -47,6 +58,15 @@ class PermissionGroupInput(BaseInputObjectType):
class PermissionGroupCreateInput(PermissionGroupInput):
name = graphene.String(description="Group name.", required=True)
+ restricted_access_to_channels = graphene.Boolean(
+ description=(
+ "Determine if the group has restricted access to channels. DEFAULT: False"
+ )
+ + ADDED_IN_314
+ + PREVIEW_FEATURE,
+ default_value=False,
+ required=False,
+ )
class Meta:
doc_category = DOC_CATEGORY_USERS
@@ -72,15 +92,19 @@ class PermissionGroupCreate(ModelMutation):
@classmethod
def _save_m2m(cls, info: ResolveInfo, instance, cleaned_data):
- add_permissions = cleaned_data.get("add_permissions")
with traced_atomic_transaction():
- if add_permissions:
+ if add_permissions := cleaned_data.get("add_permissions"):
instance.permissions.add(*add_permissions)
- users = cleaned_data.get("add_users")
- if users:
+ if users := cleaned_data.get("add_users"):
instance.user_set.add(*users)
+ if cleaned_data.get("restricted_access_to_channels") is False:
+ instance.channels.clear()
+
+ if channels := cleaned_data.get("add_channels"):
+ instance.channels.add(*channels)
+
@classmethod
def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
manager = get_plugin_manager_promise(info.context).get()
@@ -93,6 +117,10 @@ class PermissionGroupCreate(ModelMutation):
user = info.context.user
user = cast(User, user)
errors: defaultdict[str, List[ValidationError]] = defaultdict(list)
+ user_accessible_channels = get_user_accessible_channels(info, info.context.user)
+ cls.clean_channels(
+ info, instance, user_accessible_channels, errors, cleaned_input
+ )
cls.clean_permissions(user, instance, errors, cleaned_input)
cls.clean_users(user, errors, cleaned_input, instance)
@@ -177,6 +205,67 @@ class PermissionGroupCreate(ModelMutation):
params = {"users": ids}
cls.update_errors(errors, error_msg, field, code, params)
+ @classmethod
+ def clean_channels(
+ cls,
+ info: ResolveInfo,
+ group: models.Group,
+ user_accessible_channels: List["Channel"],
+ errors: dict,
+ cleaned_input: dict,
+ ):
+ """Clean adding channels when the group hasn't restricted access to channels."""
+ user = info.context.user
+ user = cast(User, user)
+ if cleaned_input.get("restricted_access_to_channels") is False:
+ if not user.is_superuser:
+ channel_ids = set(Channel.objects.values_list("id", flat=True))
+ accessible_channel_ids = {
+ channel.id for channel in user_accessible_channels
+ }
+ not_accessible_channels = set(channel_ids - accessible_channel_ids)
+ error_code = PermissionGroupErrorCode.OUT_OF_SCOPE_CHANNEL.value
+ if not_accessible_channels:
+ raise ValidationError(
+ {
+ "restricted_access_to_channels": ValidationError(
+ "You can't manage group with channels out of "
+ "your scope.",
+ code=error_code,
+ )
+ }
+ )
+ cleaned_input["add_channels"] = []
+ elif add_channels := cleaned_input.get("add_channels"):
+ cls.ensure_can_manage_channels(
+ user, user_accessible_channels, errors, add_channels
+ )
+
+ @classmethod
+ def ensure_can_manage_channels(
+ cls,
+ user: "User",
+ user_accessible_channels: List["Channel"],
+ errors: dict,
+ channels: List["Channel"],
+ ):
+ # user must have access to all channels from `add_channels` list
+ if user.is_superuser:
+ return
+ channel_ids = {str(channel.id) for channel in channels}
+ accessible_channel_ids = {
+ str(channel.id) for channel in user_accessible_channels
+ }
+ invalid_channel_ids = channel_ids - accessible_channel_ids
+ if invalid_channel_ids:
+ ids = [
+ graphene.Node.to_global_id("Channel", pk) for pk in invalid_channel_ids
+ ]
+ error_msg = "You can't add channel that you don't have access to."
+ code = PermissionGroupErrorCode.OUT_OF_SCOPE_CHANNEL.value
+ params = {"channels": ids}
+ cls.update_errors(errors, error_msg, "add_channels", code, params)
+
@classmethod
def update_errors(
cls,
@@ -203,6 +292,18 @@ class PermissionGroupUpdateInput(PermissionGroupInput):
description="List of users to unassign from this group.",
required=False,
)
+ remove_channels = NonNullList(
+ graphene.ID,
+ description="List of channels to unassign from this group."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE,
+ )
+ restricted_access_to_channels = graphene.Boolean(
+ description="Determine if the group has restricted access to channels."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE,
+ required=False,
+ )
class Meta:
doc_category = DOC_CATEGORY_USERS
@@ -230,13 +331,14 @@ class PermissionGroupUpdate(PermissionGroupCreate):
def _save_m2m(cls, info: ResolveInfo, instance, cleaned_data):
with traced_atomic_transaction():
super()._save_m2m(info, instance, cleaned_data)
- remove_users = cleaned_data.get("remove_users")
- with traced_atomic_transaction():
- if remove_users:
- instance.user_set.remove(*remove_users)
- remove_permissions = cleaned_data.get("remove_permissions")
- if remove_permissions:
- instance.permissions.remove(*remove_permissions)
+ if remove_users := cleaned_data.get("remove_users"):
+ instance.user_set.remove(*remove_users)
+ if remove_permissions := cleaned_data.get("remove_permissions"):
+ instance.permissions.remove(*remove_permissions)
+ if remove_channels := cleaned_data.get("remove_channels"):
+ instance.channels.remove(*remove_channels)
+ # Invalidate dataloader for group channels
+ AccessibleChannelsByGroupIdLoader(info.context).clear(instance.id)
@classmethod
def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
@@ -251,14 +353,16 @@ class PermissionGroupUpdate(PermissionGroupCreate):
data,
):
requestor = info.context.user
- cls.ensure_requestor_can_manage_group(requestor, instance)
+ cls.ensure_requestor_can_manage_group(info, requestor, instance)
errors: DefaultDict[str, List[ValidationError]] = defaultdict(list)
permission_fields = ("add_permissions", "remove_permissions", "permissions")
user_fields = ("add_users", "remove_users", "users")
+ channel_fields = ("add_channels", "remove_channels", "channels")
cls.check_duplicates(errors, data, permission_fields)
cls.check_duplicates(errors, data, user_fields)
+ cls.check_duplicates(errors, data, channel_fields)
if errors:
raise ValidationError(errors)
@@ -268,15 +372,50 @@ class PermissionGroupUpdate(PermissionGroupCreate):
return cleaned_input
@classmethod
- def ensure_requestor_can_manage_group(cls, requestor: "User", group: models.Group):
+ def ensure_requestor_can_manage_group(
+ cls, info: ResolveInfo, requestor: "User", group: models.Group
+ ):
"""Check if requestor can manage group.
- Requestor cannot manage group with wider scope of permissions.
+ Requestor cannot manage group with wider scope of permissions or channels.
"""
- if not requestor.is_superuser and not can_user_manage_group(requestor, group):
+ if requestor.is_superuser:
+ return
+ if not can_user_manage_group_permissions(requestor, group):
error_msg = "You can't manage group with permissions out of your scope."
code = PermissionGroupErrorCode.OUT_OF_SCOPE_PERMISSION.value
raise ValidationError(error_msg, code)
+ if not can_user_manage_group_channels(info, requestor, group):
+ error_msg = "You can't manage group with channels out of your scope."
+ code = PermissionGroupErrorCode.OUT_OF_SCOPE_CHANNEL.value
+ raise ValidationError(error_msg, code)
+
+ @classmethod
+ def clean_channels(
+ cls,
+ info: ResolveInfo,
+ group: models.Group,
+ user_accessible_channels: List["Channel"],
+ errors: dict,
+ cleaned_input: dict,
+ ):
+ """Clean channels when the group hasn't restricted access to channels."""
+ super().clean_channels(
+ info, group, user_accessible_channels, errors, cleaned_input
+ )
+ if remove_channels := cleaned_input.get("remove_channels"):
+ user = info.context.user
+ user = cast(User, user)
+ cls.ensure_can_manage_channels(
+ user, user_accessible_channels, errors, remove_channels
+ )
+
+ restricted_access = cleaned_input.get("restricted_access_to_channels")
+ if restricted_access is False or (
+ restricted_access is None and group.restricted_access_to_channels is False
+ ):
+ cleaned_input["add_channels"] = []
+ cleaned_input["remove_channels"] = []
@classmethod
def clean_permissions(
@@ -467,10 +606,14 @@ class PermissionGroupDelete(ModelDeleteMutation):
raise PermissionDenied("You must be authenticated to perform this action.")
if requestor.is_superuser:
return
- if not can_user_manage_group(requestor, instance):
+ if not can_user_manage_group_permissions(requestor, instance):
error_msg = "You can't manage group with permissions out of your scope."
code = PermissionGroupErrorCode.OUT_OF_SCOPE_PERMISSION.value
raise ValidationError(error_msg, code)
+ if not can_user_manage_group_channels(info, requestor, instance):
+ error_msg = "You can't manage group with channels out of your scope."
+ code = PermissionGroupErrorCode.OUT_OF_SCOPE_CHANNEL.value
+ raise ValidationError(error_msg, code)
cls.check_if_group_can_be_removed(requestor, instance)
diff --git a/saleor/graphql/account/tests/benchmark/test_permission_group.py b/saleor/graphql/account/tests/benchmark/test_permission_group.py
index 648717406a..db890373a9 100644
--- a/saleor/graphql/account/tests/benchmark/test_permission_group.py
+++ b/saleor/graphql/account/tests/benchmark/test_permission_group.py
@@ -12,11 +12,16 @@ def test_permission_group_create(
staff_user,
permission_manage_staff,
staff_api_client,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_users,
+ permission_group_manage_apps,
+ permission_group_manage_staff,
count_queries,
):
- staff_user.user_permissions.add(permission_manage_users, permission_manage_apps)
+ staff_user.groups.add(
+ permission_group_manage_users,
+ permission_group_manage_apps,
+ permission_group_manage_staff,
+ )
query = """
mutation PermissionGroupCreate(
$input: PermissionGroupCreateInput!) {
@@ -54,9 +59,7 @@ def test_permission_group_create(
"addUsers": [graphene.Node.to_global_id("User", staff_user.id)],
}
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=(permission_manage_staff,)
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["permissionGroupCreate"]
diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.py
index bdfcab07c6..1f4514c9ee 100644
--- a/saleor/graphql/account/tests/test_account.py
+++ b/saleor/graphql/account/tests/test_account.py
@@ -27,6 +27,7 @@ from ....account.search import (
generate_user_fields_search_document_value,
prepare_user_search_document_value,
)
+from ....channel.models import Channel
from ....checkout import AddressType
from ....core.jwt import create_token
from ....core.notify_events import NotifyEventType
@@ -139,6 +140,7 @@ FULL_USER_QUERY = """
edges {
node {
id
+ number
}
}
}
@@ -197,6 +199,10 @@ FULL_USER_QUERY = """
editableGroups {
name
}
+ restrictedAccessToChannels
+ accessibleChannels {
+ slug
+ }
giftCards(first: 10) {
edges {
node {
@@ -261,6 +267,8 @@ def test_query_customer_user(
assert data["avatar"]["url"]
assert data["languageCode"] == settings.LANGUAGE_CODE.upper()
assert len(data["editableGroups"]) == 0
+ assert data["restrictedAccessToChannels"] is True
+ assert len(data["accessibleChannels"]) == 0
assert len(data["addresses"]) == user.addresses.count()
for address in data["addresses"]:
@@ -320,8 +328,8 @@ def test_query_customer_user_with_orders(
staff_api_client,
customer_user,
order_list,
+ permission_group_manage_orders,
permission_manage_users,
- permission_manage_orders,
):
# given
query = FULL_USER_QUERY
@@ -342,12 +350,12 @@ def test_query_customer_user_with_orders(
id = graphene.Node.to_global_id("User", customer_user.id)
variables = {"id": id}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(
query,
variables,
- permissions=[permission_manage_users, permission_manage_orders],
)
# then
@@ -463,6 +471,53 @@ def test_query_customer_user_with_orders_by_app_no_manage_orders_perm(
assert_no_permission(response)
+def test_query_customer_user_with_orders_restricted_access_to_channel(
+ staff_api_client,
+ customer_user,
+ order_list,
+ permission_group_all_perms_channel_USD_only,
+ channel_USD,
+ channel_PLN,
+ channel_JPY,
+):
+ # given
+ query = FULL_USER_QUERY
+ order_unfulfilled = order_list[0]
+ order_unfulfilled.user = customer_user
+ order_unfulfilled.channel = channel_PLN
+
+ order_unconfirmed = order_list[1]
+ order_unconfirmed.status = OrderStatus.UNCONFIRMED
+ order_unconfirmed.user = customer_user
+ order_unconfirmed.channel = channel_USD
+
+ order_draft = order_list[2]
+ order_draft.status = OrderStatus.DRAFT
+ order_draft.user = customer_user
+ order_draft.channel = channel_JPY
+
+ Order.objects.bulk_update(
+ [order_unconfirmed, order_draft, order_unfulfilled],
+ ["user", "status", "channel"],
+ )
+
+ id = graphene.Node.to_global_id("User", customer_user.id)
+ variables = {"id": id}
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ user = content["data"]["user"]
+ assert len(user["orders"]["edges"]) == 1
+ assert user["orders"]["edges"][0]["node"]["number"] == str(order_unconfirmed.number)
+
+
def test_query_staff_user(
staff_api_client,
staff_user,
@@ -526,6 +581,8 @@ def test_query_staff_user(
group2.name,
group4.name,
}
+ assert data["restrictedAccessToChannels"] is False
+ assert len(data["accessibleChannels"]) == Channel.objects.count()
formated_user_permissions_result = [
{
@@ -546,8 +603,10 @@ def test_query_staff_user_with_order_and_without_manage_orders_perm(
staff_user,
order_list,
permission_manage_staff,
+ permission_group_no_perms_all_channels,
):
# given
+ permission_group_no_perms_all_channels.user_set.add(staff_user)
staff_user.user_permissions.add(permission_manage_staff)
order_unfulfilled = order_list[0]
@@ -585,10 +644,11 @@ def test_query_staff_user_with_orders_and_manage_orders_perm(
staff_user,
order_list,
permission_manage_staff,
- permission_manage_orders,
+ permission_group_manage_orders,
):
# given
- staff_user.user_permissions.add(permission_manage_staff, permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_user)
+ staff_user.user_permissions.add(permission_manage_staff)
order_unfulfilled = order_list[0]
order_unfulfilled.user = staff_user
@@ -977,6 +1037,76 @@ def test_query_user_avatar_no_image(staff_api_client, permission_manage_staff):
assert not data["avatar"]
+USER_CHANNEL_ACCESSIBILITY_QUERY = """
+ query User($id: ID) {
+ user(id: $id) {
+ id
+ restrictedAccessToChannels
+ accessibleChannels {
+ slug
+ }
+ }
+ }
+"""
+
+
+def test_query_user_channel_accessibility_restricted_access_to_channels(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+ channel_USD,
+):
+ # given
+ user = staff_api_client.user
+ user.groups.add(permission_group_all_perms_channel_USD_only)
+
+ id = graphene.Node.to_global_id("User", user.pk)
+ variables = {"id": id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ USER_CHANNEL_ACCESSIBILITY_QUERY, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["user"]
+ assert data["id"]
+ assert data["restrictedAccessToChannels"] is True
+ assert len(data["accessibleChannels"]) == 1
+ assert data["accessibleChannels"][0]["slug"] == channel_USD.slug
+
+
+def test_query_user_channel_accessibility_not_restricted_access(
+ staff_api_client,
+ permission_group_all_perms_all_channels,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+ channel_USD,
+):
+ # given
+ user = staff_api_client.user
+ user.groups.add(
+ permission_group_all_perms_all_channels,
+ permission_group_all_perms_channel_USD_only,
+ )
+
+ id = graphene.Node.to_global_id("User", user.pk)
+ variables = {"id": id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ USER_CHANNEL_ACCESSIBILITY_QUERY, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["user"]
+ assert data["id"]
+ assert data["restrictedAccessToChannels"] is False
+ assert len(data["accessibleChannels"]) == Channel.objects.count()
+
+
def test_query_customers(staff_api_client, user_api_client, permission_manage_users):
query = """
query Users {
@@ -1340,7 +1470,7 @@ def test_user_with_cancelled_fulfillments(
staff_api_client,
customer_user,
permission_manage_users,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order_with_cancelled_fulfillment,
):
query = """
@@ -1361,9 +1491,8 @@ def test_user_with_cancelled_fulfillments(
"""
user_id = graphene.Node.to_global_id("User", customer_user.id)
variables = {"id": user_id}
- staff_api_client.user.user_permissions.add(
- permission_manage_users, permission_manage_orders
- )
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ staff_api_client.user.user_permissions.add(permission_manage_users)
response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
order_id = graphene.Node.to_global_id(
diff --git a/saleor/graphql/account/tests/test_account_permission_group.py b/saleor/graphql/account/tests/test_account_permission_group.py
index 21fddb07ae..a989b05745 100644
--- a/saleor/graphql/account/tests/test_account_permission_group.py
+++ b/saleor/graphql/account/tests/test_account_permission_group.py
@@ -2,21 +2,17 @@ import json
from unittest.mock import patch
import graphene
-import pytest
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
from ....account.error_codes import PermissionGroupErrorCode
from ....account.models import Group, User
+from ....channel.models import Channel
from ....core.utils.json_serializer import CustomJsonEncoder
from ....permission.enums import AccountPermissions, AppPermission, OrderPermissions
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.payloads import generate_meta, generate_requestor
-from ...tests.utils import (
- assert_no_permission,
- get_graphql_content,
- get_graphql_content_from_response,
-)
+from ...tests.utils import assert_no_permission, get_graphql_content
PERMISSION_GROUP_CREATE_MUTATION = """
mutation PermissionGroupCreate(
@@ -34,6 +30,10 @@ PERMISSION_GROUP_CREATE_MUTATION = """
users {
email
}
+ restrictedAccessToChannels
+ accessibleChannels {
+ slug
+ }
}
errors{
field
@@ -41,6 +41,7 @@ PERMISSION_GROUP_CREATE_MUTATION = """
permissions
users
message
+ channels
}
}
}
@@ -51,16 +52,17 @@ def test_permission_group_create_mutation(
staff_users,
permission_manage_staff,
staff_api_client,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_users,
+ permission_group_manage_apps,
):
staff_user = staff_users[0]
- staff_user.user_permissions.add(permission_manage_users, permission_manage_apps)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_apps)
query = PERMISSION_GROUP_CREATE_MUTATION
+ name = "New permission group"
variables = {
"input": {
- "name": "New permission group",
+ "name": name,
"addPermissions": [
AccountPermissions.MANAGE_USERS.name,
AppPermission.MANAGE_APPS.name,
@@ -77,8 +79,10 @@ def test_permission_group_create_mutation(
data = content["data"]["permissionGroupCreate"]
permission_group_data = data["group"]
- group = Group.objects.get()
+ group = Group.objects.get(name=name)
assert permission_group_data["name"] == group.name == variables["input"]["name"]
+ assert permission_group_data["restrictedAccessToChannels"] is False
+ assert len(permission_group_data["accessibleChannels"]) == Channel.objects.count()
permissions = {
permission["name"] for permission in permission_group_data["permissions"]
}
@@ -110,8 +114,8 @@ def test_permission_group_create_mutation_trigger_webhook(
staff_users,
permission_manage_staff,
staff_api_client,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_users,
+ permission_group_manage_apps,
settings,
):
# given
@@ -119,7 +123,7 @@ def test_permission_group_create_mutation_trigger_webhook(
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
staff_user = staff_users[0]
- staff_user.user_permissions.add(permission_manage_users, permission_manage_apps)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_apps)
query = PERMISSION_GROUP_CREATE_MUTATION
variables = {
@@ -168,11 +172,11 @@ def test_permission_group_create_app_no_permission(
staff_users,
permission_manage_staff,
app_api_client,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_users,
+ permission_group_manage_apps,
):
staff_user = staff_users[0]
- staff_user.user_permissions.add(permission_manage_users, permission_manage_apps)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_apps)
query = PERMISSION_GROUP_CREATE_MUTATION
variables = {
@@ -194,18 +198,62 @@ def test_permission_group_create_app_no_permission(
assert_no_permission(response)
+def test_permission_group_create_no_channel_access(
+ staff_users,
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+ channel_USD,
+):
+ # given
+ staff_user = staff_users[0]
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_user)
+ query = PERMISSION_GROUP_CREATE_MUTATION
+ channel_PLN_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ channel_USD_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ variables = {
+ "input": {
+ "name": "New permission group",
+ "restrictedAccessToChannels": True,
+ "addPermissions": [
+ AccountPermissions.MANAGE_USERS.name,
+ AppPermission.MANAGE_APPS.name,
+ ],
+ "addUsers": [
+ graphene.Node.to_global_id("User", user.id) for user in staff_users
+ ],
+ "addChannels": [channel_PLN_id, channel_USD_id],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["permissionGroupCreate"]
+ errors = data["errors"]
+
+ assert len(errors) == 1
+ assert errors[0]["field"] == "addChannels"
+ assert errors[0]["code"] == PermissionGroupErrorCode.OUT_OF_SCOPE_CHANNEL.name
+ assert errors[0]["channels"] == [channel_PLN_id]
+
+
def test_permission_group_create_mutation_only_required_fields(
staff_users,
permission_manage_staff,
staff_api_client,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_users,
+ permission_group_manage_apps,
):
staff_user = staff_users[0]
- staff_user.user_permissions.add(permission_manage_users, permission_manage_apps)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_apps)
query = PERMISSION_GROUP_CREATE_MUTATION
+ name = "New permission group"
- variables = {"input": {"name": "New permission group"}}
+ variables = {"input": {"name": name}}
response = staff_api_client.post_graphql(
query, variables, permissions=(permission_manage_staff,)
)
@@ -213,7 +261,7 @@ def test_permission_group_create_mutation_only_required_fields(
data = content["data"]["permissionGroupCreate"]
permission_group_data = data["group"]
- group = Group.objects.get()
+ group = Group.objects.get(name=name)
assert permission_group_data["name"] == group.name == variables["input"]["name"]
assert permission_group_data["permissions"] == []
assert not group.permissions.all()
@@ -225,16 +273,17 @@ def test_permission_group_create_mutation_only_required_fields_not_none(
staff_users,
permission_manage_staff,
staff_api_client,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_users,
+ permission_group_manage_apps,
):
staff_user = staff_users[0]
- staff_user.user_permissions.add(permission_manage_users, permission_manage_apps)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_apps)
query = PERMISSION_GROUP_CREATE_MUTATION
+ name = "New permission group"
variables = {
"input": {
- "name": "New permission group",
+ "name": name,
"addUsers": None,
"addPermissions": None,
}
@@ -246,7 +295,7 @@ def test_permission_group_create_mutation_only_required_fields_not_none(
data = content["data"]["permissionGroupCreate"]
permission_group_data = data["group"]
- group = Group.objects.get()
+ group = Group.objects.get(name=name)
assert permission_group_data["name"] == group.name == variables["input"]["name"]
assert permission_group_data["permissions"] == []
assert not group.permissions.all()
@@ -259,17 +308,19 @@ def test_permission_group_create_mutation_lack_of_permission(
permission_manage_staff,
staff_api_client,
superuser_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
+ permission_group_all_perms_all_channels,
):
"""Ensue staff user can't create group with wider scope of permissions.
Ensure that superuser pass restrictions.
"""
- staff_user.user_permissions.add(permission_manage_orders)
+ staff_user.groups.add(permission_group_manage_orders)
query = PERMISSION_GROUP_CREATE_MUTATION
+ name = "New permission group"
variables = {
"input": {
- "name": "New permission group",
+ "name": name,
"addPermissions": [
AccountPermissions.MANAGE_USERS.name,
OrderPermissions.MANAGE_ORDERS.name,
@@ -302,7 +353,7 @@ def test_permission_group_create_mutation_lack_of_permission(
errors = data["errors"]
assert not errors
- group = Group.objects.get()
+ group = Group.objects.get(name=name)
assert data["group"]["name"] == group.name == variables["input"]["name"]
permissions_codes = {
permission["code"].lower() for permission in data["group"]["permissions"]
@@ -319,10 +370,9 @@ def test_permission_group_create_mutation_group_exists(
permission_manage_staff,
staff_api_client,
permission_group_manage_users,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_apps,
):
- staff_user.user_permissions.add(permission_manage_users, permission_manage_apps)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_apps)
query = PERMISSION_GROUP_CREATE_MUTATION
variables = {
@@ -357,8 +407,9 @@ def test_permission_group_create_mutation_add_customer_user(
permission_manage_staff,
staff_api_client,
superuser_api_client,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_users,
+ permission_group_manage_apps,
+ permission_group_all_perms_all_channels,
):
"""Ensure creating permission group with customer user in input field for adding
users failed. Mutations should failed. Error should contains list of wrong users
@@ -370,7 +421,7 @@ def test_permission_group_create_mutation_add_customer_user(
email="[email protected]", password="test"
)
- staff_user.user_permissions.add(permission_manage_users, permission_manage_apps)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_apps)
query = PERMISSION_GROUP_CREATE_MUTATION
user_ids = [
@@ -424,9 +475,9 @@ def test_permission_group_create_mutation_lack_of_permission_and_customer_user(
customer_user,
permission_manage_staff,
staff_api_client,
- permission_manage_users,
+ permission_group_manage_users,
):
- staff_user.user_permissions.add(permission_manage_users)
+ staff_user.groups.add(permission_group_manage_users)
query = PERMISSION_GROUP_CREATE_MUTATION
user_ids = [
@@ -469,15 +520,14 @@ def test_permission_group_create_mutation_requestor_does_not_have_all_users_perm
permission_group_manage_users,
permission_manage_staff,
staff_api_client,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_apps,
):
"""Ensure user can create group with user whose permission scope
is wider than requestor scope.
"""
staff_user = staff_users[0]
- staff_user.user_permissions.add(permission_manage_apps)
+ staff_user.groups.add(permission_group_manage_apps)
permission_group_manage_users.user_set.add(staff_users[1])
query = PERMISSION_GROUP_CREATE_MUTATION
@@ -518,6 +568,118 @@ def test_permission_group_create_mutation_requestor_does_not_have_all_users_perm
)
+def test_permission_group_create_mutation_restricted_access_to_channels(
+ staff_users,
+ permission_manage_staff,
+ staff_api_client,
+ permission_group_manage_users,
+ permission_group_manage_apps,
+ channel_PLN,
+ channel_USD,
+):
+ # given
+ staff_user = staff_users[0]
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_apps)
+ query = PERMISSION_GROUP_CREATE_MUTATION
+
+ variables = {
+ "input": {
+ "name": "New permission group",
+ "restrictedAccessToChannels": True,
+ "addChannels": [graphene.Node.to_global_id("Channel", channel_PLN.id)],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_staff,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["permissionGroupCreate"]
+ permission_group_data = data["group"]
+ assert permission_group_data["name"] == variables["input"]["name"]
+ assert permission_group_data["restrictedAccessToChannels"] is True
+ assert len(permission_group_data["accessibleChannels"]) == 1
+ assert permission_group_data["accessibleChannels"][0]["slug"] == channel_PLN.slug
+ assert data["errors"] == []
+
+
+def test_permission_group_create_mutation_not_restricted_channels(
+ permission_manage_staff,
+ staff_api_client,
+ permission_group_no_perms_all_channels,
+ channel_PLN,
+ channel_USD,
+):
+ """Ensure that creating permission group with restrictedAccessToChannels se to
+ False won't assign any channels to the group."""
+ # given
+ permission_group_no_perms_all_channels.user_set.add(staff_api_client.user)
+ query = PERMISSION_GROUP_CREATE_MUTATION
+ name = "New permission group"
+
+ variables = {
+ "input": {
+ "name": name,
+ "restrictedAccessToChannels": False,
+ "addChannels": [graphene.Node.to_global_id("Channel", channel_PLN.pk)],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_staff,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["permissionGroupCreate"]
+ permission_group_data = data["group"]
+ assert data["errors"] == []
+ assert permission_group_data["restrictedAccessToChannels"] is False
+ assert len(permission_group_data["accessibleChannels"]) == Channel.objects.count()
+ group = Group.objects.get(name=name)
+ assert group.channels.count() == 0
+
+
+def test_permission_group_create_mutation_not_restricted_channels_no_access(
+ permission_manage_staff,
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+ channel_USD,
+):
+ """Ensure that user with restricted channel access is not able to create a group
+ with not restricted channel access."""
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ query = PERMISSION_GROUP_CREATE_MUTATION
+ name = "New permission group"
+
+ variables = {
+ "input": {
+ "name": name,
+ "restrictedAccessToChannels": False,
+ "addChannels": [graphene.Node.to_global_id("Channel", channel_PLN.pk)],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["permissionGroupCreate"]
+ errors = data["errors"]
+
+ assert len(errors) == 1
+ assert errors[0]["field"] == "restrictedAccessToChannels"
+ assert errors[0]["code"] == PermissionGroupErrorCode.OUT_OF_SCOPE_CHANNEL.name
+
+
PERMISSION_GROUP_UPDATE_MUTATION = """
mutation PermissionGroupUpdate(
$id: ID!, $input: PermissionGroupUpdateInput!) {
@@ -534,12 +696,17 @@ PERMISSION_GROUP_UPDATE_MUTATION = """
users {
email
}
+ restrictedAccessToChannels
+ accessibleChannels {
+ slug
+ }
}
errors{
field
code
permissions
users
+ channels
message
}
}
@@ -549,13 +716,17 @@ PERMISSION_GROUP_UPDATE_MUTATION = """
def test_permission_group_update_mutation(
staff_users,
- permission_manage_staff,
staff_api_client,
- permission_manage_apps,
+ permission_group_manage_apps,
+ permission_group_manage_users,
permission_manage_users,
+ permission_manage_staff,
+ channel_PLN,
+ channel_USD,
):
+ # given
staff_user = staff_users[0]
- staff_user.user_permissions.add(permission_manage_apps, permission_manage_users)
+ staff_user.groups.add(permission_group_manage_apps, permission_group_manage_users)
query = PERMISSION_GROUP_UPDATE_MUTATION
group1, group2 = Group.objects.bulk_create(
@@ -568,6 +739,11 @@ def test_permission_group_update_mutation(
group1.user_set.add(group1_user)
group2.user_set.add(staff_user)
+ group1.restricted_access_to_channels = True
+ group1.save(update_fields=["restricted_access_to_channels"])
+
+ group1.channels.add(channel_USD)
+
# set of users emails being in a group
users = set(group1.user_set.values_list("email", flat=True))
@@ -579,9 +755,15 @@ def test_permission_group_update_mutation(
"removePermissions": [AccountPermissions.MANAGE_USERS.name],
"addUsers": [graphene.Node.to_global_id("User", staff_user.pk)],
"removeUsers": [graphene.Node.to_global_id("User", group1_user.pk)],
+ "addChannels": [graphene.Node.to_global_id("Channel", channel_PLN.pk)],
+ "removeChannels": [graphene.Node.to_global_id("Channel", channel_USD.pk)],
},
}
+
+ # when
response = staff_api_client.post_graphql(query, variables)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["permissionGroupUpdate"]
permission_group_data = data["group"]
@@ -605,6 +787,9 @@ def test_permission_group_update_mutation(
== permissions_codes
)
assert set(group1.user_set.all().values_list("email", flat=True)) == users
+ assert permission_group_data["restrictedAccessToChannels"] is True
+ assert len(permission_group_data["accessibleChannels"]) == 1
+ assert permission_group_data["accessibleChannels"][0]["slug"] == channel_PLN.slug
assert data["errors"] == []
@@ -617,9 +802,10 @@ def test_permission_group_update_mutation_trigger_webhook(
any_webhook,
staff_users,
permission_manage_staff,
- staff_api_client,
- permission_manage_apps,
permission_manage_users,
+ staff_api_client,
+ permission_group_manage_apps,
+ permission_group_manage_users,
settings,
):
# given
@@ -627,7 +813,7 @@ def test_permission_group_update_mutation_trigger_webhook(
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
staff_user = staff_users[0]
- staff_user.user_permissions.add(permission_manage_apps, permission_manage_users)
+ staff_user.groups.add(permission_group_manage_apps, permission_group_manage_users)
query = PERMISSION_GROUP_UPDATE_MUTATION
group1, group2 = Group.objects.bulk_create(
@@ -678,16 +864,240 @@ def test_permission_group_update_mutation_trigger_webhook(
)
+def test_permission_group_update_mutation_to_not_restricted_channels(
+ permission_group_no_perms_all_channels,
+ permission_group_all_perms_channel_USD_only,
+ staff_api_client,
+ channel_PLN,
+ channel_USD,
+):
+ # given
+ staff_user = staff_api_client.user
+ group = permission_group_all_perms_channel_USD_only
+ staff_user.groups.add(
+ permission_group_no_perms_all_channels,
+ permission_group_all_perms_channel_USD_only,
+ )
+
+ assert group.channels.count() > 0
+
+ variables = {
+ "id": graphene.Node.to_global_id("Group", group.id),
+ "input": {
+ "name": "New permission group",
+ "restrictedAccessToChannels": False,
+ "addChannels": [graphene.Node.to_global_id("Channel", channel_PLN.pk)],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PERMISSION_GROUP_UPDATE_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["permissionGroupUpdate"]
+ permission_group_data = data["group"]
+ assert data["errors"] == []
+ assert permission_group_data["restrictedAccessToChannels"] is False
+ assert len(permission_group_data["accessibleChannels"]) == Channel.objects.count()
+ group.refresh_from_db()
+ assert group.channels.count() == 0
+
+
+def test_permission_group_update_mutation_to_not_restricted_channels_no_access(
+ permission_group_all_perms_channel_USD_only,
+ staff_api_client,
+ channel_PLN,
+ channel_USD,
+):
+ # given
+ staff_user = staff_api_client.user
+ group = permission_group_all_perms_channel_USD_only
+ group.user_set.add(staff_user)
+
+ assert group.channels.count() > 0
+
+ variables = {
+ "id": graphene.Node.to_global_id("Group", group.id),
+ "input": {
+ "name": "New permission group",
+ "restrictedAccessToChannels": False,
+ "addChannels": [graphene.Node.to_global_id("Channel", channel_PLN.pk)],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PERMISSION_GROUP_UPDATE_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["permissionGroupUpdate"]
+ assert not data["group"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "restrictedAccessToChannels"
+ assert (
+ data["errors"][0]["code"] == PermissionGroupErrorCode.OUT_OF_SCOPE_CHANNEL.name
+ )
+
+
+def test_permission_group_update_mutation_to_not_restricted_channels_superuser(
+ permission_group_all_perms_channel_USD_only,
+ superuser_api_client,
+ channel_PLN,
+ channel_USD,
+):
+ # given
+ group = permission_group_all_perms_channel_USD_only
+
+ assert group.channels.count() > 0
+
+ variables = {
+ "id": graphene.Node.to_global_id("Group", group.id),
+ "input": {
+ "name": "New permission group",
+ "restrictedAccessToChannels": False,
+ "addChannels": [graphene.Node.to_global_id("Channel", channel_PLN.pk)],
+ },
+ }
+
+ # when
+ response = superuser_api_client.post_graphql(
+ PERMISSION_GROUP_UPDATE_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["permissionGroupUpdate"]
+ permission_group_data = data["group"]
+ assert data["errors"] == []
+ assert permission_group_data["restrictedAccessToChannels"] is False
+ assert len(permission_group_data["accessibleChannels"]) == Channel.objects.count()
+ group.refresh_from_db()
+ assert group.channels.count() == 0
+
+
+def test_permission_group_update_mutation_not_restricted_channels(
+ permission_group_all_perms_all_channels,
+ staff_api_client,
+ channel_PLN,
+ channel_USD,
+):
+ # given
+ staff_user = staff_api_client.user
+ group = permission_group_all_perms_all_channels
+ group.user_set.add(staff_user)
+
+ assert group.channels.count() == 0
+
+ variables = {
+ "id": graphene.Node.to_global_id("Group", group.id),
+ "input": {
+ "addChannels": [graphene.Node.to_global_id("Channel", channel_PLN.pk)]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PERMISSION_GROUP_UPDATE_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["permissionGroupUpdate"]
+ permission_group_data = data["group"]
+ assert data["errors"] == []
+ assert permission_group_data["restrictedAccessToChannels"] is False
+ assert len(permission_group_data["accessibleChannels"]) == Channel.objects.count()
+ group.refresh_from_db()
+ assert group.channels.count() == 0
+
+
+def test_permission_group_update_mutation_no_channel_access(
+ permission_group_all_perms_channel_USD_only,
+ staff_api_client,
+ channel_PLN,
+ channel_USD,
+):
+ # given
+ staff_user = staff_api_client.user
+ group = permission_group_all_perms_channel_USD_only
+ group.user_set.add(staff_user)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)
+
+ variables = {
+ "id": graphene.Node.to_global_id("Group", group.id),
+ "input": {"addChannels": [channel_id]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PERMISSION_GROUP_UPDATE_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["permissionGroupUpdate"]
+ errors = data["errors"]
+
+ assert not data["group"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "addChannels"
+ assert errors[0]["code"] == PermissionGroupErrorCode.OUT_OF_SCOPE_CHANNEL.name
+ assert errors[0]["permissions"] is None
+ assert errors[0]["users"] is None
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_permission_group_update_mutation_out_of_scope_channel(
+ permission_group_all_perms_channel_USD_only,
+ permission_group_no_perms_all_channels,
+ staff_api_client,
+ channel_PLN,
+ channel_USD,
+):
+ # given
+ staff_user = staff_api_client.user
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_user)
+ group = permission_group_no_perms_all_channels
+
+ variables = {
+ "id": graphene.Node.to_global_id("Group", group.id),
+ "input": {"name": "New name"},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PERMISSION_GROUP_UPDATE_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["permissionGroupUpdate"]
+ errors = data["errors"]
+
+ assert not data["group"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PermissionGroupErrorCode.OUT_OF_SCOPE_CHANNEL.name
+ assert errors[0]["permissions"] is None
+ assert errors[0]["users"] is None
+ assert errors[0]["channels"] is None
+
+
def test_permission_group_update_mutation_removing_perm_left_not_manageable_perms(
- permission_group_manage_users,
- staff_user,
+ staff_users,
permission_manage_staff,
staff_api_client,
- permission_manage_apps,
- permission_manage_users,
+ permission_group_manage_apps,
+ permission_group_manage_users,
):
"""Ensure user cannot remove permissions if it left not meanagable perms."""
- staff_user.user_permissions.add(permission_manage_apps, permission_manage_users)
+ staff_api_client.user.groups.add(
+ permission_group_manage_apps, permission_group_manage_users
+ )
group = permission_group_manage_users
query = PERMISSION_GROUP_UPDATE_MUTATION
@@ -698,7 +1108,7 @@ def test_permission_group_update_mutation_removing_perm_left_not_manageable_perm
"name": "New permission group",
"addPermissions": [AppPermission.MANAGE_APPS.name],
"removePermissions": [AccountPermissions.MANAGE_USERS.name],
- "addUsers": [graphene.Node.to_global_id("User", staff_user.pk)],
+ "addUsers": [graphene.Node.to_global_id("User", staff_users[-1].pk)],
"removeUsers": [graphene.Node.to_global_id("User", group_user.pk)],
},
}
@@ -718,16 +1128,15 @@ def test_permission_group_update_mutation_removing_perm_left_not_manageable_perm
)
assert errors[0]["permissions"] == [AccountPermissions.MANAGE_USERS.name]
assert errors[0]["users"] is None
- assert staff_user.groups.count() == 0
+ assert staff_users[-1].groups.count() == 0
def test_permission_group_update_mutation_superuser_can_remove_any_perms(
- permission_group_manage_users,
permission_manage_staff,
superuser_api_client,
staff_user,
- permission_manage_apps,
- permission_manage_users,
+ permission_group_manage_apps,
+ permission_group_manage_users,
):
"""Ensure superuser can remove any permissions."""
group = permission_group_manage_users
@@ -775,14 +1184,13 @@ def test_permission_group_update_mutation_superuser_can_remove_any_perms(
def test_permission_group_update_mutation_app_no_permission(
- permission_group_manage_users,
staff_user,
permission_manage_staff,
app_api_client,
- permission_manage_apps,
- permission_manage_users,
+ permission_group_manage_apps,
+ permission_group_manage_users,
):
- staff_user.user_permissions.add(permission_manage_apps, permission_manage_users)
+ staff_user.groups.add(permission_group_manage_apps, permission_group_manage_users)
group = permission_group_manage_users
query = PERMISSION_GROUP_UPDATE_MUTATION
@@ -805,15 +1213,14 @@ def test_permission_group_update_mutation_app_no_permission(
def test_permission_group_update_mutation_remove_me_from_last_group(
- permission_group_manage_users,
staff_users,
permission_manage_staff,
staff_api_client,
- permission_manage_users,
+ permission_group_manage_users,
):
"""Ensure mutation failed when user removing himself from user's last group."""
staff_user, staff_user1, staff_user2 = staff_users
- staff_user.user_permissions.add(permission_manage_users)
+ staff_user.groups.add(permission_group_manage_users)
group = permission_group_manage_users
group.permissions.add(permission_manage_staff)
# ensure user is in group
@@ -845,16 +1252,16 @@ def test_permission_group_update_mutation_remove_me_from_last_group(
def test_permission_group_update_mutation_remove_me_from_not_last_group(
- permission_group_manage_users,
staff_users,
permission_manage_staff,
staff_api_client,
- permission_manage_users,
+ permission_group_manage_users,
permission_manage_orders,
+ permission_manage_users,
):
"""Ensure user can remove himself from group if he is a member of another group."""
staff_user, staff_user1, _ = staff_users
- staff_user.user_permissions.add(permission_manage_users)
+ staff_user.groups.add(permission_group_manage_users)
groups = Group.objects.bulk_create(
[Group(name="manage users"), Group(name="manage staff and users")]
)
@@ -867,7 +1274,7 @@ def test_permission_group_update_mutation_remove_me_from_not_last_group(
group1.user_set.add(staff_user)
group2.user_set.add(staff_user, staff_user1)
- assert staff_user.groups.count() == 2
+ assert staff_user.groups.count() == 3
query = PERMISSION_GROUP_UPDATE_MUTATION
@@ -884,7 +1291,7 @@ def test_permission_group_update_mutation_remove_me_from_not_last_group(
assert not errors
assert staff_user_id not in permission_group_data["users"]
- assert staff_user.groups.count() == 1
+ assert staff_user.groups.count() == 2
def test_permission_group_update_mutation_remove_last_user_from_group(
@@ -896,7 +1303,7 @@ def test_permission_group_update_mutation_remove_last_user_from_group(
):
"""Ensure user can remove last user from the group."""
staff_user, staff_user1, staff_user2 = staff_users
- staff_user.user_permissions.add(permission_manage_users)
+ staff_user.groups.add(permission_group_manage_users)
groups = Group.objects.bulk_create(
[Group(name="manage users"), Group(name="manage staff and users")]
)
@@ -906,6 +1313,7 @@ def test_permission_group_update_mutation_remove_last_user_from_group(
group1.user_set.add(staff_user1)
group2.user_set.add(staff_user2)
+ assert staff_user.groups.count() == 1
# ensure group contains only 1 user
assert group1.user_set.count() == 1
@@ -928,33 +1336,34 @@ def test_permission_group_update_mutation_remove_last_user_from_group(
errors = data["errors"]
assert not errors
- assert staff_user.groups.count() == 0
+ assert staff_user.groups.count() == 1
assert permission_group_data["users"] == []
def test_permission_group_update_mutation_only_name(
permission_group_manage_users,
+ permission_group_manage_staff,
staff_user,
- permission_manage_staff,
staff_api_client,
permission_manage_users,
):
"""Ensure mutation update group when only name are passed in input."""
- staff_user.user_permissions.add(permission_manage_staff, permission_manage_users)
+ staff_user.groups.add(permission_group_manage_staff, permission_group_manage_users)
group = permission_group_manage_users
old_group_name = group.name
query = PERMISSION_GROUP_UPDATE_MUTATION
+ name = "New permission group"
variables = {
"id": graphene.Node.to_global_id("Group", group.id),
- "input": {"name": "New permission group"},
+ "input": {"name": name},
}
response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["permissionGroupUpdate"]
permission_group_data = data["group"]
- group = Group.objects.get()
+ group = Group.objects.get(name=name)
assert group.name != old_group_name
assert permission_group_data["name"] == group.name
assert group.permissions.all().count() == 1
@@ -980,20 +1389,21 @@ def test_permission_group_update_mutation_only_name(
def test_permission_group_update_mutation_only_name_other_fields_with_none(
permission_group_manage_users,
staff_user,
- permission_manage_staff,
+ permission_group_manage_staff,
staff_api_client,
permission_manage_users,
):
"""Ensure mutation update group when only name are passed in input."""
- staff_user.user_permissions.add(permission_manage_staff, permission_manage_users)
+ staff_user.groups.add(permission_group_manage_staff, permission_group_manage_users)
group = permission_group_manage_users
old_group_name = group.name
query = PERMISSION_GROUP_UPDATE_MUTATION
+ name = "New permission group"
variables = {
"id": graphene.Node.to_global_id("Group", group.id),
"input": {
- "name": "New permission group",
+ "name": name,
"addPermissions": None,
"removePermissions": None,
"addUsers": None,
@@ -1005,7 +1415,7 @@ def test_permission_group_update_mutation_only_name_other_fields_with_none(
data = content["data"]["permissionGroupUpdate"]
permission_group_data = data["group"]
- group = Group.objects.get()
+ group = Group.objects.get(name=name)
assert group.name != old_group_name
assert permission_group_data["name"] == group.name
assert group.permissions.all().count() == 1
@@ -1030,15 +1440,14 @@ def test_permission_group_update_mutation_only_name_other_fields_with_none(
def test_permission_group_update_mutation_with_name_which_exists(
permission_group_manage_users,
+ permission_group_manage_staff,
staff_user,
- permission_manage_staff,
staff_api_client,
- permission_manage_users,
):
"""Ensure mutation failed where updating name with value which already is a name of
different group.
"""
- staff_user.user_permissions.add(permission_manage_staff, permission_manage_users)
+ staff_user.groups.add(permission_group_manage_staff, permission_group_manage_users)
group = permission_group_manage_users
old_group_name = group.name
query = PERMISSION_GROUP_UPDATE_MUTATION
@@ -1067,15 +1476,14 @@ def test_permission_group_update_mutation_with_name_which_exists(
def test_permission_group_update_mutation_only_permissions(
- permission_group_manage_users,
staff_user,
permission_manage_staff,
staff_api_client,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_users,
+ permission_group_manage_apps,
):
"""Ensure mutation update group when only permissions are passed in input."""
- staff_user.user_permissions.add(permission_manage_users, permission_manage_apps)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_apps)
group = permission_group_manage_users
old_group_name = group.name
query = PERMISSION_GROUP_UPDATE_MUTATION
@@ -1091,7 +1499,7 @@ def test_permission_group_update_mutation_only_permissions(
data = content["data"]["permissionGroupUpdate"]
permission_group_data = data["group"]
- group = Group.objects.get()
+ group.refresh_from_db()
assert group.name == old_group_name
assert permission_group_data["name"] == group.name
permissions = {
@@ -1102,14 +1510,13 @@ def test_permission_group_update_mutation_only_permissions(
def test_permission_group_update_mutation_no_input_data(
- permission_group_manage_users,
staff_user,
- permission_manage_staff,
- permission_manage_users,
+ permission_group_manage_users,
+ permission_group_manage_staff,
staff_api_client,
):
"""Ensure mutation doesn't change group when input is empty."""
- staff_user.user_permissions.add(permission_manage_staff, permission_manage_users)
+ staff_user.groups.add(permission_group_manage_staff, permission_group_manage_users)
group = permission_group_manage_users
query = PERMISSION_GROUP_UPDATE_MUTATION
@@ -1134,13 +1541,13 @@ def test_permission_group_update_mutation_user_cannot_manage_group(
permission_manage_staff,
staff_api_client,
superuser_api_client,
- permission_manage_apps,
+ permission_group_manage_apps,
):
"""Ensure that update mutation failed when user try to update group for which
he doesn't have permission.
Ensure superuser pass restrictions.
"""
- staff_user.user_permissions.add(permission_manage_apps)
+ staff_user.groups.add(permission_group_manage_apps)
group = permission_group_manage_users
query = PERMISSION_GROUP_UPDATE_MUTATION
@@ -1185,19 +1592,18 @@ def test_permission_group_update_mutation_user_cannot_manage_group(
def test_permission_group_update_mutation_user_in_list_to_add_and_remove(
- permission_group_manage_users,
staff_users,
permission_manage_staff,
staff_api_client,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_users,
+ permission_group_manage_apps,
):
"""Ensure update mutation failed when user IDs are in both lists for adding
and removing. Ensure mutation contains list of user IDs which cause
the problem.
"""
staff_user = staff_users[0]
- staff_user.user_permissions.add(permission_manage_users, permission_manage_apps)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_apps)
group = permission_group_manage_users
query = PERMISSION_GROUP_UPDATE_MUTATION
@@ -1228,22 +1634,21 @@ def test_permission_group_update_mutation_user_in_list_to_add_and_remove(
def test_permission_group_update_mutation_permissions_in_list_to_add_and_remove(
- permission_group_manage_users,
staff_user,
permission_manage_staff,
staff_api_client,
- permission_manage_users,
- permission_manage_apps,
- permission_manage_orders,
+ permission_group_manage_users,
+ permission_group_manage_apps,
+ permission_group_manage_orders,
):
"""Ensure update mutation failed when permission items are in both lists for
adding and removing. Ensure mutation contains list of permissions which cause
the problem.
"""
- staff_user.user_permissions.add(
- permission_manage_users,
- permission_manage_apps,
- permission_manage_orders,
+ staff_user.groups.add(
+ permission_group_manage_users,
+ permission_group_manage_apps,
+ permission_group_manage_orders,
)
group = permission_group_manage_users
query = PERMISSION_GROUP_UPDATE_MUTATION
@@ -1275,23 +1680,22 @@ def test_permission_group_update_mutation_permissions_in_list_to_add_and_remove(
def test_permission_group_update_mutation_permissions_and_users_duplicated(
- permission_group_manage_users,
staff_users,
permission_manage_staff,
staff_api_client,
- permission_manage_users,
- permission_manage_apps,
- permission_manage_orders,
+ permission_group_manage_users,
+ permission_group_manage_apps,
+ permission_group_manage_orders,
):
"""Ensure updating mutations with the same permission and users in list for
adding and removing failed. Mutation should failed. Error should contains list of
users IDs and permissions that are duplicated.
"""
staff_user = staff_users[0]
- staff_user.user_permissions.add(
- permission_manage_users,
- permission_manage_apps,
- permission_manage_orders,
+ staff_user.groups.add(
+ permission_group_manage_users,
+ permission_group_manage_apps,
+ permission_group_manage_orders,
)
group = permission_group_manage_users
query = PERMISSION_GROUP_UPDATE_MUTATION
@@ -1333,20 +1737,19 @@ def test_permission_group_update_mutation_permissions_and_users_duplicated(
def test_permission_group_update_mutation_user_add_customer_user(
- permission_group_manage_users,
staff_user,
permission_manage_staff,
staff_api_client,
superuser_api_client,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_users,
+ permission_group_manage_apps,
customer_user,
):
"""Ensure update mutation with customer user in field for adding users failed.
Ensure error contains list with user IDs which cause the problem.
Ensure it also fail for superuser.
"""
- staff_user.user_permissions.add(permission_manage_users, permission_manage_apps)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_apps)
group = permission_group_manage_users
query = PERMISSION_GROUP_UPDATE_MUTATION
@@ -1391,20 +1794,19 @@ def test_permission_group_update_mutation_user_add_customer_user(
def test_permission_group_update_mutation_lack_of_permission(
- permission_group_manage_users,
staff_user,
permission_manage_staff,
staff_api_client,
superuser_api_client,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_users,
+ permission_group_manage_apps,
permission_manage_orders,
):
"""Ensure update mutation failed when user trying to add permission which
he doesn't have.
Ensure superuser pass the restrictions.
"""
- staff_user.user_permissions.add(permission_manage_users, permission_manage_apps)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_apps)
group = permission_group_manage_users
query = PERMISSION_GROUP_UPDATE_MUTATION
@@ -1455,12 +1857,11 @@ def test_permission_group_update_mutation_lack_of_permission(
def test_permission_group_update_mutation_out_of_scope_users(
staff_users,
- permission_group_manage_users,
permission_manage_staff,
staff_api_client,
superuser_api_client,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_users,
+ permission_group_manage_apps,
permission_manage_orders,
permission_manage_products,
):
@@ -1477,7 +1878,7 @@ def test_permission_group_update_mutation_out_of_scope_users(
is_active=True,
)
- staff_user.user_permissions.add(permission_manage_apps, permission_manage_users)
+ staff_user.groups.add(permission_group_manage_apps, permission_group_manage_users)
staff_users[1].user_permissions.add(permission_manage_products)
staff_user3.user_permissions.add(permission_manage_orders)
@@ -1521,7 +1922,7 @@ def test_permission_group_update_mutation_out_of_scope_users(
errors = data["errors"]
assert not errors
- group = Group.objects.get()
+ group.refresh_from_db()
assert not errors
permissions_codes = {
permission["code"].lower() for permission in data["group"]["permissions"]
@@ -1537,14 +1938,73 @@ def test_permission_group_update_mutation_out_of_scope_users(
assert staff in group_users
-def test_permission_group_update_mutation_multiple_errors(
+def test_permission_group_update_mutation_duplicated_channels(
+ staff_user,
+ permission_manage_staff,
+ staff_api_client,
permission_group_manage_users,
+ permission_group_manage_apps,
+ channel_PLN,
+ channel_USD,
+ channel_JPY,
+):
+ """Ensure update mutation failed when channel IDs are in both lists for adding
+ and removing. Ensure mutation contains list of channel IDs which cause
+ the problem.
+ """
+ # given
+ staff_user.groups.add(
+ permission_group_manage_users,
+ permission_group_manage_apps,
+ )
+ group = permission_group_manage_users
+
+ query = PERMISSION_GROUP_UPDATE_MUTATION
+
+ add_channels = [
+ graphene.Node.to_global_id("Channel", channel)
+ for channel in [channel_PLN, channel_USD, channel_JPY]
+ ]
+ remove_channels = [
+ graphene.Node.to_global_id("Channel", channel)
+ for channel in [channel_USD, channel_JPY]
+ ]
+ variables = {
+ "id": graphene.Node.to_global_id("Group", group.id),
+ "input": {
+ "addChannels": add_channels,
+ "removeChannels": remove_channels,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_staff,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["permissionGroupUpdate"]
+ errors = data["errors"]
+
+ assert len(errors) == 1
+ assert errors[0]["code"] == PermissionGroupErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["field"] == "channels"
+ assert set(errors[0]["channels"]) == {
+ graphene.Node.to_global_id("Channel", channel)
+ for channel in [channel_USD, channel_JPY]
+ }
+ assert errors[0]["users"] is None
+ assert errors[0]["permissions"] is None
+
+
+def test_permission_group_update_mutation_multiple_errors(
staff_user,
customer_user,
permission_manage_staff,
staff_api_client,
- permission_manage_users,
- permission_manage_apps,
+ permission_group_manage_users,
+ permission_group_manage_apps,
permission_manage_orders,
):
"""Ensure update mutation failed with all validation errors when input data
@@ -1553,7 +2013,7 @@ def test_permission_group_update_mutation_multiple_errors(
- adding customer user (ASSIGN_NON_STAFF_MEMBER)
"""
- staff_user.user_permissions.add(permission_manage_apps, permission_manage_users)
+ staff_user.groups.add(permission_group_manage_apps, permission_group_manage_users)
group = permission_group_manage_users
query = PERMISSION_GROUP_UPDATE_MUTATION
@@ -1610,9 +2070,11 @@ def test_permission_group_update_mutation_multiple_errors(
def test_permission_group_update_mutation_remove_all_users_manageable_perms(
staff_users,
- permission_manage_users,
+ permission_group_manage_users,
+ permission_group_manage_orders,
permission_manage_staff,
permission_manage_orders,
+ permission_manage_users,
staff_api_client,
):
"""Ensure that user can remove group users if there is other source of all group
@@ -1632,7 +2094,7 @@ def test_permission_group_update_mutation_remove_all_users_manageable_perms(
group1.user_set.add(staff_user1, staff_user2)
group2.user_set.add(staff_user2)
- staff_user.user_permissions.add(permission_manage_users, permission_manage_orders)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_orders)
query = PERMISSION_GROUP_UPDATE_MUTATION
variables = {
"id": graphene.Node.to_global_id("Group", group1.id),
@@ -1659,8 +2121,10 @@ def test_permission_group_update_mutation_remove_all_users_manageable_perms(
def test_permission_group_update_mutation_remove_all_group_users_not_manageable_perms(
staff_users,
- permission_manage_users,
+ permission_group_manage_users,
+ permission_group_manage_orders,
permission_manage_staff,
+ permission_manage_users,
permission_manage_orders,
staff_api_client,
superuser_api_client,
@@ -1682,7 +2146,7 @@ def test_permission_group_update_mutation_remove_all_group_users_not_manageable_
group1.user_set.add(staff_user1, staff_user2)
group2.user_set.add(staff_user2)
- staff_user.user_permissions.add(permission_manage_users, permission_manage_orders)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_orders)
query = PERMISSION_GROUP_UPDATE_MUTATION
variables = {
"id": graphene.Node.to_global_id("Group", group1.id),
@@ -1726,9 +2190,11 @@ def test_permission_group_update_mutation_remove_all_group_users_not_manageable_
def test_permission_group_update_mutation_remove_group_users_add_with_manage_stuff(
staff_users,
- permission_manage_users,
+ permission_group_manage_users,
+ permission_group_manage_orders,
permission_manage_staff,
permission_manage_orders,
+ permission_manage_users,
staff_api_client,
):
"""Ensure that user can remove all group users when adding somebody with
@@ -1747,7 +2213,7 @@ def test_permission_group_update_mutation_remove_group_users_add_with_manage_stu
group1.user_set.add(staff_user1)
group2.user_set.add(staff_user2)
- staff_user.user_permissions.add(permission_manage_users, permission_manage_orders)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_orders)
query = PERMISSION_GROUP_UPDATE_MUTATION
variables = {
"id": graphene.Node.to_global_id("Group", group1.id),
@@ -1771,33 +2237,32 @@ def test_permission_group_update_mutation_remove_group_users_add_with_manage_stu
assert group_data["users"][0]["email"] == staff_user2.email
-def test_group_update_mutation_remove_some_users_from_group_with_manage_stuff(
+def test_group_update_mutation_remove_some_users_from_group_with_manage_staff(
staff_users,
- permission_manage_users,
+ permission_group_manage_users,
+ permission_group_manage_staff,
permission_manage_staff,
staff_api_client,
- permission_group_manage_users,
):
"""Ensure that user can remove some of user group if group has manage
staff permission.
"""
staff_user, staff_user1, staff_user2 = staff_users
group = permission_group_manage_users
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_staff)
group.permissions.add(permission_manage_staff)
-
group.user_set.add(staff_user1, staff_user2)
- staff_user.user_permissions.add(permission_manage_users)
+ assert group.user_set.count() == 3
+
query = PERMISSION_GROUP_UPDATE_MUTATION
variables = {
"id": graphene.Node.to_global_id("Group", group.id),
"input": {"removeUsers": [graphene.Node.to_global_id("User", staff_user1.id)]},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=(permission_manage_staff,)
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["permissionGroupUpdate"]
errors = data["errors"]
@@ -1805,12 +2270,13 @@ def test_group_update_mutation_remove_some_users_from_group_with_manage_stuff(
assert not errors
assert group_data["name"] == group.name
- assert len(group_data["users"]) == 1
- assert group_data["users"][0]["email"] == staff_user2.email
+ assert len(group_data["users"]) == 2
+ assert staff_user1.email not in [user["email"] for user in group_data["users"]]
def test_group_update_mutation_remove_some_users_from_group_user_with_manage_stuff(
staff_users,
+ permission_group_manage_users,
permission_manage_users,
permission_manage_staff,
staff_api_client,
@@ -1832,7 +2298,7 @@ def test_group_update_mutation_remove_some_users_from_group_user_with_manage_stu
group1.user_set.add(staff_user1, staff_user2)
group2.user_set.add(staff_user2)
- staff_user.user_permissions.add(permission_manage_users)
+ staff_user.groups.add(permission_group_manage_users)
query = PERMISSION_GROUP_UPDATE_MUTATION
variables = {
"id": graphene.Node.to_global_id("Group", group1.id),
@@ -1855,6 +2321,8 @@ def test_group_update_mutation_remove_some_users_from_group_user_with_manage_stu
def test_permission_group_update_mutation_remove_user_with_manage_staff(
staff_users,
+ permission_group_manage_users,
+ permission_group_manage_orders,
permission_manage_users,
permission_manage_staff,
permission_manage_orders,
@@ -1875,7 +2343,7 @@ def test_permission_group_update_mutation_remove_user_with_manage_staff(
group1.user_set.add(staff_user1, staff_user2)
group2.user_set.add(staff_user2)
- staff_user.user_permissions.add(permission_manage_users, permission_manage_orders)
+ staff_user.groups.add(permission_group_manage_users, permission_group_manage_orders)
query = PERMISSION_GROUP_UPDATE_MUTATION
variables = {
"id": graphene.Node.to_global_id("Group", group1.id),
@@ -1905,6 +2373,7 @@ def test_permission_group_update_mutation_remove_user_with_manage_staff(
def test_permission_group_update_mutation_remove_user_with_manage_staff_add_user(
staff_users,
+ permission_group_manage_users,
permission_manage_users,
permission_manage_staff,
permission_manage_orders,
@@ -1926,7 +2395,7 @@ def test_permission_group_update_mutation_remove_user_with_manage_staff_add_user
group1.user_set.add(staff_user1, staff_user2)
group2.user_set.add(staff_user2, staff_user)
- staff_user.user_permissions.add(permission_manage_users)
+ staff_user.groups.add(permission_group_manage_users)
query = PERMISSION_GROUP_UPDATE_MUTATION
variables = {
"id": graphene.Node.to_global_id("Group", group1.id),
@@ -2224,13 +2693,12 @@ def test_group_delete_mutation_left_not_manageable_permission(
def test_group_delete_mutation_delete_last_group(
staff_users,
- permission_group_manage_users,
staff_api_client,
permission_manage_staff,
- permission_manage_users,
+ permission_group_manage_users,
):
staff_user, staff_user1, staff_user2 = staff_users
- staff_user.user_permissions.add(permission_manage_users)
+ staff_user.groups.add(permission_group_manage_users)
group = permission_group_manage_users
query = PERMISSION_GROUP_DELETE_MUTATION
@@ -2260,7 +2728,7 @@ def test_group_delete_mutation_delete_last_group_with_manage_staff(
permission_manage_users,
):
staff_user, staff_user1, staff_user2 = staff_users
- staff_user.user_permissions.add(permission_manage_users)
+ staff_user.groups.add(permission_group_manage_users)
groups = Group.objects.bulk_create(
[Group(name="manage users and staff"), Group(name="manage users")]
)
@@ -2330,271 +2798,40 @@ def test_group_delete_mutation_cannot_remove_requestor_last_group(
)
-QUERY_PERMISSION_GROUP_WITH_FILTER = """
- query ($filter: PermissionGroupFilterInput ){
- permissionGroups(first: 5, filter: $filter){
- edges{
- node{
- id
- name
- permissions{
- name
- code
- }
- users {
- email
- }
- userCanManage
- }
- }
- }
- }
- """
-
-
- "permission_group_filter, count",
- (({"search": "Manage user groups"}, 1), ({"search": "Manage"}, 2), ({}, 3)),
-)
-def test_permission_groups_query(
- permission_group_manage_users,
- staff_user,
- permission_manage_staff,
- staff_api_client,
- permission_group_filter,
- count,
-):
- staff_user.user_permissions.add(permission_manage_staff)
- query = QUERY_PERMISSION_GROUP_WITH_FILTER
-
- Group.objects.bulk_create(
- [Group(name="Manage product."), Group(name="Remove product.")]
- )
-
- variables = {"filter": permission_group_filter}
- response = staff_api_client.post_graphql(query, variables)
- content = get_graphql_content(response)
- data = content["data"]["permissionGroups"]["edges"]
-
- assert len(data) == count
-
-
-def test_permission_groups_query_with_filter_by_ids(
- permission_group_manage_users,
+def test_group_delete_mutation_no_channel_access(
+ staff_users,
+ permission_group_all_perms_channel_USD_only,
permission_manage_staff,
+ permission_manage_orders,
+ permission_manage_products,
staff_api_client,
):
# given
- query = QUERY_PERMISSION_GROUP_WITH_FILTER
- variables = {
- "filter": {
- "ids": [
- graphene.Node.to_global_id("Group", permission_group_manage_users.pk)
- ]
- }
- }
-
- # when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_staff]
- )
- content = get_graphql_content(response)
-
- # then
- data = content["data"]["permissionGroups"]["edges"]
- assert len(data) == 1
-
-
-def test_permission_groups_no_permission_to_perform(
- permission_group_manage_users,
- permission_manage_staff,
- staff_api_client,
-):
- query = QUERY_PERMISSION_GROUP_WITH_FILTER
-
- variables = {"filter": {"search": "Manage user groups"}}
- response = staff_api_client.post_graphql(query, variables)
- assert_no_permission(response)
-
-
-QUERY_PERMISSION_GROUP_WITH_SORT = """
- query ($sort_by: PermissionGroupSortingInput!) {
- permissionGroups(first:5, sortBy: $sort_by) {
- edges{
- node{
- name
- }
- }
- }
- }
-"""
-
-
- "permission_group_sort, result",
- (
- (
- {"field": "NAME", "direction": "ASC"},
- ["Add", "Manage user groups.", "Remove"],
- ),
- (
- {"field": "NAME", "direction": "DESC"},
- ["Remove", "Manage user groups.", "Add"],
- ),
- ),
-)
-def test_permission_group_with_sort(
- permission_group_manage_users,
- staff_user,
- permission_manage_staff,
- staff_api_client,
- permission_group_sort,
- result,
-):
- staff_user.user_permissions.add(permission_manage_staff)
- query = QUERY_PERMISSION_GROUP_WITH_SORT
-
- Group.objects.bulk_create([Group(name="Add"), Group(name="Remove")])
-
- variables = {"sort_by": permission_group_sort}
- response = staff_api_client.post_graphql(query, variables)
- content = get_graphql_content(response)
- data = content["data"]["permissionGroups"]["edges"]
-
- for order, group_name in enumerate(result):
- assert data[order]["node"]["name"] == group_name
-
-
-QUERY_PERMISSION_GROUP = """
- query ($id: ID!){
- permissionGroup(id: $id){
- id
- name
- permissions {
- name
- code
- }
- users{
- email
- }
- userCanManage
- }
- }
- """
-
-
-def test_permission_group_query(
- permission_group_manage_users,
- staff_user,
- permission_manage_staff,
- permission_manage_users,
- staff_api_client,
-):
- staff_user.user_permissions.add(permission_manage_staff, permission_manage_users)
- group = permission_group_manage_users
- query = QUERY_PERMISSION_GROUP
-
- group_staff_user = group.user_set.first()
-
- variables = {"id": graphene.Node.to_global_id("Group", group.id)}
- response = staff_api_client.post_graphql(query, variables)
- content = get_graphql_content(response)
- data = content["data"]["permissionGroup"]
-
- assert data["name"] == group.name
- assert len(data["users"]) == 1
- assert data["users"][0]["email"] == group_staff_user.email
- result_permissions = {permission["name"] for permission in data["permissions"]}
- assert (
- set(group.permissions.all().values_list("name", flat=True))
- == result_permissions
+ staff_user, staff_user1, staff_user2 = staff_users
+ staff_user.groups.add(permission_group_all_perms_channel_USD_only)
+ groups = Group.objects.bulk_create(
+ [Group(name="manage orders"), Group(name="manage orders and products")]
)
- permissions_codes = {
- permission["code"].lower() for permission in data["permissions"]
- }
- assert (
- set(group.permissions.all().values_list("codename", flat=True))
- == permissions_codes
+ group1, group2 = groups
+ group1.permissions.add(permission_manage_orders, permission_manage_staff)
+ group2.permissions.add(
+ permission_manage_orders, permission_manage_products, permission_manage_staff
)
- assert data["userCanManage"] is True
-
-
-def test_permission_group_query_user_cannot_manage(
- permission_group_manage_users,
- staff_user,
- permission_manage_staff,
- staff_api_client,
-):
- staff_user.user_permissions.add(permission_manage_staff)
- group = permission_group_manage_users
- query = QUERY_PERMISSION_GROUP
-
- group_staff_user = group.user_set.first()
- variables = {"id": graphene.Node.to_global_id("Group", group.id)}
- response = staff_api_client.post_graphql(query, variables)
- content = get_graphql_content(response)
- data = content["data"]["permissionGroup"]
-
- assert data["name"] == group.name
- assert len(data["users"]) == 1
- assert data["users"][0]["email"] == group_staff_user.email
- result_permissions = {permission["name"] for permission in data["permissions"]}
- assert (
- set(group.permissions.all().values_list("name", flat=True))
- == result_permissions
- )
- permissions_codes = {
- permission["code"].lower() for permission in data["permissions"]
- }
- assert (
- set(group.permissions.all().values_list("codename", flat=True))
- == permissions_codes
- )
- assert data["userCanManage"] is False
+ staff_user2.groups.add(group1, group2)
+ query = PERMISSION_GROUP_DELETE_MUTATION
-def test_permission_group_no_permission_to_perform(
- permission_group_manage_users,
- permission_manage_staff,
- staff_api_client,
-):
- group = permission_group_manage_users
- query = QUERY_PERMISSION_GROUP
+ variables = {"id": graphene.Node.to_global_id("Group", group1.id)}
- variables = {"id": graphene.Node.to_global_id("Group", group.id)}
+ # when
response = staff_api_client.post_graphql(query, variables)
- assert_no_permission(response)
-
-
-def test_query_permission_group_by_invalid_id(
- staff_api_client,
- staff_user,
- permission_group_manage_users,
- permission_manage_users,
- permission_manage_staff,
-):
- staff_user.user_permissions.add(permission_manage_staff, permission_manage_users)
- id = "bh/"
- variables = {"id": id}
- response = staff_api_client.post_graphql(QUERY_PERMISSION_GROUP, variables)
- content = get_graphql_content_from_response(response)
- assert len(content["errors"]) == 1
- assert content["errors"][0]["message"] == f"Couldn't resolve id: {id}."
- assert content["data"]["permissionGroup"] is None
-
-def test_query_permission_group_with_invalid_object_type(
- staff_api_client,
- staff_user,
- permission_group_manage_users,
- permission_manage_staff,
- permission_manage_users,
-):
- staff_user.user_permissions.add(permission_manage_staff, permission_manage_users)
- variables = {
- "id": graphene.Node.to_global_id("Order", permission_group_manage_users.pk)
- }
- response = staff_api_client.post_graphql(QUERY_PERMISSION_GROUP, variables)
+ # then
content = get_graphql_content(response)
- assert content["data"]["permissionGroup"] is None
+ data = content["data"]["permissionGroupDelete"]
+ errors = data["errors"]
+
+ assert not data["group"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PermissionGroupErrorCode.OUT_OF_SCOPE_CHANNEL.name
diff --git a/saleor/graphql/account/tests/test_account_utils.py b/saleor/graphql/account/tests/test_account_utils.py
index d114cc691d..feb42073ba 100644
--- a/saleor/graphql/account/tests/test_account_utils.py
+++ b/saleor/graphql/account/tests/test_account_utils.py
@@ -1,5 +1,6 @@
from ....account.models import Group, User
from ....app.models import App
+from ....channel.models import Channel
from ....permission.enums import (
AccountPermissions,
OrderPermissions,
@@ -8,6 +9,8 @@ from ....permission.enums import (
from ..utils import (
can_manage_app,
can_user_manage_group,
+ can_user_manage_group_channels,
+ can_user_manage_group_permissions,
get_group_permission_codes,
get_group_to_permissions_and_users_mapping,
get_groups_which_user_can_manage,
@@ -17,6 +20,7 @@ from ..utils import (
get_not_manageable_permissions_when_deactivate_or_remove_users,
get_out_of_scope_permissions,
get_out_of_scope_users,
+ get_user_accessible_channels,
get_user_permissions,
get_users_and_look_for_permissions_in_groups_with_manage_staff,
is_owner_or_has_one_of_perms,
@@ -24,10 +28,74 @@ from ..utils import (
)
+def test_can_user_manage_group_is_true(
+ info,
+ staff_user,
+ permission_group_manage_users,
+ permission_group_all_perms_all_channels,
+):
+ # given
+ staff_user.groups.add(permission_group_all_perms_all_channels)
+
+ # when
+ can_manage = can_user_manage_group(info, staff_user, permission_group_manage_users)
+
+ # then
+ can_manage is True
+
+
+def test_can_user_manage_group_superuser(
+ info, superuser, permission_group_all_perms_all_channels
+):
+ # when
+ can_manage = can_user_manage_group(
+ info, superuser, permission_group_all_perms_all_channels
+ )
+
+ # then
+ can_manage is True
+
+
+def test_can_user_manage_group_no_channel_access(
+ info,
+ staff_user,
+ permission_group_all_perms_channel_USD_only,
+ permission_group_manage_apps,
+):
+ # given
+ staff_user.groups.add(permission_group_all_perms_channel_USD_only)
+
+ # when
+ can_manage = can_user_manage_group(info, staff_user, permission_group_manage_apps)
+
+ # then
+ can_manage is False
+
+
+def test_can_user_manage_group_no_permissions(
+ info,
+ staff_user,
+ permission_group_manage_staff,
+ permission_group_all_perms_all_channels,
+):
+ # given
+ staff_user.groups.add(permission_group_manage_staff)
+
+ # when
+ can_manage = can_user_manage_group(
+ info, staff_user, permission_group_all_perms_all_channels
+ )
+
+ # then
+ can_manage is False
+
+
def test_can_manage_group_user_without_permissions(
staff_user, permission_group_manage_users
):
- result = can_user_manage_group(staff_user, permission_group_manage_users)
+ result = can_user_manage_group_permissions(
+ staff_user, permission_group_manage_users
+ )
assert result is False
@@ -38,28 +106,106 @@ def test_can_manage_group_user_with_different_permissions(
permission_manage_orders,
):
staff_user.user_permissions.add(permission_manage_orders)
- result = can_user_manage_group(staff_user, permission_group_manage_users)
+ result = can_user_manage_group_permissions(
+ staff_user, permission_group_manage_users
+ )
assert result is False
-def test_can_manage_group(
+def test_can_manage_group_permissions(
staff_user,
permission_group_manage_users,
permission_manage_users,
permission_manage_orders,
):
staff_user.user_permissions.add(permission_manage_users, permission_manage_orders)
- result = can_user_manage_group(staff_user, permission_group_manage_users)
+ result = can_user_manage_group_permissions(
+ staff_user, permission_group_manage_users
+ )
assert result is True
-def test_can_manage_group_user_superuser(
+def test_can_manage_group_permissions_user_superuser(
admin_user, permission_group_manage_users, permission_manage_orders
):
- result = can_user_manage_group(admin_user, permission_group_manage_users)
+ result = can_user_manage_group_permissions(
+ admin_user, permission_group_manage_users
+ )
assert result is True
+def test_can_user_manage_group_channels(
+ info,
+ staff_user,
+ permission_group_no_perms_all_channels,
+ permission_group_manage_users,
+):
+ # given
+ staff_user.groups.add(permission_group_manage_users)
+
+ # when
+ can_manage = can_user_manage_group_channels(
+ info, staff_user, permission_group_no_perms_all_channels
+ )
+
+ # then
+ assert can_manage is True
+
+
+def test_can_user_manage_group_channels_user_with_restricted_channel_access(
+ info,
+ staff_user,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+ channel_USD,
+):
+ # given
+ group = Group.objects.create(
+ name="Group with USD and PLN channel access.",
+ restricted_access_to_channels=True,
+ )
+ group.channels.add(channel_USD, channel_PLN)
+ staff_user.groups.add(group)
+
+ # when
+ can_manage = can_user_manage_group_channels(
+ info, staff_user, permission_group_all_perms_channel_USD_only
+ )
+
+ # then
+ assert can_manage is True
+
+
+def test_can_user_manage_group_channels_superuser(
+ info, superuser, permission_group_no_perms_all_channels
+):
+ # when
+ can_manage = can_user_manage_group_channels(
+ info, superuser, permission_group_no_perms_all_channels
+ )
+
+ # then
+ assert can_manage is True
+
+
+def test_can_user_manage_group_channels_no_channel_access(
+ info,
+ staff_user,
+ permission_group_all_perms_channel_USD_only,
+ permission_group_no_perms_all_channels,
+):
+ # given
+ staff_user.groups.add(permission_group_all_perms_channel_USD_only)
+
+ # when
+ can_manage = can_user_manage_group_channels(
+ info, staff_user, permission_group_no_perms_all_channels
+ )
+
+ # then
+ assert can_manage is False
+
+
def test_get_out_of_scope_permissions_user_has_all_permissions(
staff_user, permission_manage_orders, permission_manage_users
):
@@ -900,3 +1046,51 @@ def test_requestor_has_access_no_access_by_staff(
# then
assert result is False
+
+
+def test_get_user_accessible_channels_all_channels(
+ staff_user, permission_group_all_perms_all_channels, info, channel_PLN, channel_USD
+):
+ # given
+ permission_group_all_perms_all_channels.user_set.add(staff_user)
+
+ # when
+ channels = get_user_accessible_channels(info, staff_user)
+
+ # then
+ assert len(channels) == Channel.objects.count()
+
+
+def test_get_user_accessible_channels_some_channels(
+ staff_user,
+ permission_group_all_perms_channel_USD_only,
+ info,
+ channel_PLN,
+ channel_USD,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_user)
+
+ # when
+ channels = get_user_accessible_channels(info, staff_user)
+
+ # then
+ assert len(channels) == 1
+ assert channels[0] == channel_USD
+
+
+def test_get_user_accessible_channels_restricted_access_no_channels(
+ staff_user,
+ permission_group_all_perms_without_any_channel,
+ info,
+ channel_PLN,
+ channel_USD,
+):
+ # given
+ permission_group_all_perms_without_any_channel.user_set.add(staff_user)
+
+ # when
+ channels = get_user_accessible_channels(info, staff_user)
+
+ # then
+ assert len(channels) == 0
diff --git a/saleor/graphql/account/tests/test_permission_group_queries.py b/saleor/graphql/account/tests/test_permission_group_queries.py
new file mode 100644
index 0000000000..ef422507bf
--- /dev/null
+++ b/saleor/graphql/account/tests/test_permission_group_queries.py
@@ -0,0 +1,363 @@
+import graphene
+import pytest
+
+from ....account.models import Group
+from ....channel.models import Channel
+from ...tests.utils import (
+ assert_no_permission,
+ get_graphql_content,
+ get_graphql_content_from_response,
+)
+
+QUERY_PERMISSION_GROUP_WITH_FILTER = """
+query ($filter: PermissionGroupFilterInput ){
+ permissionGroups(first: 5, filter: $filter){
+ edges{
+ node{
+ id
+ name
+ permissions{
+ name
+ code
+ }
+ users {
+ email
+ }
+ userCanManage
+ }
+ }
+ }
+}
+"""
+
+
+ "permission_group_filter, count",
+ (({"search": "Manage user groups"}, 1), ({"search": "Manage"}, 2), ({}, 3)),
+)
+def test_permission_groups_query(
+ permission_group_manage_users,
+ staff_user,
+ permission_manage_staff,
+ staff_api_client,
+ permission_group_filter,
+ count,
+):
+ staff_user.user_permissions.add(permission_manage_staff)
+ query = QUERY_PERMISSION_GROUP_WITH_FILTER
+
+ Group.objects.bulk_create(
+ [Group(name="Manage product."), Group(name="Remove product.")]
+ )
+
+ variables = {"filter": permission_group_filter}
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["permissionGroups"]["edges"]
+
+ assert len(data) == count
+
+
+def test_permission_groups_query_with_filter_by_ids(
+ permission_group_manage_users,
+ permission_manage_staff,
+ staff_api_client,
+):
+ # given
+ query = QUERY_PERMISSION_GROUP_WITH_FILTER
+ variables = {
+ "filter": {
+ "ids": [
+ graphene.Node.to_global_id("Group", permission_group_manage_users.pk)
+ ]
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_staff]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["permissionGroups"]["edges"]
+ assert len(data) == 1
+
+
+def test_permission_groups_no_permission_to_perform(
+ permission_group_manage_users,
+ permission_manage_staff,
+ staff_api_client,
+):
+ query = QUERY_PERMISSION_GROUP_WITH_FILTER
+
+ variables = {"filter": {"search": "Manage user groups"}}
+ response = staff_api_client.post_graphql(query, variables)
+ assert_no_permission(response)
+
+
+QUERY_PERMISSION_GROUP_WITH_SORT = """
+query ($sort_by: PermissionGroupSortingInput!) {
+ permissionGroups(first:5, sortBy: $sort_by) {
+ edges{
+ node{
+ name
+ }
+ }
+ }
+}
+"""
+
+
+ "permission_group_sort, result",
+ (
+ (
+ {"field": "NAME", "direction": "ASC"},
+ ["Add", "Manage user group.", "Remove"],
+ ),
+ (
+ {"field": "NAME", "direction": "DESC"},
+ ["Remove", "Manage user group.", "Add"],
+ ),
+ ),
+)
+def test_permission_group_with_sort(
+ permission_group_manage_users,
+ staff_user,
+ permission_manage_staff,
+ staff_api_client,
+ permission_group_sort,
+ result,
+):
+ staff_user.user_permissions.add(permission_manage_staff)
+ query = QUERY_PERMISSION_GROUP_WITH_SORT
+
+ Group.objects.bulk_create([Group(name="Add"), Group(name="Remove")])
+
+ variables = {"sort_by": permission_group_sort}
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["permissionGroups"]["edges"]
+
+ for order, group_name in enumerate(result):
+ assert data[order]["node"]["name"] == group_name
+
+
+QUERY_PERMISSION_GROUP = """
+query ($id: ID!){
+ permissionGroup(id: $id){
+ id
+ name
+ permissions {
+ name
+ code
+ }
+ users{
+ email
+ }
+ userCanManage
+ accessibleChannels {
+ slug
+ }
+ restrictedAccessToChannels
+ }
+}
+"""
+
+
+def test_permission_group_query(
+ permission_group_manage_users,
+ staff_user,
+ permission_manage_staff,
+ permission_manage_users,
+ staff_api_client,
+):
+ staff_user.user_permissions.add(permission_manage_staff, permission_manage_users)
+ group = permission_group_manage_users
+ query = QUERY_PERMISSION_GROUP
+
+ group_staff_user = group.user_set.first()
+
+ variables = {"id": graphene.Node.to_global_id("Group", group.id)}
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["permissionGroup"]
+
+ assert data["name"] == group.name
+ assert len(data["users"]) == 1
+ assert data["users"][0]["email"] == group_staff_user.email
+ result_permissions = {permission["name"] for permission in data["permissions"]}
+ assert (
+ set(group.permissions.all().values_list("name", flat=True))
+ == result_permissions
+ )
+ permissions_codes = {
+ permission["code"].lower() for permission in data["permissions"]
+ }
+ assert (
+ set(group.permissions.all().values_list("codename", flat=True))
+ == permissions_codes
+ )
+ assert data["userCanManage"] is True
+
+
+def test_permission_group_query_user_cannot_manage(
+ permission_group_manage_users,
+ staff_user,
+ permission_manage_staff,
+ staff_api_client,
+):
+ staff_user.user_permissions.add(permission_manage_staff)
+ group = permission_group_manage_users
+ query = QUERY_PERMISSION_GROUP
+
+ group_staff_user = group.user_set.first()
+
+ variables = {"id": graphene.Node.to_global_id("Group", group.id)}
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["permissionGroup"]
+
+ assert data["name"] == group.name
+ assert len(data["users"]) == 1
+ assert data["users"][0]["email"] == group_staff_user.email
+ result_permissions = {permission["name"] for permission in data["permissions"]}
+ assert (
+ set(group.permissions.all().values_list("name", flat=True))
+ == result_permissions
+ )
+ permissions_codes = {
+ permission["code"].lower() for permission in data["permissions"]
+ }
+ assert (
+ set(group.permissions.all().values_list("codename", flat=True))
+ == permissions_codes
+ )
+ assert data["userCanManage"] is False
+
+
+def test_permission_group_no_permission_to_perform(
+ permission_group_manage_users,
+ permission_manage_staff,
+ staff_api_client,
+):
+ group = permission_group_manage_users
+ query = QUERY_PERMISSION_GROUP
+
+ variables = {"id": graphene.Node.to_global_id("Group", group.id)}
+ response = staff_api_client.post_graphql(query, variables)
+ assert_no_permission(response)
+
+
+def test_query_permission_group_by_invalid_id(
+ staff_api_client,
+ staff_user,
+ permission_group_manage_users,
+ permission_manage_users,
+ permission_manage_staff,
+):
+ staff_user.user_permissions.add(permission_manage_staff, permission_manage_users)
+ id = "bh/"
+ variables = {"id": id}
+ response = staff_api_client.post_graphql(QUERY_PERMISSION_GROUP, variables)
+ content = get_graphql_content_from_response(response)
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["message"] == f"Couldn't resolve id: {id}."
+ assert content["data"]["permissionGroup"] is None
+
+
+def test_query_permission_group_with_invalid_object_type(
+ staff_api_client,
+ staff_user,
+ permission_group_manage_users,
+ permission_manage_staff,
+ permission_manage_users,
+):
+ staff_user.user_permissions.add(permission_manage_staff, permission_manage_users)
+ variables = {
+ "id": graphene.Node.to_global_id("Order", permission_group_manage_users.pk)
+ }
+ response = staff_api_client.post_graphql(QUERY_PERMISSION_GROUP, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["permissionGroup"] is None
+
+
+def test_query_permission_group_without_restricted_access_to_channels(
+ staff_api_client,
+ staff_user,
+ permission_group_all_perms_all_channels,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ group = permission_group_all_perms_all_channels
+ group.user_set.add(staff_user)
+
+ variables = {"id": graphene.Node.to_global_id("Group", group.id)}
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_PERMISSION_GROUP, variables)
+
+ # then
+
+ content = get_graphql_content(response)
+ group_data = content["data"]["permissionGroup"]
+ assert group_data["name"] == group.name
+ assert group_data["restrictedAccessToChannels"] is False
+ assert len(group_data["accessibleChannels"]) == 2
+
+
+def test_query_permission_group_with_restricted_access_to_channels(
+ staff_api_client,
+ staff_user,
+ permission_group_all_perms_channel_USD_only,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ group = permission_group_all_perms_channel_USD_only
+ group.user_set.add(staff_user)
+
+ assert Channel.objects.count() > 1
+
+ variables = {"id": graphene.Node.to_global_id("Group", group.id)}
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_PERMISSION_GROUP, variables)
+
+ # then
+
+ content = get_graphql_content(response)
+ group_data = content["data"]["permissionGroup"]
+ assert group_data["name"] == group.name
+ assert group_data["restrictedAccessToChannels"] is True
+ assert len(group_data["accessibleChannels"]) == 1
+ assert group_data["accessibleChannels"][0]["slug"] == channel_USD.slug
+
+
+def test_query_permission_group_with_restricted_access_to_channels_no_channels_assigned(
+ staff_api_client,
+ staff_user,
+ permission_group_all_perms_without_any_channel,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ group = permission_group_all_perms_without_any_channel
+ group.user_set.add(staff_user)
+
+ assert Channel.objects.count() > 1
+
+ variables = {"id": graphene.Node.to_global_id("Group", group.id)}
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_PERMISSION_GROUP, variables)
+
+ # then
+
+ content = get_graphql_content(response)
+ group_data = content["data"]["permissionGroup"]
+ assert group_data["name"] == group.name
+ assert group_data["restrictedAccessToChannels"] is True
+ assert len(group_data["accessibleChannels"]) == 0
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index 88bc754889..3048845942 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -5,6 +5,7 @@ from typing import List, Optional, cast
import graphene
from django.contrib.auth import get_user_model
from graphene import relay
+from promise import Promise
from ...account import models
from ...checkout.utils import get_user_checkout
@@ -20,11 +21,18 @@ from ...thumbnail.utils import (
from ..account.utils import check_is_owner_or_has_one_of_perms
from ..app.dataloaders import AppByIdLoader, get_app_promise
from ..app.types import App
+from ..channel.types import Channel
from ..checkout.dataloaders import CheckoutByUserAndChannelLoader, CheckoutByUserLoader
from ..checkout.types import Checkout, CheckoutCountableConnection
from ..core import ResolveInfo
from ..core.connection import CountableConnection, create_connection_slice
-from ..core.descriptions import ADDED_IN_38, ADDED_IN_310, DEPRECATED_IN_3X_FIELD
+from ..core.descriptions import (
+ ADDED_IN_38,
+ ADDED_IN_310,
+ ADDED_IN_314,
+ DEPRECATED_IN_3X_FIELD,
+ PREVIEW_FEATURE,
+)
from ..core.doc_category import DOC_CATEGORY_USERS
from ..core.enums import LanguageCodeEnum
from ..core.federation import federated_entity, resolve_federation_references
@@ -48,7 +56,10 @@ from ..order.dataloaders import OrderLineByIdLoader, OrdersByUserLoader
from ..plugins.dataloaders import get_plugin_manager_promise
from ..utils import format_permissions_for_display, get_user_or_app_from_context
from .dataloaders import (
+ AccessibleChannelsByGroupIdLoader,
+ AccessibleChannelsByUserIdLoader,
CustomerEventsByUserLoader,
+ RestrictedChannelAccessByUserIdLoader,
ThumbnailByUserIdSizeAndFormatLoader,
)
from .enums import CountryCodeEnum, CustomerEventsEnum
@@ -321,6 +332,23 @@ class User(ModelObjectType[models.User]):
"saleor.graphql.account.types.Group",
description="List of user's permission groups which user can manage.",
)
+ accessible_channels = NonNullList(
+ Channel,
+ description=(
+ "List of channels the user has access to. The sum of channels from all "
+ "user groups. If at least one group has `restrictedAccessToChannels` "
+ "set to False - all channels are returned." + ADDED_IN_314 + PREVIEW_FEATURE
+ ),
+ )
+ restricted_access_to_channels = graphene.Boolean(
+ required=True,
+ description=(
+ "Determine if user have restricted access to channels. False if at least "
+ "one user group has `restrictedAccessToChannels` set to False."
+ )
+ + ADDED_IN_314
+ + PREVIEW_FEATURE,
+ )
avatar = ThumbnailField()
events = PermissionsField(
NonNullList(CustomerEvent),
@@ -449,6 +477,18 @@ class User(ModelObjectType[models.User]):
def resolve_editable_groups(root: models.User, _info: ResolveInfo):
return get_groups_which_user_can_manage(root)
+ @staticmethod
+ def resolve_accessible_channels(root: models.Group, info: ResolveInfo):
+ # Sum of channels from all user groups. If at least one group has
+ # `restrictedAccessToChannels` set to False - all channels are returned
+ return AccessibleChannelsByUserIdLoader(info.context).load(root.id)
+
+ @staticmethod
+ def resolve_restricted_access_to_channels(root: models.Group, info: ResolveInfo):
+ # Returns False if at least one user group has `restrictedAccessToChannels`
+ # set to False
+ return RestrictedChannelAccessByUserIdLoader(info.context).load(root.id)
+
@staticmethod
def resolve_note(root: models.User, _info: ResolveInfo):
return root.note
@@ -474,18 +514,34 @@ class User(ModelObjectType[models.User]):
)
requester = user_or_app
- def _resolve_orders(orders):
+ def _resolve_orders(data):
+ orders = data[0]
+ accessible_channels = data[1] if len(data) == 2 else None
if not requester.has_perm(OrderPermissions.MANAGE_ORDERS):
# allow fetch requestor orders (except drafts)
orders = [
order for order in orders if order.status != OrderStatus.DRAFT
]
+ # Return only orders from channels that the user has access to.
+ # The app has access to all channels.
+ if root != user_or_app and accessible_channels is not None:
+ accessible_channels = [channel.id for channel in accessible_channels]
+ orders = [
+ order for order in orders if order.channel_id in accessible_channels
+ ]
+
return create_connection_slice(
orders, info, kwargs, OrderCountableConnection
)
- return OrdersByUserLoader(info.context).load(root.id).then(_resolve_orders)
+ to_fetch = [OrdersByUserLoader(info.context).load(root.id)]
+ if isinstance(requester, models.User):
+ to_fetch.append(
+ AccessibleChannelsByUserIdLoader(info.context).load(requester.id)
+ )
+
+ return Promise.all(to_fetch).then(_resolve_orders)
@staticmethod
def resolve_avatar(
@@ -657,6 +713,18 @@ class Group(ModelObjectType[models.Group]):
"True, if the currently authenticated user has rights to manage a group."
),
)
+ accessible_channels = NonNullList(
+ Channel,
+ description="List of channels the group has access to."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE,
+ )
+ restricted_access_to_channels = graphene.Boolean(
+ required=True,
+ description="Determine if the group have restricted access to channels."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE,
+ )
class Meta:
description = "Represents permission group data."
@@ -680,7 +748,11 @@ class Group(ModelObjectType[models.Group]):
user = info.context.user
if not user:
return False
- return can_user_manage_group(user, root)
+ return can_user_manage_group(info, user, root)
+
+ @staticmethod
+ def resolve_accessible_channels(root: models.Group, info: ResolveInfo):
+ return AccessibleChannelsByGroupIdLoader(info.context).load(root.id)
@staticmethod
def __resolve_references(roots: List["Group"], info: ResolveInfo):
diff --git a/saleor/graphql/account/utils.py b/saleor/graphql/account/utils.py
index 2e3acd858c..732e259860 100644
--- a/saleor/graphql/account/utils.py
+++ b/saleor/graphql/account/utils.py
@@ -17,6 +17,10 @@ from ...permission.enums import AccountPermissions
from ...permission.utils import has_one_of_permissions
from ..app.dataloaders import get_app_promise
from ..core import ResolveInfo, SaleorContext
+from .dataloaders import (
+ AccessibleChannelsByGroupIdLoader,
+ AccessibleChannelsByUserIdLoader,
+)
if TYPE_CHECKING:
from django.db.models import QuerySet
@@ -218,12 +222,30 @@ def get_out_of_scope_users(root_user: "User", users: List["User"]):
return out_of_scope_users
-def can_user_manage_group(user: "User", group: Group) -> bool:
+def can_user_manage_group(info, user: "User", group: Group) -> bool:
+ """User can't manage a group with permission or channel that is out of his scope."""
+ return can_user_manage_group_permissions(
+ user, group
+ ) and can_user_manage_group_channels(info, user, group)
+
+
+def can_user_manage_group_permissions(user: "User", group: Group) -> bool:
"""User can't manage a group with permission that is out of the user's scope."""
permissions = get_group_permission_codes(group)
return user.has_perms(permissions)
+def can_user_manage_group_channels(info, user: "User", group: Group) -> bool:
+ """User can't manage a group with channel that is out of the user's scope."""
+ if user.is_superuser:
+ return True
+ accessible_channels = set(get_user_accessible_channels(info, user))
+ group_channels = set(
+ AccessibleChannelsByGroupIdLoader(info.context).load(group.id).get()
+ )
+ return not bool(group_channels - accessible_channels)
+
+
def can_manage_app(requestor: Union["User", "App", None], app: "App") -> bool:
"""Requestor can't manage app with wider scope of permissions."""
permissions = app.get_permissions()
@@ -510,3 +532,11 @@ def check_is_owner_or_has_one_of_perms(
"""
if not is_owner_or_has_one_of_perms(requestor, owner, *perms):
raise PermissionDenied(permissions=list(perms) + [AuthorizationFilters.OWNER])
+
+
+def get_user_accessible_channels(info, user: Optional[User]):
+ return (
+ (AccessibleChannelsByUserIdLoader(info.context).load(user.id).get())
+ if user is not None
+ else []
+ )
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index 1651c20caa..bcb7b24084 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -41,14 +41,15 @@ from ...permission.utils import (
message_one_of_permissions_required,
one_of_permissions_or_auth_filter_required,
)
-from ..core import ResolveInfo
+from ..account.utils import get_user_accessible_channels
+from ..app.dataloaders import get_app_promise
from ..core.doc_category import DOC_CATEGORY_MAP
-from ..core.utils import ext_ref_to_global_id_or_error
from ..core.validators import validate_one_of_args_is_in_mutation
from ..meta.permissions import PRIVATE_META_PERMISSION_MAP, PUBLIC_META_PERMISSION_MAP
from ..payment.utils import metadata_contains_empty_key
from ..plugins.dataloaders import get_plugin_manager_promise
from ..utils import get_nodes, resolve_global_ids_to_primary_keys
+from . import ResolveInfo
from .context import disallow_replica_in_context, setup_context_user
from .descriptions import DEPRECATED_IN_3X_FIELD
from .types import (
@@ -59,7 +60,11 @@ from .types import (
Upload,
UploadError,
)
-from .utils import from_global_id_or_error, snake_to_camel_case
+from .utils import (
+ ext_ref_to_global_id_or_error,
+ from_global_id_or_error,
+ snake_to_camel_case,
+)
from .utils.error_codes import get_error_code_from_error
@@ -594,6 +599,22 @@ class BaseMutation(graphene.Mutation):
f"Couldn't resolve permission to item type: {type_name}. "
)
+ @classmethod
+ def check_channel_permissions(
+ cls, info: ResolveInfo, channel_ids: Iterable[Union[UUID, int]]
+ ):
+ # App has access to all channels
+ if get_app_promise(info.context).get():
+ return
+ accessible_channels = get_user_accessible_channels(info, info.context.user)
+ accessible_channel_ids = {str(channel.id) for channel in accessible_channels}
+ channel_ids = {str(channel_id) for channel_id in channel_ids}
+ invalid_channel_ids = channel_ids - accessible_channel_ids
+ if invalid_channel_ids:
+ raise PermissionDenied(
+ message="You don't have access to some objects' channel."
+ )
+
def is_list_of_ids(field) -> bool:
if isinstance(field.type, graphene.List):
@@ -824,6 +845,41 @@ class ModelWithExtRefMutation(ModelMutation):
return cls.get_node_or_error(info, object_id, only_type=model_type, qs=qs)
+class ModelWithRestrictedChannelAccessMutation(ModelMutation):
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ """Perform model mutation.
+
+ Depending on the input data, `mutate` either creates a new instance or
+ updates an existing one. If `id` argument is present, it is assumed
+ that this is an "update" mutation. Otherwise, a new instance is
+ created based on the model associated with this mutation.
+ """
+ instance = cls.get_instance(info, **data)
+ channel_id = cls.get_instance_channel_id(instance, **data)
+ cls.check_channel_permissions(info, [channel_id])
+ data = data.get("input")
+ cleaned_input = cls.clean_input(info, instance, data)
+ metadata_list = cleaned_input.pop("metadata", None)
+ private_metadata_list = cleaned_input.pop("private_metadata", None)
+ instance = cls.construct_instance(instance, cleaned_input)
+
+ cls.validate_and_update_metadata(instance, metadata_list, private_metadata_list)
+ cls.clean_instance(info, instance)
+ cls.save(info, instance, cleaned_input)
+ cls._save_m2m(info, instance, cleaned_input)
+ cls.post_save_action(info, instance, cleaned_input)
+ return cls.success_response(instance)
+
+ @classmethod
+ def get_instance_channel_id(cls, instance, **data) -> Union[UUID, int]:
+ """Retrieve the instance channel id for channel permission accessible check."""
+ raise NotImplementedError()
+
+
class ModelDeleteMutation(ModelMutation):
class Meta:
abstract = True
@@ -854,6 +910,35 @@ class ModelDeleteMutation(ModelMutation):
return cls.success_response(instance)
+class ModelDeleteWithRestrictedChannelAccessMutation(ModelDeleteMutation):
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def perform_mutation( # type: ignore[override]
+ cls, _root, info: ResolveInfo, /, *, external_reference=None, id=None
+ ):
+ """Perform a mutation that deletes a model instance."""
+ instance = cls.get_instance(info, external_reference=external_reference, id=id)
+ channel_id = cls.get_instance_channel_id(instance)
+ cls.check_channel_permissions(info, [channel_id])
+
+ cls.clean_instance(info, instance)
+ db_id = instance.id
+ 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.
+ instance.id = db_id
+ cls.post_save_action(info, instance, None)
+ return cls.success_response(instance)
+
+ @classmethod
+ def get_instance_channel_id(cls, instance) -> Union[UUID, int]:
+ """Retrieve the instance channel id for channel permission accessible check."""
+ raise NotImplementedError()
+
+
class BaseBulkMutation(BaseMutation):
count = graphene.Int(
required=True, description="Returns how many objects were affected."
@@ -987,6 +1072,73 @@ class ModelBulkDeleteMutation(BaseBulkMutation):
queryset.delete()
+class BaseBulkWithRestrictedChannelAccessMutation(BaseBulkMutation):
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def perform_mutation( # type: ignore[override]
+ cls, _root, info: ResolveInfo, /, *, ids, **data
+ ) -> Tuple[int, Optional[ValidationError]]:
+ """Perform a mutation that deletes a list of model instances."""
+ clean_instance_ids = []
+ errors_dict: Dict[str, List[ValidationError]] = {}
+ # Allow to pass empty list for dummy mutation
+ if not ids:
+ return 0, None
+ instance_model = cls._meta.model
+ model_type = cls.get_type_for_model()
+ if not model_type:
+ raise ImproperlyConfigured(
+ f"GraphQL type for model {cls._meta.model.__name__} could not be "
+ f"resolved for {cls.__name__}"
+ )
+
+ try:
+ instances = cls.get_nodes_or_error(
+ ids, "id", model_type, schema=info.schema
+ )
+ except ValidationError as error:
+ return 0, error
+
+ channel_ids = cls.get_channel_ids(instances)
+ cls.check_channel_permissions(info, channel_ids)
+
+ for instance, node_id in zip(instances, ids):
+ instance_errors = []
+
+ # catch individual validation errors to raise them later as
+ # a single error
+ try:
+ cls.clean_instance(info, instance)
+ except ValidationError as e:
+ msg = ". ".join(e.messages)
+ instance_errors.append(msg)
+
+ if not instance_errors:
+ clean_instance_ids.append(instance.pk)
+ else:
+ instance_errors_msg = ". ".join(instance_errors)
+ ValidationError({node_id: instance_errors_msg}).update_error_dict(
+ errors_dict
+ )
+
+ if errors_dict:
+ errors = ValidationError(errors_dict)
+ else:
+ errors = None
+ count = len(clean_instance_ids)
+ if count:
+ qs = instance_model.objects.filter(pk__in=clean_instance_ids)
+ cls.bulk_action(info, qs, **data)
+ return count, errors
+
+ @classmethod
+ def get_channel_ids(cls, instances) -> Iterable[Union[UUID, int]]:
+ """Get the instances channel ids for channel permission accessible check."""
+ raise NotImplementedError()
+
+
class FileUpload(BaseMutation):
uploaded_file = graphene.Field(File)
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 2135812895..ab092a16e1 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -357,6 +357,11 @@ class PermissionGroupError(Error):
description="List of user IDs which causes the error.",
required=False,
)
+ channels = NonNullList(
+ graphene.ID,
+ description="List of chnnels IDs which causes the error.",
+ required=False,
+ )
class Meta:
doc_category = DOC_CATEGORY_USERS
diff --git a/saleor/graphql/invoice/mutations.py b/saleor/graphql/invoice/mutations.py
index ae1f9a96e6..7ee41dd226 100644
--- a/saleor/graphql/invoice/mutations.py
+++ b/saleor/graphql/invoice/mutations.py
@@ -71,6 +71,7 @@ class InvoiceRequest(ModelMutation):
cls, _root, info: ResolveInfo, /, *, number=None, order_id
):
order = cls.get_node_or_error(info, order_id, only_type=Order, field="orderId")
+ cls.check_channel_permissions(info, [order.channel_id])
cls.clean_order(order)
manager = get_plugin_manager_promise(info.context).get()
if not is_event_active_for_any_plugin("invoice_request", manager.all_plugins):
@@ -193,6 +194,7 @@ class InvoiceCreate(ModelMutation):
cls, _root, info: ResolveInfo, /, *, input, order_id
):
order = cls.get_node_or_error(info, order_id, only_type=Order, field="orderId")
+ cls.check_channel_permissions(info, [order.channel_id])
cls.clean_order(info, order)
cleaned_input = cls.clean_input(info, order, input)
@@ -241,6 +243,7 @@ class InvoiceRequestDelete(ModelMutation):
cls, _root, info: ResolveInfo, /, *, id
):
invoice = cls.get_node_or_error(info, id, only_type=Invoice)
+ cls.check_channel_permissions(info, [invoice.order.channel_id])
invoice.status = JobStatus.PENDING
invoice.save(update_fields=["status", "updated_at"])
manager = get_plugin_manager_promise(info.context).get()
@@ -267,6 +270,7 @@ class InvoiceDelete(ModelDeleteMutation):
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
invoice = cls.get_instance(info, **data)
+ cls.check_channel_permissions(info, [invoice.order.channel_id])
response = super().perform_mutation(_root, info, **data)
app = get_app_promise(info.context).get()
events.invoice_deleted_event(
@@ -339,6 +343,7 @@ class InvoiceUpdate(ModelMutation):
cls, _root, info: ResolveInfo, /, *, id, input
):
instance = cls.get_instance(info, id=id)
+ cls.check_channel_permissions(info, [instance.order.channel_id])
cleaned_input = cls.clean_input(info, instance, input)
metadata_list = cleaned_input.pop("metadata", None)
private_metadata_list = cleaned_input.pop("private_metadata", None)
@@ -415,6 +420,7 @@ class InvoiceSendNotification(ModelMutation):
user = info.context.user
user = cast(User, user)
instance = cls.get_instance(info, id=id)
+ cls.check_channel_permissions(info, [instance.order.channel_id])
cls.clean_instance(info, instance)
app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
diff --git a/saleor/graphql/invoice/tests/test_invoice_create.py b/saleor/graphql/invoice/tests/test_invoice_create.py
index 8b110454ac..96c3ab8375 100644
--- a/saleor/graphql/invoice/tests/test_invoice_create.py
+++ b/saleor/graphql/invoice/tests/test_invoice_create.py
@@ -4,7 +4,7 @@ import graphene
import pytest
from ....core import JobStatus
-from ....graphql.tests.utils import get_graphql_content
+from ....graphql.tests.utils import assert_no_permission, get_graphql_content
from ....invoice.error_codes import InvoiceErrorCode
from ....invoice.models import Invoice, InvoiceEvent, InvoiceEvents
from ....order import OrderEvents, OrderStatus
@@ -40,8 +40,9 @@ INVOICE_CREATE_MUTATION = """
"""
-def test_create_invoice(staff_api_client, permission_manage_orders, order):
+def test_create_invoice(staff_api_client, permission_group_manage_orders, order):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
number = "01/12/2020/TEST"
url = "http://www.example.com"
order_id = graphene.Node.to_global_id("Order", order.pk)
@@ -58,9 +59,7 @@ def test_create_invoice(staff_api_client, permission_manage_orders, order):
}
# when
- response = staff_api_client.post_graphql(
- INVOICE_CREATE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_CREATE_MUTATION, variables)
# then
content = get_graphql_content(response)
@@ -92,9 +91,82 @@ def test_create_invoice(staff_api_client, permission_manage_orders, order):
).exists()
+def test_create_invoice_by_user_no_channel_access(
+ staff_api_client, permission_group_all_perms_channel_USD_only, order, channel_PLN
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ number = "01/12/2020/TEST"
+ url = "http://www.example.com"
+
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ variables = {
+ "orderId": order_id,
+ "input": {
+ "number": number,
+ "url": url,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(INVOICE_CREATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_create_invoice_by_app(app_api_client, permission_manage_orders, order):
+ # given
+ number = "01/12/2020/TEST"
+ url = "http://www.example.com"
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ variables = {
+ "orderId": order_id,
+ "input": {
+ "number": number,
+ "url": url,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ INVOICE_CREATE_MUTATION, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ invoice = Invoice.objects.get(order=order, status=JobStatus.SUCCESS)
+ assert order_id == content["data"]["invoiceCreate"]["invoice"]["order"]["id"]
+ assert invoice.url == content["data"]["invoiceCreate"]["invoice"]["url"]
+ assert invoice.number == content["data"]["invoiceCreate"]["invoice"]["number"]
+ assert (
+ invoice.status.upper() == content["data"]["invoiceCreate"]["invoice"]["status"]
+ )
+ assert InvoiceEvent.objects.filter(
+ type=InvoiceEvents.CREATED,
+ user=None,
+ app=app_api_client.app,
+ invoice=invoice,
+ order=invoice.order,
+ parameters__number=number,
+ parameters__url=url,
+ ).exists()
+ assert order.events.filter(
+ type=OrderEvents.INVOICE_GENERATED,
+ order=order,
+ user=None,
+ app=app_api_client.app,
+ parameters__invoice_number=number,
+ ).exists()
+
+
def test_create_invoice_no_billing_address(
- staff_api_client, permission_manage_orders, order
+ staff_api_client, permission_group_manage_orders, order
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order.billing_address = None
order.save()
number = "01/12/2020/TEST"
@@ -106,9 +178,7 @@ def test_create_invoice_no_billing_address(
"url": url,
},
}
- response = staff_api_client.post_graphql(
- INVOICE_CREATE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_CREATE_MUTATION, variables)
content = get_graphql_content(response)
assert not Invoice.objects.filter(order_id=order.pk, number=number).exists()
error = content["data"]["invoiceCreate"]["errors"][0]
@@ -121,8 +191,9 @@ def test_create_invoice_no_billing_address(
"status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED, OrderStatus.EXPIRED)
)
def test_create_invoice_invalid_order_status(
- status, staff_api_client, permission_manage_orders, order
+ status, staff_api_client, permission_group_manage_orders, order
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order.status = status
order.save()
number = "01/12/2020/TEST"
@@ -134,9 +205,7 @@ def test_create_invoice_invalid_order_status(
"url": url,
},
}
- response = staff_api_client.post_graphql(
- INVOICE_CREATE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_CREATE_MUTATION, variables)
content = get_graphql_content(response)
assert not Invoice.objects.filter(order_id=order.pk, number=number).exists()
error = content["data"]["invoiceCreate"]["errors"][0]
@@ -145,7 +214,8 @@ def test_create_invoice_invalid_order_status(
assert not order.events.filter(type=OrderEvents.INVOICE_GENERATED).exists()
-def test_create_invoice_invalid_id(staff_api_client, permission_manage_orders):
+def test_create_invoice_invalid_id(staff_api_client, permission_group_manage_orders):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"orderId": graphene.Node.to_global_id("Order", uuid.uuid4()),
"input": {
@@ -153,16 +223,17 @@ def test_create_invoice_invalid_id(staff_api_client, permission_manage_orders):
"url": "http://www.example.com",
},
}
- response = staff_api_client.post_graphql(
- INVOICE_CREATE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_CREATE_MUTATION, variables)
content = get_graphql_content(response)
error = content["data"]["invoiceCreate"]["errors"][0]
assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
assert error["field"] == "orderId"
-def test_create_invoice_empty_params(staff_api_client, permission_manage_orders, order):
+def test_create_invoice_empty_params(
+ staff_api_client, permission_group_manage_orders, order
+):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"orderId": graphene.Node.to_global_id("Order", order.pk),
"input": {
@@ -170,9 +241,7 @@ def test_create_invoice_empty_params(staff_api_client, permission_manage_orders,
"url": "",
},
}
- response = staff_api_client.post_graphql(
- INVOICE_CREATE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_CREATE_MUTATION, variables)
content = get_graphql_content(response)
errors = content["data"]["invoiceCreate"]["errors"]
assert errors[0] == {
diff --git a/saleor/graphql/invoice/tests/test_invoice_delete.py b/saleor/graphql/invoice/tests/test_invoice_delete.py
index c67abc2c4e..10d75f5078 100644
--- a/saleor/graphql/invoice/tests/test_invoice_delete.py
+++ b/saleor/graphql/invoice/tests/test_invoice_delete.py
@@ -2,7 +2,7 @@ from unittest.mock import patch
import graphene
-from ....graphql.tests.utils import get_graphql_content
+from ....graphql.tests.utils import assert_no_permission, get_graphql_content
from ....invoice.error_codes import InvoiceErrorCode
from ....invoice.models import Invoice, InvoiceEvent, InvoiceEvents
@@ -20,30 +20,79 @@ INVOICE_DELETE_MUTATION = """
"""
-def test_invoice_delete(staff_api_client, permission_manage_orders, order):
+def test_invoice_delete(staff_api_client, permission_group_manage_orders, order):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
invoice = Invoice.objects.create(order=order)
variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
- response = staff_api_client.post_graphql(
+
+ # when
+ response = staff_api_client.post_graphql(INVOICE_DELETE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["invoiceDelete"]["errors"]
+ assert not Invoice.objects.filter(id=invoice.pk).exists()
+ assert InvoiceEvent.objects.filter(
+ type=InvoiceEvents.DELETED,
+ user=staff_api_client.user,
+ parameters__invoice_id=invoice.id,
+ ).exists()
+
+
+def test_invoice_delete_by_user_no_channel_access(
+ staff_api_client, permission_group_all_perms_channel_USD_only, order, channel_PLN
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ invoice = Invoice.objects.create(order=order)
+ variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
+
+ # when
+ response = staff_api_client.post_graphql(INVOICE_DELETE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_invoice_delete_by_app(app_api_client, permission_manage_orders, order):
+ # given
+ invoice = Invoice.objects.create(order=order)
+ variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
+
+ # when
+ response = app_api_client.post_graphql(
INVOICE_DELETE_MUTATION, variables, permissions=[permission_manage_orders]
)
+
+ # then
content = get_graphql_content(response)
assert not content["data"]["invoiceDelete"]["errors"]
assert not Invoice.objects.filter(id=invoice.pk).exists()
assert InvoiceEvent.objects.filter(
type=InvoiceEvents.DELETED,
- user=staff_api_client.user,
+ user=None,
+ app=app_api_client.app,
parameters__invoice_id=invoice.id,
).exists()
@patch("saleor.plugins.manager.PluginsManager.invoice_delete")
def test_invoice_delete_invalid_id(
- plugin_mock, staff_api_client, permission_manage_orders
+ plugin_mock, staff_api_client, permission_group_manage_orders
):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"id": graphene.Node.to_global_id("Invoice", 1337)}
- response = staff_api_client.post_graphql(
- INVOICE_DELETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+
+ # when
+ response = staff_api_client.post_graphql(INVOICE_DELETE_MUTATION, variables)
+
+ # then
content = get_graphql_content(response)
error = content["data"]["invoiceDelete"]["errors"][0]
assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
diff --git a/saleor/graphql/invoice/tests/test_invoice_request.py b/saleor/graphql/invoice/tests/test_invoice_request.py
index af3d09f977..5487dadf69 100644
--- a/saleor/graphql/invoice/tests/test_invoice_request.py
+++ b/saleor/graphql/invoice/tests/test_invoice_request.py
@@ -4,7 +4,7 @@ import graphene
import pytest
from ....core import JobStatus
-from ....graphql.tests.utils import get_graphql_content
+from ....graphql.tests.utils import assert_no_permission, get_graphql_content
from ....invoice.error_codes import InvoiceErrorCode
from ....invoice.models import Invoice, InvoiceEvent, InvoiceEvents
from ....order import OrderEvents, OrderStatus
@@ -49,9 +49,10 @@ def test_invoice_request(
plugin_mock,
active_event_check_mock,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
dummy_invoice = Invoice.objects.create(order=order)
plugin_mock.return_value = dummy_invoice
number = "01/12/2020/TEST"
@@ -60,9 +61,7 @@ def test_invoice_request(
"orderId": graphene_order_id,
"number": number,
}
- response = staff_api_client.post_graphql(
- INVOICE_REQUEST_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_REQUEST_MUTATION, variables)
content = get_graphql_content(response)
invoice = Invoice.objects.filter(
number=number, order=order.pk, status=JobStatus.PENDING
@@ -85,12 +84,93 @@ def test_invoice_request(
).exists()
+def test_invoice_request_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ order,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ Invoice.objects.create(order=order)
+ number = "01/12/2020/TEST"
+ graphene_order_id = graphene.Node.to_global_id("Order", order.pk)
+ variables = {
+ "orderId": graphene_order_id,
+ "number": number,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(INVOICE_REQUEST_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch(
+ "saleor.graphql.invoice.mutations.is_event_active_for_any_plugin", return_value=True
+)
+@patch("saleor.plugins.manager.PluginsManager.invoice_request")
+def test_invoice_request_by_app(
+ plugin_mock,
+ active_event_check_mock,
+ app_api_client,
+ permission_manage_orders,
+ order,
+):
+ # given
+ dummy_invoice = Invoice.objects.create(order=order)
+ plugin_mock.return_value = dummy_invoice
+ number = "01/12/2020/TEST"
+ graphene_order_id = graphene.Node.to_global_id("Order", order.pk)
+ variables = {
+ "orderId": graphene_order_id,
+ "number": number,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ INVOICE_REQUEST_MUTATION, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ invoice = Invoice.objects.filter(
+ number=number, order=order.pk, status=JobStatus.PENDING
+ ).first()
+ assert invoice
+ plugin_mock.assert_called_once_with(order=order, invoice=invoice, number=number)
+ assert InvoiceEvent.objects.filter(
+ type=InvoiceEvents.REQUESTED,
+ user=None,
+ app=app_api_client.app,
+ order=invoice.order,
+ parameters__number=number,
+ ).exists()
+ assert (
+ content["data"]["invoiceRequest"]["invoice"]["status"]
+ == JobStatus.PENDING.upper()
+ )
+ assert content["data"]["invoiceRequest"]["order"]["id"] == graphene_order_id
+ assert invoice.order.events.filter(
+ type=OrderEvents.INVOICE_REQUESTED,
+ order=order,
+ user=None,
+ app=app_api_client.app,
+ ).exists()
+
+
@pytest.mark.parametrize(
"status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED, OrderStatus.EXPIRED)
)
def test_invoice_request_invalid_order_status(
- status, staff_api_client, permission_manage_orders, order
+ status, staff_api_client, permission_group_manage_orders, order
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order.status = status
order.save()
number = "01/12/2020/TEST"
@@ -98,9 +178,7 @@ def test_invoice_request_invalid_order_status(
"orderId": graphene.Node.to_global_id("Order", order.pk),
"number": number,
}
- response = staff_api_client.post_graphql(
- INVOICE_REQUEST_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_REQUEST_MUTATION, variables)
content = get_graphql_content(response)
assert not Invoice.objects.filter(number=number, order=order.pk).exists()
error = content["data"]["invoiceRequest"]["errors"][0]
@@ -110,8 +188,9 @@ def test_invoice_request_invalid_order_status(
def test_invoice_request_no_billing_address(
- staff_api_client, permission_manage_orders, order
+ staff_api_client, permission_group_manage_orders, order
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order.billing_address = None
order.save()
number = "01/12/2020/TEST"
@@ -119,9 +198,7 @@ def test_invoice_request_no_billing_address(
"orderId": graphene.Node.to_global_id("Order", order.pk),
"number": number,
}
- response = staff_api_client.post_graphql(
- INVOICE_REQUEST_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_REQUEST_MUTATION, variables)
content = get_graphql_content(response)
assert not Invoice.objects.filter(number=number, order=order.pk).exists()
error = content["data"]["invoiceRequest"]["errors"][0]
@@ -134,25 +211,23 @@ def test_invoice_request_no_billing_address(
"saleor.graphql.invoice.mutations.is_event_active_for_any_plugin", return_value=True
)
def test_invoice_request_no_number(
- active_event_check_mock, staff_api_client, permission_manage_orders, order
+ active_event_check_mock, staff_api_client, permission_group_manage_orders, order
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"orderId": graphene.Node.to_global_id("Order", order.pk)}
- staff_api_client.post_graphql(
- INVOICE_REQUEST_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ staff_api_client.post_graphql(INVOICE_REQUEST_MUTATION, variables)
invoice = Invoice.objects.get(order=order.pk)
assert invoice.number is None
assert OrderEvent.objects.filter(type=OrderEvents.INVOICE_REQUESTED).exists()
-def test_invoice_request_invalid_id(staff_api_client, permission_manage_orders):
+def test_invoice_request_invalid_id(staff_api_client, permission_group_manage_orders):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"orderId": "T3JkZXI6ZmZmMTVjYjItZTc1OC00MGJhLThkYTktNjE3ZTIwNDhlMGQ2",
"number": "01/12/2020/TEST",
}
- response = staff_api_client.post_graphql(
- INVOICE_REQUEST_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_REQUEST_MUTATION, variables)
content = get_graphql_content(response)
error = content["data"]["invoiceRequest"]["errors"][0]
assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
@@ -164,16 +239,15 @@ def test_invoice_request_invalid_id(staff_api_client, permission_manage_orders):
return_value=False,
)
def test_invoice_request_no_invoice_plugin(
- active_event_check_mock, order, permission_manage_orders, staff_api_client
+ active_event_check_mock, order, permission_group_manage_orders, staff_api_client
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
number = "01/12/2020/TEST"
variables = {
"orderId": graphene.Node.to_global_id("Order", order.pk),
"number": number,
}
- response = staff_api_client.post_graphql(
- INVOICE_REQUEST_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_REQUEST_MUTATION, variables)
content = get_graphql_content(response)
assert not Invoice.objects.filter(number=number, order=order.pk).exists()
error = content["data"]["invoiceRequest"]["errors"][0]
diff --git a/saleor/graphql/invoice/tests/test_invoice_request_delete.py b/saleor/graphql/invoice/tests/test_invoice_request_delete.py
index f8122507ff..1ea008b3e6 100644
--- a/saleor/graphql/invoice/tests/test_invoice_request_delete.py
+++ b/saleor/graphql/invoice/tests/test_invoice_request_delete.py
@@ -31,12 +31,17 @@ def setup_dummy_gateways(settings):
@patch("saleor.plugins.manager.PluginsManager.invoice_delete")
def test_invoice_request_delete(
- plugin_mock, staff_api_client, permission_manage_orders, order
+ plugin_mock, staff_api_client, permission_group_manage_orders, order
):
+ # given
invoice = Invoice.objects.create(order=order)
variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
staff_api_client.post_graphql(INVOICE_REQUEST_DELETE_MUTATION, variables)
+
+ # then
invoice.refresh_from_db()
plugin_mock.assert_called_once_with(invoice)
assert InvoiceEvent.objects.filter(
@@ -47,13 +52,63 @@ def test_invoice_request_delete(
).exists()
+def test_invoice_request_delete_by_user_no_channel_access(
+ staff_api_client, permission_group_all_perms_channel_USD_only, order, channel_PLN
+):
+ # given
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ invoice = Invoice.objects.create(order=order)
+ variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(INVOICE_REQUEST_DELETE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.plugins.manager.PluginsManager.invoice_delete")
+def test_invoice_request_delete_by_app(
+ plugin_mock, app_api_client, permission_manage_orders, order
+):
+ # given
+ invoice = Invoice.objects.create(order=order)
+ variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
+
+ # when
+ app_api_client.post_graphql(
+ INVOICE_REQUEST_DELETE_MUTATION,
+ variables,
+ permissions=(permission_manage_orders,),
+ )
+
+ # then
+ invoice.refresh_from_db()
+ plugin_mock.assert_called_once_with(invoice)
+ assert InvoiceEvent.objects.filter(
+ type=InvoiceEvents.REQUESTED_DELETION,
+ user=None,
+ app=app_api_client.app,
+ invoice=invoice,
+ order=invoice.order,
+ ).exists()
+
+
@patch("saleor.plugins.manager.PluginsManager.invoice_delete")
def test_invoice_request_delete_invalid_id(
- plugin_mock, staff_api_client, permission_manage_orders
+ plugin_mock, staff_api_client, permission_group_manage_orders
):
+ # given
variables = {"id": graphene.Node.to_global_id("Invoice", 1337)}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
response = staff_api_client.post_graphql(INVOICE_REQUEST_DELETE_MUTATION, variables)
+
+ # then
content = get_graphql_content(response)
error = content["data"]["invoiceRequestDelete"]["errors"][0]
assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
@@ -63,10 +118,15 @@ def test_invoice_request_delete_invalid_id(
@patch("saleor.plugins.manager.PluginsManager.invoice_delete")
def test_invoice_request_delete_no_permission(
- plugin_mock, staff_api_client, permission_manage_orders, order
+ plugin_mock, staff_api_client, permission_group_manage_orders, order
):
+ # given
invoice = Invoice.objects.create(order=order)
variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
+
+ # when
response = staff_api_client.post_graphql(INVOICE_REQUEST_DELETE_MUTATION, variables)
+
+ # then
assert_no_permission(response)
plugin_mock.assert_not_called()
diff --git a/saleor/graphql/invoice/tests/test_invoice_update.py b/saleor/graphql/invoice/tests/test_invoice_update.py
index eca967410d..c086c095d9 100644
--- a/saleor/graphql/invoice/tests/test_invoice_update.py
+++ b/saleor/graphql/invoice/tests/test_invoice_update.py
@@ -1,7 +1,7 @@
import graphene
from ....core import JobStatus
-from ....graphql.tests.utils import get_graphql_content
+from ....graphql.tests.utils import assert_no_permission, get_graphql_content
from ....invoice.error_codes import InvoiceErrorCode
from ....invoice.models import Invoice
@@ -33,7 +33,8 @@ INVOICE_UPDATE_MUTATION = """
"""
-def test_invoice_update(staff_api_client, permission_manage_orders, order):
+def test_invoice_update(staff_api_client, permission_group_manage_orders, order):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
test_key = "test_key"
metadata = {test_key: "test_val"}
invoice = Invoice.objects.create(order=order, metadata=metadata)
@@ -47,9 +48,7 @@ def test_invoice_update(staff_api_client, permission_manage_orders, order):
"url": url,
},
}
- response = staff_api_client.post_graphql(
- INVOICE_UPDATE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_UPDATE_MUTATION, variables)
content = get_graphql_content(response)
invoice.refresh_from_db()
assert invoice.status == JobStatus.SUCCESS
@@ -61,7 +60,37 @@ def test_invoice_update(staff_api_client, permission_manage_orders, order):
assert content["data"]["invoiceUpdate"]["invoice"]["id"] == graphene_invoice_id
-def test_invoice_update_metadata(staff_api_client, permission_manage_orders, order):
+def test_invoice_update_by_user_no_channel_access(
+ staff_api_client, permission_group_all_perms_channel_USD_only, order, channel_PLN
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ test_key = "test_key"
+ metadata = {test_key: "test_val"}
+ invoice = Invoice.objects.create(order=order, metadata=metadata)
+ number = "01/12/2020/TEST"
+ url = "http://www.example.com"
+ graphene_invoice_id = graphene.Node.to_global_id("Invoice", invoice.pk)
+ variables = {
+ "id": graphene_invoice_id,
+ "input": {
+ "number": number,
+ "url": url,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(INVOICE_UPDATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_invoice_update_by_app(app_api_client, permission_manage_orders, order):
# given
test_key = "test_key"
metadata = {test_key: "test_val"}
@@ -82,8 +111,8 @@ def test_invoice_update_metadata(staff_api_client, permission_manage_orders, ord
}
# when
- response = staff_api_client.post_graphql(
- INVOICE_UPDATE_MUTATION, variables, permissions=[permission_manage_orders]
+ response = app_api_client.post_graphql(
+ INVOICE_UPDATE_MUTATION, variables, permissions=(permission_manage_orders,)
)
# then
@@ -100,7 +129,10 @@ def test_invoice_update_metadata(staff_api_client, permission_manage_orders, ord
assert content["data"]["invoiceUpdate"]["invoice"]["id"] == graphene_invoice_id
-def test_invoice_update_single_value(staff_api_client, permission_manage_orders, order):
+def test_invoice_update_single_value(
+ staff_api_client, permission_group_manage_orders, order
+):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
number = "01/12/2020/TEST"
invoice = Invoice.objects.create(order=order, number=number)
url = "http://www.example.com"
@@ -110,9 +142,7 @@ def test_invoice_update_single_value(staff_api_client, permission_manage_orders,
"url": url,
},
}
- response = staff_api_client.post_graphql(
- INVOICE_UPDATE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_UPDATE_MUTATION, variables)
content = get_graphql_content(response)
invoice.refresh_from_db()
assert invoice.status == JobStatus.SUCCESS
@@ -121,17 +151,16 @@ def test_invoice_update_single_value(staff_api_client, permission_manage_orders,
def test_invoice_update_missing_number(
- staff_api_client, permission_manage_orders, order
+ staff_api_client, permission_group_manage_orders, order
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
invoice = Invoice.objects.create(order=order)
url = "http://www.example.com"
variables = {
"id": graphene.Node.to_global_id("Invoice", invoice.pk),
"input": {"url": url},
}
- response = staff_api_client.post_graphql(
- INVOICE_UPDATE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_UPDATE_MUTATION, variables)
content = get_graphql_content(response)
invoice.refresh_from_db()
error = content["data"]["invoiceUpdate"]["errors"][0]
@@ -141,11 +170,10 @@ def test_invoice_update_missing_number(
assert invoice.status == JobStatus.PENDING
-def test_invoice_update_invalid_id(staff_api_client, permission_manage_orders):
+def test_invoice_update_invalid_id(staff_api_client, permission_group_manage_orders):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"id": "SW52b2ljZToxMzM3", "input": {"number": "01/12/2020/TEST"}}
- response = staff_api_client.post_graphql(
- INVOICE_UPDATE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_UPDATE_MUTATION, variables)
content = get_graphql_content(response)
error = content["data"]["invoiceUpdate"]["errors"][0]
assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
diff --git a/saleor/graphql/invoice/tests/test_send_invoice_notification.py b/saleor/graphql/invoice/tests/test_send_invoice_notification.py
index 5681a0ac7b..3f4e1ccc6a 100644
--- a/saleor/graphql/invoice/tests/test_send_invoice_notification.py
+++ b/saleor/graphql/invoice/tests/test_send_invoice_notification.py
@@ -5,7 +5,7 @@ import graphene
from ....core import JobStatus
from ....core.notify_events import NotifyEventType
from ....core.tests.utils import get_site_context_payload
-from ....graphql.tests.utils import get_graphql_content
+from ....graphql.tests.utils import assert_no_permission, get_graphql_content
from ....invoice.models import Invoice
from ....invoice.notifications import get_invoice_payload
from ....order import OrderEvents
@@ -27,17 +27,16 @@ INVOICE_SEND_EMAIL_MUTATION = """
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_invoice_send_notification_by_user(
- mock_notify, staff_api_client, permission_manage_orders, order, site_settings
+ mock_notify, staff_api_client, permission_group_manage_orders, order, site_settings
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
number = "01/12/2020/TEST"
url = "http://www.example.com"
invoice = Invoice.objects.create(
order=order, number=number, url=url, status=JobStatus.SUCCESS
)
variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
- response = staff_api_client.post_graphql(
- INVOICE_SEND_EMAIL_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_SEND_EMAIL_MUTATION, variables)
content = get_graphql_content(response)
expected_payload = {
"requester_user_id": to_global_id_or_none(staff_api_client.user),
@@ -55,19 +54,47 @@ def test_invoice_send_notification_by_user(
assert not content["data"]["invoiceSendNotification"]["errors"]
+def test_invoice_send_notification_by_user_no_channel_access(
+ staff_api_client, permission_group_all_perms_channel_USD_only, order, channel_PLN
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ number = "01/12/2020/TEST"
+ url = "http://www.example.com"
+ invoice = Invoice.objects.create(
+ order=order, number=number, url=url, status=JobStatus.SUCCESS
+ )
+ variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
+
+ # when
+ response = staff_api_client.post_graphql(INVOICE_SEND_EMAIL_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_invoice_send_notification_by_app(
mock_notify, app_api_client, permission_manage_orders, order, site_settings
):
+ # given
number = "01/12/2020/TEST"
url = "http://www.example.com"
invoice = Invoice.objects.create(
order=order, number=number, url=url, status=JobStatus.SUCCESS
)
variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
+
+ # when
response = app_api_client.post_graphql(
- INVOICE_SEND_EMAIL_MUTATION, variables, permissions=[permission_manage_orders]
+ INVOICE_SEND_EMAIL_MUTATION, variables, permissions=(permission_manage_orders,)
)
+
+ # then
content = get_graphql_content(response)
expected_payload = {
"requester_user_id": None,
@@ -87,15 +114,14 @@ def test_invoice_send_notification_by_app(
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_invoice_send_notification_pending(
- mock_notify, staff_api_client, permission_manage_orders, order
+ mock_notify, staff_api_client, permission_group_manage_orders, order
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
invoice = Invoice.objects.create(
order=order, number=None, url=None, status=JobStatus.PENDING
)
variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
- response = staff_api_client.post_graphql(
- INVOICE_SEND_EMAIL_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_SEND_EMAIL_MUTATION, variables)
content = get_graphql_content(response)
errors = content["data"]["invoiceSendNotification"]["errors"]
assert errors == [
@@ -109,15 +135,14 @@ def test_invoice_send_notification_pending(
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_invoice_send_notification_without_url_and_number(
- mock_notify, staff_api_client, permission_manage_orders, order
+ mock_notify, staff_api_client, permission_group_manage_orders, order
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
invoice = Invoice.objects.create(
order=order, number=None, url=None, status=JobStatus.SUCCESS
)
variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
- response = staff_api_client.post_graphql(
- INVOICE_SEND_EMAIL_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_SEND_EMAIL_MUTATION, variables)
content = get_graphql_content(response)
errors = content["data"]["invoiceSendNotification"]["errors"]
assert errors == [
@@ -131,8 +156,9 @@ def test_invoice_send_notification_without_url_and_number(
@patch("saleor.plugins.manager.PluginsManager.notify")
@patch("saleor.order.models.Order.get_customer_email")
def test_invoice_send_email_without_email(
- order_mock, mock_notify, staff_api_client, permission_manage_orders, order
+ order_mock, mock_notify, staff_api_client, permission_group_manage_orders, order
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_mock.return_value = None
invoice = Invoice.objects.create(
order=order,
@@ -141,9 +167,7 @@ def test_invoice_send_email_without_email(
status=JobStatus.SUCCESS,
)
variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
- response = staff_api_client.post_graphql(
- INVOICE_SEND_EMAIL_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(INVOICE_SEND_EMAIL_MUTATION, variables)
content = get_graphql_content(response)
mock_notify.assert_not_called()
assert order_mock.called
diff --git a/saleor/graphql/order/bulk_mutations/draft_orders.py b/saleor/graphql/order/bulk_mutations/draft_orders.py
index b8f7d61394..051b73b1e6 100644
--- a/saleor/graphql/order/bulk_mutations/draft_orders.py
+++ b/saleor/graphql/order/bulk_mutations/draft_orders.py
@@ -1,16 +1,25 @@
+from typing import Iterable, Union
+from uuid import UUID
+
import graphene
from django.core.exceptions import ValidationError
+from ....channel import models as channel_models
from ....order import OrderStatus, models
from ....order.error_codes import OrderErrorCode
from ....permission.enums import OrderPermissions
from ...core import ResolveInfo
-from ...core.mutations import ModelBulkDeleteMutation
+from ...core.mutations import (
+ BaseBulkWithRestrictedChannelAccessMutation,
+ ModelBulkDeleteMutation,
+)
from ...core.types import NonNullList, OrderError
from ..types import Order, OrderLine
-class DraftOrderBulkDelete(ModelBulkDeleteMutation):
+class DraftOrderBulkDelete(
+ ModelBulkDeleteMutation, BaseBulkWithRestrictedChannelAccessMutation
+):
class Arguments:
ids = NonNullList(
graphene.ID, required=True, description="List of draft order IDs to delete."
@@ -36,8 +45,15 @@ class DraftOrderBulkDelete(ModelBulkDeleteMutation):
}
)
+ @classmethod
+ def get_channel_ids(cls, instances) -> Iterable[Union[UUID, int]]:
+ """Get the instances channel ids for channel permission accessible check."""
+ return [order.channel_id for order in instances]
+
-class DraftOrderLinesBulkDelete(ModelBulkDeleteMutation):
+class DraftOrderLinesBulkDelete(
+ ModelBulkDeleteMutation, BaseBulkWithRestrictedChannelAccessMutation
+):
class Arguments:
ids = NonNullList(
graphene.ID, required=True, description="List of order lines IDs to delete."
@@ -62,3 +78,13 @@ class DraftOrderLinesBulkDelete(ModelBulkDeleteMutation):
)
}
)
+
+ @classmethod
+ def get_channel_ids(cls, instances) -> Iterable[Union[UUID, int]]:
+ """Get the instances channel ids for channel permission accessible check."""
+ orders = models.Order.objects.filter(
+ id__in=[line.order_id for line in instances]
+ )
+ return channel_models.Channel.objects.filter(
+ id__in=orders.values("channel_id")
+ ).values_list("id", flat=True)
diff --git a/saleor/graphql/order/bulk_mutations/orders.py b/saleor/graphql/order/bulk_mutations/orders.py
index c1b1a0cd82..fd258c38d5 100644
--- a/saleor/graphql/order/bulk_mutations/orders.py
+++ b/saleor/graphql/order/bulk_mutations/orders.py
@@ -1,3 +1,6 @@
+from typing import Iterable, Union
+from uuid import UUID
+
import graphene
from ....order import models
@@ -5,14 +8,14 @@ from ....order.actions import cancel_order
from ....permission.enums import OrderPermissions
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
-from ...core.mutations import BaseBulkMutation
+from ...core.mutations import BaseBulkWithRestrictedChannelAccessMutation
from ...core.types import NonNullList, OrderError
from ...plugins.dataloaders import get_plugin_manager_promise
from ..mutations.order_cancel import clean_order_cancel
from ..types import Order
-class OrderBulkCancel(BaseBulkMutation):
+class OrderBulkCancel(BaseBulkWithRestrictedChannelAccessMutation):
class Arguments:
ids = NonNullList(
graphene.ID, required=True, description="List of orders IDs to cancel."
@@ -40,3 +43,8 @@ class OrderBulkCancel(BaseBulkMutation):
app=get_app_promise(info.context).get(),
manager=manager,
)
+
+ @classmethod
+ def get_channel_ids(cls, instances) -> Iterable[Union[UUID, int]]:
+ """Get the instances channel ids for channel permission accessible check."""
+ return [order.channel_id for order in instances]
diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.py
index 441e68a536..e804df1ec7 100644
--- a/saleor/graphql/order/mutations/draft_order_complete.py
+++ b/saleor/graphql/order/mutations/draft_order_complete.py
@@ -84,6 +84,7 @@ class DraftOrderComplete(BaseMutation):
only_type=Order,
qs=models.Order.objects.prefetch_related("lines__variant"),
)
+ cls.check_channel_permissions(info, [order.channel_id])
order, _ = fetch_order_prices_if_expired(order, manager)
cls.validate_order(order)
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index e9a6cf2371..b937cc7d04 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -28,9 +28,10 @@ from ...channel.types import Channel
from ...core import ResolveInfo
from ...core.descriptions import ADDED_IN_36, ADDED_IN_310
from ...core.doc_category import DOC_CATEGORY_ORDERS
-from ...core.mutations import ModelMutation
+from ...core.mutations import ModelWithRestrictedChannelAccessMutation
from ...core.scalars import PositiveDecimal
from ...core.types import BaseInputObjectType, NonNullList, OrderError
+from ...core.utils import from_global_id_or_error
from ...plugins.dataloaders import get_plugin_manager_promise
from ...product.types import ProductVariant
from ...shipping.utils import get_shipping_model_by_object_id
@@ -114,7 +115,7 @@ class DraftOrderCreateInput(DraftOrderInput):
doc_category = DOC_CATEGORY_ORDERS
-class DraftOrderCreate(ModelMutation, I18nMixin):
+class DraftOrderCreate(ModelWithRestrictedChannelAccessMutation, I18nMixin):
class Arguments:
input = DraftOrderCreateInput(
required=True, description="Fields required to create an order."
@@ -128,6 +129,26 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
error_type_class = OrderError
error_type_field = "order_errors"
+ @classmethod
+ def get_instance_channel_id(cls, instance, **data):
+ if channel_id := instance.channel_id:
+ return channel_id
+
+ channel_id = data["input"].get("channel_id")
+ if not channel_id:
+ raise ValidationError(
+ {
+ "channel": ValidationError(
+ "Channel id is required.", code=OrderErrorCode.REQUIRED.value
+ )
+ }
+ )
+ _, channel_id = from_global_id_or_error(
+ channel_id, "Channel", raise_error=False
+ )
+
+ return channel_id
+
@classmethod
def clean_input(cls, info: ResolveInfo, instance, data, **kwargs):
shipping_address = data.pop("shipping_address", None)
diff --git a/saleor/graphql/order/mutations/draft_order_delete.py b/saleor/graphql/order/mutations/draft_order_delete.py
index 8f043bdbaa..969a76963c 100644
--- a/saleor/graphql/order/mutations/draft_order_delete.py
+++ b/saleor/graphql/order/mutations/draft_order_delete.py
@@ -7,13 +7,18 @@ from ....order.error_codes import OrderErrorCode
from ....permission.enums import OrderPermissions
from ...core import ResolveInfo
from ...core.descriptions import ADDED_IN_310
-from ...core.mutations import ModelDeleteMutation, ModelWithExtRefMutation
+from ...core.mutations import (
+ ModelDeleteWithRestrictedChannelAccessMutation,
+ ModelWithExtRefMutation,
+)
from ...core.types import OrderError
from ...plugins.dataloaders import get_plugin_manager_promise
from ..types import Order
-class DraftOrderDelete(ModelDeleteMutation, ModelWithExtRefMutation):
+class DraftOrderDelete(
+ ModelDeleteWithRestrictedChannelAccessMutation, ModelWithExtRefMutation
+):
class Arguments:
id = graphene.ID(required=False, description="ID of a product to delete.")
external_reference = graphene.String(
@@ -49,3 +54,7 @@ class DraftOrderDelete(ModelDeleteMutation, ModelWithExtRefMutation):
response = super().perform_mutation(_root, info, **data)
cls.call_event(manager.draft_order_deleted, order)
return response
+
+ @classmethod
+ def get_instance_channel_id(cls, instance):
+ return instance.channel_id
diff --git a/saleor/graphql/order/mutations/fulfillment_approve.py b/saleor/graphql/order/mutations/fulfillment_approve.py
index b6c288f4c0..417205ee43 100644
--- a/saleor/graphql/order/mutations/fulfillment_approve.py
+++ b/saleor/graphql/order/mutations/fulfillment_approve.py
@@ -76,9 +76,10 @@ class FulfillmentApprove(BaseMutation):
user = info.context.user
user = cast(User, user)
fulfillment = cls.get_node_or_error(info, id, only_type=Fulfillment)
+ order = fulfillment.order
+ cls.check_channel_permissions(info, [order.channel_id])
cls.clean_input(info, fulfillment)
- order = fulfillment.order
manager = get_plugin_manager_promise(info.context).get()
app = get_app_promise(info.context).get()
site = get_site_promise(info.context).get()
diff --git a/saleor/graphql/order/mutations/fulfillment_cancel.py b/saleor/graphql/order/mutations/fulfillment_cancel.py
index 84a8e24273..61a3825975 100644
--- a/saleor/graphql/order/mutations/fulfillment_cancel.py
+++ b/saleor/graphql/order/mutations/fulfillment_cancel.py
@@ -93,6 +93,7 @@ class FulfillmentCancel(BaseMutation):
user = cast(User, user)
fulfillment = cls.get_node_or_error(info, id, only_type=Fulfillment)
order = fulfillment.order
+ cls.check_channel_permissions(info, [order.channel_id])
cls.validate_order(order)
diff --git a/saleor/graphql/order/mutations/fulfillment_refund_products.py b/saleor/graphql/order/mutations/fulfillment_refund_products.py
index 327e88b6a7..f7d4f78395 100644
--- a/saleor/graphql/order/mutations/fulfillment_refund_products.py
+++ b/saleor/graphql/order/mutations/fulfillment_refund_products.py
@@ -140,6 +140,7 @@ class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
cleaned_input = cls.clean_input(info, data.get("order"), data.get("input"))
order = cleaned_input["order"]
+ cls.check_channel_permissions(info, [order.channel_id])
manager = get_plugin_manager_promise(info.context).get()
try:
app = get_app_promise(info.context).get()
diff --git a/saleor/graphql/order/mutations/fulfillment_return_products.py b/saleor/graphql/order/mutations/fulfillment_return_products.py
index 74aa7bc572..e7bf364acf 100644
--- a/saleor/graphql/order/mutations/fulfillment_return_products.py
+++ b/saleor/graphql/order/mutations/fulfillment_return_products.py
@@ -163,6 +163,7 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
cleaned_input = cls.clean_input(info, data.get("order"), data.get("input"))
order = cleaned_input["order"]
+ cls.check_channel_permissions(info, [order.channel_id])
manager = get_plugin_manager_promise(info.context).get()
try:
app = get_app_promise(info.context).get()
diff --git a/saleor/graphql/order/mutations/fulfillment_update_tracking.py b/saleor/graphql/order/mutations/fulfillment_update_tracking.py
index 54082e11bc..795e712e4e 100644
--- a/saleor/graphql/order/mutations/fulfillment_update_tracking.py
+++ b/saleor/graphql/order/mutations/fulfillment_update_tracking.py
@@ -50,14 +50,20 @@ class FulfillmentUpdateTracking(BaseMutation):
user = info.context.user
user = cast(User, user)
fulfillment = cls.get_node_or_error(info, id, only_type=Fulfillment)
+
+ order = fulfillment.order
+ cls.check_channel_permissions(info, [order.channel_id])
+
tracking_number = input.get("tracking_number") or ""
fulfillment.tracking_number = tracking_number
fulfillment.save()
- order = fulfillment.order
+
app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
fulfillment_tracking_updated(fulfillment, user, app, tracking_number, manager)
+
notify_customer = input.get("notify_customer")
if notify_customer:
send_fulfillment_update(order, fulfillment, manager)
+
return FulfillmentUpdateTracking(fulfillment=fulfillment, order=order)
diff --git a/saleor/graphql/order/mutations/order_add_note.py b/saleor/graphql/order/mutations/order_add_note.py
index 55f2e8275a..0dc4bd1b40 100644
--- a/saleor/graphql/order/mutations/order_add_note.py
+++ b/saleor/graphql/order/mutations/order_add_note.py
@@ -66,6 +66,7 @@ class OrderAddNote(BaseMutation):
cls, _root, info: ResolveInfo, /, *, id: str, input
):
order = cls.get_node_or_error(info, id, only_type=Order)
+ cls.check_channel_permissions(info, [order.channel_id])
cleaned_input = cls.clean_input(info, order, input)
app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
diff --git a/saleor/graphql/order/mutations/order_cancel.py b/saleor/graphql/order/mutations/order_cancel.py
index 53989ca606..733b60fd3d 100644
--- a/saleor/graphql/order/mutations/order_cancel.py
+++ b/saleor/graphql/order/mutations/order_cancel.py
@@ -49,6 +49,7 @@ class OrderCancel(BaseMutation):
cls, _root, info: ResolveInfo, /, *, id: str
):
order = cls.get_node_or_error(info, id, only_type=Order)
+ cls.check_channel_permissions(info, [order.channel_id])
order = clean_order_cancel(order)
user = info.context.user
app = get_app_promise(info.context).get()
diff --git a/saleor/graphql/order/mutations/order_capture.py b/saleor/graphql/order/mutations/order_capture.py
index 2cbe50b5c1..3a6f52f783 100644
--- a/saleor/graphql/order/mutations/order_capture.py
+++ b/saleor/graphql/order/mutations/order_capture.py
@@ -68,6 +68,7 @@ class OrderCapture(BaseMutation):
)
order = cls.get_node_or_error(info, id, only_type=Order)
+ cls.check_channel_permissions(info, [order.channel_id])
app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
diff --git a/saleor/graphql/order/mutations/order_confirm.py b/saleor/graphql/order/mutations/order_confirm.py
index e7cc6ba75c..269cbd4718 100644
--- a/saleor/graphql/order/mutations/order_confirm.py
+++ b/saleor/graphql/order/mutations/order_confirm.py
@@ -65,6 +65,7 @@ class OrderConfirm(ModelMutation):
user = info.context.user
user = cast(User, user)
order = cls.get_instance(info, **data)
+ cls.check_channel_permissions(info, [order.channel_id])
order.status = OrderStatus.UNFULFILLED
update_order_display_gross_prices(order)
order.save(update_fields=["status", "updated_at", "display_gross_prices"])
diff --git a/saleor/graphql/order/mutations/order_discount_add.py b/saleor/graphql/order/mutations/order_discount_add.py
index 3d7ff13f0c..657a5ebbc0 100644
--- a/saleor/graphql/order/mutations/order_discount_add.py
+++ b/saleor/graphql/order/mutations/order_discount_add.py
@@ -60,6 +60,7 @@ class OrderDiscountAdd(OrderDiscountCommon):
):
manager = get_plugin_manager_promise(info.context).get()
order = cls.get_node_or_error(info, order_id, only_type=Order)
+ cls.check_channel_permissions(info, [order.channel_id])
cls.validate(info, order, input)
reason = input.get("reason")
diff --git a/saleor/graphql/order/mutations/order_discount_delete.py b/saleor/graphql/order/mutations/order_discount_delete.py
index 9851dea273..e0c0ab5a75 100644
--- a/saleor/graphql/order/mutations/order_discount_delete.py
+++ b/saleor/graphql/order/mutations/order_discount_delete.py
@@ -49,6 +49,7 @@ class OrderDiscountDelete(OrderDiscountCommon):
)
}
)
+ cls.check_channel_permissions(info, [order.channel_id])
app = get_app_promise(info.context).get()
order = cls.validate_order(info, order)
diff --git a/saleor/graphql/order/mutations/order_discount_update.py b/saleor/graphql/order/mutations/order_discount_update.py
index f85a2a5a90..ff6a6912de 100644
--- a/saleor/graphql/order/mutations/order_discount_update.py
+++ b/saleor/graphql/order/mutations/order_discount_update.py
@@ -64,6 +64,7 @@ class OrderDiscountUpdate(OrderDiscountCommon):
)
}
)
+ cls.check_channel_permissions(info, [order.channel_id])
cls.validate(info, order, order_discount, input)
reason = input.get("reason", order_discount.reason)
diff --git a/saleor/graphql/order/mutations/order_fulfill.py b/saleor/graphql/order/mutations/order_fulfill.py
index 2a02ca1107..18833de6d1 100644
--- a/saleor/graphql/order/mutations/order_fulfill.py
+++ b/saleor/graphql/order/mutations/order_fulfill.py
@@ -268,6 +268,7 @@ class OrderFulfill(BaseMutation):
raise ValidationError(
"Order does not exist.", code=OrderErrorCode.NOT_FOUND.value
)
+ cls.check_channel_permissions(info, [instance.channel_id])
site = get_site_promise(info.context).get()
cleaned_input = cls.clean_input(info, instance, input, site=site)
diff --git a/saleor/graphql/order/mutations/order_line_delete.py b/saleor/graphql/order/mutations/order_line_delete.py
index ce4690fc03..0a978ec616 100644
--- a/saleor/graphql/order/mutations/order_line_delete.py
+++ b/saleor/graphql/order/mutations/order_line_delete.py
@@ -48,6 +48,7 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):
only_type=OrderLine,
)
order = line.order
+ cls.check_channel_permissions(info, [order.channel_id])
cls.validate_order(line.order)
db_id = line.id
diff --git a/saleor/graphql/order/mutations/order_line_discount_remove.py b/saleor/graphql/order/mutations/order_line_discount_remove.py
index b1979698fd..3e376ab3c5 100644
--- a/saleor/graphql/order/mutations/order_line_discount_remove.py
+++ b/saleor/graphql/order/mutations/order_line_discount_remove.py
@@ -42,6 +42,7 @@ class OrderLineDiscountRemove(OrderDiscountCommon):
):
order_line = cls.get_node_or_error(info, order_line_id, only_type=OrderLine)
order = order_line.order
+ cls.check_channel_permissions(info, [order.channel_id])
cls.validate(info, order)
with traced_atomic_transaction():
remove_discount_from_order_line(order_line, order)
diff --git a/saleor/graphql/order/mutations/order_line_discount_update.py b/saleor/graphql/order/mutations/order_line_discount_update.py
index 5732f05f76..26cd3dbf39 100644
--- a/saleor/graphql/order/mutations/order_line_discount_update.py
+++ b/saleor/graphql/order/mutations/order_line_discount_update.py
@@ -54,6 +54,7 @@ class OrderLineDiscountUpdate(OrderDiscountCommon):
):
order_line = cls.get_node_or_error(info, order_line_id, only_type=OrderLine)
order = order_line.order
+ cls.check_channel_permissions(info, [order.channel_id])
cls.validate(info, order, order_line, input)
reason = input.get("reason")
value_type = input.get("value_type")
diff --git a/saleor/graphql/order/mutations/order_line_update.py b/saleor/graphql/order/mutations/order_line_update.py
index 47ebf50297..54136c9fc7 100644
--- a/saleor/graphql/order/mutations/order_line_update.py
+++ b/saleor/graphql/order/mutations/order_line_update.py
@@ -14,7 +14,7 @@ from ....order.utils import (
from ....permission.enums import OrderPermissions
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
-from ...core.mutations import ModelMutation
+from ...core.mutations import ModelWithRestrictedChannelAccessMutation
from ...core.types import OrderError
from ...plugins.dataloaders import get_plugin_manager_promise
from ..types import Order, OrderLine
@@ -22,7 +22,9 @@ from .draft_order_create import OrderLineInput
from .utils import EditableOrderValidationMixin, get_webhook_handler_by_order_status
-class OrderLineUpdate(EditableOrderValidationMixin, ModelMutation):
+class OrderLineUpdate(
+ EditableOrderValidationMixin, ModelWithRestrictedChannelAccessMutation
+):
order = graphene.Field(Order, description="Related order.")
class Arguments:
@@ -100,3 +102,8 @@ class OrderLineUpdate(EditableOrderValidationMixin, ModelMutation):
response = super().success_response(instance)
response.order = instance.order
return response
+
+ @classmethod
+ def get_instance_channel_id(cls, instance, **data):
+ """Retrieve the instance channel id for channel permission accessible check."""
+ return instance.order.channel_id
diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.py
index 069f4804f3..9c2696c101 100644
--- a/saleor/graphql/order/mutations/order_lines_create.py
+++ b/saleor/graphql/order/mutations/order_lines_create.py
@@ -150,6 +150,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
cls, _root, info: ResolveInfo, /, *, id: str, input
):
order = cls.get_node_or_error(info, id, only_type=Order)
+ cls.check_channel_permissions(info, [order.channel_id])
cls.validate_order(order)
existing_lines_info = fetch_order_lines(order)
diff --git a/saleor/graphql/order/mutations/order_mark_as_paid.py b/saleor/graphql/order/mutations/order_mark_as_paid.py
index 2f0de56e83..b29fc8fb8d 100644
--- a/saleor/graphql/order/mutations/order_mark_as_paid.py
+++ b/saleor/graphql/order/mutations/order_mark_as_paid.py
@@ -111,6 +111,7 @@ class OrderMarkAsPaid(BaseMutation):
cls, _root, info: ResolveInfo, /, *, id, transaction_reference=None
):
order = cls.get_node_or_error(info, id, only_type=Order)
+ cls.check_channel_permissions(info, [order.channel_id])
manager = get_plugin_manager_promise(info.context).get()
order, _ = fetch_order_prices_if_expired(order, manager)
cls.clean_billing_address(order)
diff --git a/saleor/graphql/order/mutations/order_refund.py b/saleor/graphql/order/mutations/order_refund.py
index bdfcc49082..3747bfd842 100644
--- a/saleor/graphql/order/mutations/order_refund.py
+++ b/saleor/graphql/order/mutations/order_refund.py
@@ -81,6 +81,7 @@ class OrderRefund(BaseMutation):
)
order = cls.get_node_or_error(info, id, only_type=Order)
+ cls.check_channel_permissions(info, [order.channel_id])
order = clean_order_refund(order)
app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
diff --git a/saleor/graphql/order/mutations/order_update_shipping.py b/saleor/graphql/order/mutations/order_update_shipping.py
index 5a85520bbe..bb42f34401 100644
--- a/saleor/graphql/order/mutations/order_update_shipping.py
+++ b/saleor/graphql/order/mutations/order_update_shipping.py
@@ -66,6 +66,7 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
"lines", "channel__shipping_method_listings"
),
)
+ cls.check_channel_permissions(info, [order.channel_id])
cls.validate_order(order)
if "shipping_method" not in input:
diff --git a/saleor/graphql/order/mutations/order_void.py b/saleor/graphql/order/mutations/order_void.py
index 412be9c504..ed134eb044 100644
--- a/saleor/graphql/order/mutations/order_void.py
+++ b/saleor/graphql/order/mutations/order_void.py
@@ -53,6 +53,7 @@ class OrderVoid(BaseMutation):
cls, _root, info: ResolveInfo, /, *, id: str
):
order = cls.get_node_or_error(info, id, only_type=Order)
+ cls.check_channel_permissions(info, [order.channel_id])
app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
payment = order.get_last_payment()
diff --git a/saleor/graphql/order/resolvers.py b/saleor/graphql/order/resolvers.py
index 5e36e42359..ae861d7c30 100644
--- a/saleor/graphql/order/resolvers.py
+++ b/saleor/graphql/order/resolvers.py
@@ -3,10 +3,12 @@ from uuid import UUID
from django.db.models import Q
from ...channel.models import Channel
+from ...core.exceptions import PermissionDenied
from ...order import OrderStatus, models
from ...order.events import OrderEvents
-from ...order.models import OrderEvent
from ...order.utils import sum_order_totals
+from ..account.utils import get_user_accessible_channels
+from ..app.dataloaders import get_app_promise
from ..channel.utils import get_default_channel_slug_or_graphql_error
from ..core.context import get_database_connection_name
from ..core.tracing import traced_resolver
@@ -22,14 +24,34 @@ def resolve_orders(
qs = models.Order.objects.using(database_connection_name).non_draft()
if channel_slug:
qs = qs.filter(channel__slug=str(channel_slug))
+
if requesting_user and not requestor_has_access_to_all:
- qs = qs.filter(user_id=requesting_user.id)
- return qs
+ return qs.filter(user_id=requesting_user.id)
+
+ if get_app_promise(info.context).get():
+ return qs
+
+ accessible_channels = get_user_accessible_channels(info, info.context.user)
+ if channel_slug and channel_slug not in [
+ channel.slug for channel in accessible_channels
+ ]:
+ raise PermissionDenied(
+ message=f"You do not have access to the {channel_slug} channel."
+ )
+ channel_ids = [channel.id for channel in accessible_channels]
+ return qs.filter(channel_id__in=channel_ids)
def resolve_draft_orders(info):
database_connection_name = get_database_connection_name(info.context)
- return models.Order.objects.using(database_connection_name).drafts()
+ qs = models.Order.objects.using(database_connection_name).drafts()
+
+ if get_app_promise(info.context).get():
+ return qs
+
+ accessible_channels = get_user_accessible_channels(info, info.context.user)
+ channel_ids = [channel.id for channel in accessible_channels]
+ return qs.filter(channel_id__in=channel_ids)
@traced_resolver
@@ -40,6 +62,15 @@ def resolve_orders_total(info, period, channel_slug):
if not channel:
return None
database_connection_name = get_database_connection_name(info.context)
+
+ app = get_app_promise(info.context).get()
+ if not app:
+ accessible_channels = get_user_accessible_channels(info, info.context.user)
+ if channel_slug not in [channel.slug for channel in accessible_channels]:
+ raise PermissionDenied(
+ message=f"You do not have access to the {channel_slug} channel."
+ )
+
qs = (
models.Order.objects.using(database_connection_name)
.non_draft()
@@ -70,7 +101,15 @@ def resolve_homepage_events(info):
OrderEvents.ORDER_FULLY_PAID,
]
database_connection_name = get_database_connection_name(info.context)
- return OrderEvent.objects.using(database_connection_name).filter(type__in=types)
+ lookup = Q(type__in=types)
+ app = get_app_promise(info.context).get()
+ if not app:
+ # get order events from orders that user has access to
+ accessible_channels = get_user_accessible_channels(info, info.context.user)
+ channel_ids = [channel.id for channel in accessible_channels]
+ accessible_orders = models.Order.objects.filter(channel_id__in=channel_ids)
+ lookup &= Q(order_id__in=accessible_orders.values("id"))
+ return models.OrderEvent.objects.using(database_connection_name).filter(lookup)
def resolve_order_by_token(info, token):
diff --git a/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py b/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py
index 998ac4edd8..cca3733b56 100644
--- a/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py
+++ b/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py
@@ -14,7 +14,7 @@ from ....tests.utils import get_graphql_content
def test_fulfillment_refund_products_order_lines(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
payment_dummy,
count_queries,
@@ -48,6 +48,7 @@ def test_fulfillment_refund_products_order_lines(
}
}
"""
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
payment_dummy.total = order_with_lines.total_gross_amount
payment_dummy.captured_amount = payment_dummy.total
payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
@@ -60,7 +61,6 @@ def test_fulfillment_refund_products_order_lines(
"order": order_id,
"input": {"orderLines": [{"orderLineId": line_id, "quantity": 2}]},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(query, variables)
@@ -76,7 +76,7 @@ def test_fulfillment_return_products_order_lines(
mocked_refund,
back_in_stock_webhook_mock,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
payment_dummy,
count_queries,
@@ -129,6 +129,7 @@ def test_fulfillment_return_products_order_lines(
}
}
"""
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
payment_dummy.total = order_with_lines.total_gross_amount
payment_dummy.captured_amount = payment_dummy.total
payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
@@ -163,7 +164,6 @@ def test_fulfillment_return_products_order_lines(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
diff --git a/saleor/graphql/order/tests/benchmark/test_order_fulfill.py b/saleor/graphql/order/tests/benchmark/test_order_fulfill.py
index b122228eaa..680247b13b 100644
--- a/saleor/graphql/order/tests/benchmark/test_order_fulfill.py
+++ b/saleor/graphql/order/tests/benchmark/test_order_fulfill.py
@@ -31,11 +31,12 @@ def test_order_fulfill(
mock_create_fulfillments,
staff_api_client,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
count_queries,
):
order = order_with_lines
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = ORDER_FULFILL_QUERY
order_id = graphene.Node.to_global_id("Order", order.id)
order_line, order_line2 = order.lines.all()
@@ -58,9 +59,7 @@ def test_order_fulfill(
],
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert not data["errors"]
@@ -76,11 +75,12 @@ def test_order_fulfill_with_gift_cards(
order,
gift_card_non_shippable_order_line,
gift_card_shippable_order_line,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
count_queries,
):
query = ORDER_FULFILL_QUERY
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order.id)
order_line, order_line2 = (
gift_card_non_shippable_order_line,
@@ -109,9 +109,7 @@ def test_order_fulfill_with_gift_cards(
],
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
diff --git a/saleor/graphql/order/tests/deprecated/test_discount_order.py b/saleor/graphql/order/tests/deprecated/test_discount_order.py
index df634c6daa..e594ea3c79 100644
--- a/saleor/graphql/order/tests/deprecated/test_discount_order.py
+++ b/saleor/graphql/order/tests/deprecated/test_discount_order.py
@@ -31,7 +31,7 @@ def test_delete_order_discount_from_order_with_old_id(
status,
draft_order_with_fixed_discount_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
# given
order = draft_order_with_fixed_discount_order
@@ -53,7 +53,7 @@ def test_delete_order_discount_from_order_with_old_id(
"OrderDiscount", order_discount.old_id
),
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDER_DISCOUNT_DELETE, variables)
@@ -107,7 +107,7 @@ def test_update_percentage_order_discount_by_old_id(
status,
draft_order_with_fixed_discount_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
# given
order = draft_order_with_fixed_discount_order
@@ -130,7 +130,7 @@ def test_update_percentage_order_discount_by_old_id(
"reason": reason,
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDER_DISCOUNT_UPDATE, variables)
diff --git a/saleor/graphql/order/tests/deprecated/test_order.py b/saleor/graphql/order/tests/deprecated/test_order.py
index 27f3c00a35..735fe851a7 100644
--- a/saleor/graphql/order/tests/deprecated/test_order.py
+++ b/saleor/graphql/order/tests/deprecated/test_order.py
@@ -47,16 +47,17 @@ query Orders($period: ReportingPeriod, $channel: String) {
"""
-def test_orders_total(staff_api_client, permission_manage_orders, order_with_lines):
+def test_orders_total(
+ staff_api_client, permission_group_manage_orders, order_with_lines
+):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
variables = {"period": ReportingPeriod.TODAY.name}
# when
with warnings.catch_warnings(record=True) as warns:
- response = staff_api_client.post_graphql(
- QUERY_ORDER_TOTAL, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(QUERY_ORDER_TOTAL, variables)
content = get_graphql_content(response)
# then
@@ -99,10 +100,11 @@ def test_order_line_remove_by_old_line_id(
draft_order_updated_webhook_mock,
status,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
query = ORDER_LINE_DELETE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.status = status
order.save(update_fields=["status"])
@@ -113,9 +115,7 @@ def test_order_line_remove_by_old_line_id(
line_id = graphene.Node.to_global_id("OrderLine", line.old_id)
variables = {"id": line_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderLineDelete"]
assert OrderEvent.objects.count() == 1
@@ -158,7 +158,7 @@ def test_order_line_update_by_old_line_id(
draft_order_updated_webhook_mock,
status,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
staff_user,
):
@@ -175,7 +175,7 @@ def test_order_line_update_by_old_line_id(
removed_quantity = 2
line_id = graphene.Node.to_global_id("OrderLine", line.old_id)
variables = {"lineId": line_id, "quantity": new_quantity}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Ensure the line has the expected quantity
assert line.quantity == 3
@@ -231,10 +231,11 @@ def test_order_fulfill_old_line_id(
staff_api_client,
staff_user,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
site_settings,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
site_settings.fulfillment_auto_approve = fulfillment_auto_approve
site_settings.save(update_fields=["fulfillment_auto_approve"])
order = order_with_lines
@@ -264,9 +265,7 @@ def test_order_fulfill_old_line_id(
],
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert not data["errors"]
@@ -326,7 +325,7 @@ mutation OrderFulfillmentRefundProducts(
def test_fulfillment_refund_products_order_lines_by_old_id(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
payment_dummy,
):
@@ -345,7 +344,7 @@ def test_fulfillment_refund_products_order_lines_by_old_id(
"order": order_id,
"input": {"orderLines": [{"orderLineId": line_id, "quantity": 2}]},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
@@ -435,7 +434,7 @@ mutation OrderFulfillmentReturnProducts(
def test_fulfillment_return_products_order_lines_by_old_line_id(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
payment_dummy,
):
@@ -477,7 +476,7 @@ def test_fulfillment_return_products_order_lines_by_old_line_id(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
order_with_lines.refresh_from_db()
@@ -584,7 +583,7 @@ def test_update_order_line_discount_old_id(
status,
draft_order_with_fixed_discount_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
order = draft_order_with_fixed_discount_order
order.status = status
@@ -613,7 +612,7 @@ def test_update_order_line_discount_old_id(
"reason": reason,
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_UPDATE, variables)
content = get_graphql_content(response)
data = content["data"]["orderLineDiscountUpdate"]
@@ -671,7 +670,7 @@ def test_delete_discount_from_order_line_by_old_id(
mocked_calculate_order_line_unit,
draft_order_with_fixed_discount_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
order = draft_order_with_fixed_discount_order
order.status = OrderStatus.DRAFT
@@ -703,7 +702,7 @@ def test_delete_discount_from_order_line_by_old_id(
variables = {
"orderLineId": graphene.Node.to_global_id("OrderLine", line.old_id),
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_REMOVE, variables)
content = get_graphql_content(response)
data = content["data"]["orderLineDiscountRemove"]
diff --git a/saleor/graphql/order/tests/integration/__init__.py b/saleor/graphql/order/tests/integration/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/order/tests/integration/test_draft_order.py b/saleor/graphql/order/tests/integration/test_draft_order.py
new file mode 100644
index 0000000000..558a54a77d
--- /dev/null
+++ b/saleor/graphql/order/tests/integration/test_draft_order.py
@@ -0,0 +1,162 @@
+import graphene
+import pytest
+
+from .....order import OrderStatus
+from ....account.tests.test_account_permission_group import (
+ PERMISSION_GROUP_UPDATE_MUTATION,
+)
+from ....tests.utils import assert_no_permission, get_graphql_content
+from ..mutations.test_draft_order_complete import DRAFT_ORDER_COMPLETE_MUTATION
+from ..mutations.test_draft_order_create import DRAFT_ORDER_CREATE_MUTATION
+from ..mutations.test_draft_order_update import DRAFT_ORDER_UPDATE_MUTATION
+from ..mutations.test_order_lines_create import ORDER_LINES_CREATE_MUTATION
+from ..mutations.test_order_mark_as_paid import MARK_ORDER_AS_PAID_MUTATION
+from ..queries.test_order import QUERY_ORDER_BY_ID
+
+
+def test_create_order_by_staff_in_accessible_channel(
+ staff_api_client,
+ permission_group_manage_orders,
+ channel_PLN,
+ channel_USD,
+ product,
+ shipping_method,
+ graphql_address_data,
+):
+ """Ensure that staff user is able to create and complete the draft order
+ in the channel he has access to."""
+ # given
+ permission_group_manage_orders.restricted_access_to_channels = True
+ permission_group_manage_orders.save(update_fields=["restricted_access_to_channels"])
+ permission_group_manage_orders.channels.add(channel_USD)
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+
+ # create order
+ draft_order_create_variables = {
+ "input": {
+ "userEmail": "[email protected]",
+ "billingAddress": graphql_address_data,
+ "shippingAddress": graphql_address_data,
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.id),
+ }
+ }
+ response = staff_api_client.post_graphql(
+ DRAFT_ORDER_CREATE_MUTATION, draft_order_create_variables
+ )
+
+ draft_order_id = get_graphql_content(response)["data"]["draftOrderCreate"]["order"][
+ "id"
+ ]
+
+ # add lines to order
+ variant = product.variants.first()
+ order_lines_create_variables = {
+ "orderId": draft_order_id,
+ "variantId": graphene.Node.to_global_id("ProductVariant", variant.id),
+ "quantity": 2,
+ }
+ staff_api_client.post_graphql(
+ ORDER_LINES_CREATE_MUTATION, order_lines_create_variables
+ )
+
+ # update order with available product and shipping method
+ draft_order_update_variables = {
+ "id": draft_order_id,
+ "input": {
+ "shippingMethod": graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.id
+ ),
+ },
+ }
+ staff_api_client.post_graphql(
+ DRAFT_ORDER_UPDATE_MUTATION, draft_order_update_variables
+ )
+
+ # complete order
+ staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, {"id": draft_order_id})
+
+ # then
+ # query created order
+ response = staff_api_client.post_graphql(QUERY_ORDER_BY_ID, {"id": draft_order_id})
+ content = get_graphql_content(response)
+ order_data = content["data"]["order"]
+ assert order_data["status"] == OrderStatus.UNFULFILLED.upper()
+
+
+def test_user_cannot_manage_draft_order_after_loosing_the_channel_access(
+ staff_api_client,
+ permission_group_manage_orders,
+ channel_USD,
+ graphql_address_data,
+ product,
+ shipping_method,
+ superuser_api_client,
+):
+ """Ensure that staff user cannot mark order as paid after loosing the access
+ to order channel."""
+ # given
+ permission_group_manage_orders.restricted_access_to_channels = True
+ permission_group_manage_orders.save(update_fields=["restricted_access_to_channels"])
+ permission_group_manage_orders.channels.add(channel_USD)
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ variant = product.variants.first()
+
+ # when
+
+ # create draft order
+ draft_order_create_variables = {
+ "input": {
+ "userEmail": "[email protected]",
+ "billingAddress": graphql_address_data,
+ "shippingAddress": graphql_address_data,
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.id),
+ "lines": [
+ {
+ "quantity": 1,
+ "variantId": graphene.Node.to_global_id(
+ "ProductVariant", variant.id
+ ),
+ }
+ ],
+ "shippingMethod": graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.id
+ ),
+ }
+ }
+ response = staff_api_client.post_graphql(
+ DRAFT_ORDER_CREATE_MUTATION, draft_order_create_variables
+ )
+
+ draft_order_id = get_graphql_content(response)["data"]["draftOrderCreate"]["order"][
+ "id"
+ ]
+
+ # complete order
+ staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, {"id": draft_order_id})
+
+ # update permission group - remove access to order channel
+ permission_group_update_variables = {
+ "id": graphene.Node.to_global_id("Group", permission_group_manage_orders.id),
+ "input": {
+ "restrictedAccessToChannels": True,
+ "removeChannels": [graphene.Node.to_global_id("Channel", channel_USD.id)],
+ },
+ }
+ superuser_api_client.post_graphql(
+ PERMISSION_GROUP_UPDATE_MUTATION, permission_group_update_variables
+ )
+
+ # try to mark order as paid
+ response = staff_api_client.post_graphql(
+ MARK_ORDER_AS_PAID_MUTATION, {"id": draft_order_id}
+ )
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/order/tests/integration/test_order.py b/saleor/graphql/order/tests/integration/test_order.py
new file mode 100644
index 0000000000..dc63726486
--- /dev/null
+++ b/saleor/graphql/order/tests/integration/test_order.py
@@ -0,0 +1,80 @@
+import graphene
+import pytest
+
+from ....account.tests.test_account_permission_group import (
+ PERMISSION_GROUP_UPDATE_MUTATION,
+)
+from ....tests.utils import assert_no_permission, get_graphql_content
+from ..mutations.test_fulfillment_cancel import CANCEL_FULFILLMENT_MUTATION
+from ..mutations.test_order_fulfill import ORDER_FULFILL_MUTATION
+
+
+def test_user_cannot_manage_order_after_loosing_the_channel_access(
+ staff_api_client,
+ superuser_api_client,
+ permission_group_manage_orders,
+ permission_group_all_perms_all_channels,
+ order_with_lines,
+ warehouse,
+ channel_PLN,
+):
+ """Ensure that staff user cannot cancel fulfillment after loosing the access
+ to order channel."""
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ permission_group_all_perms_all_channels.user_set.add(superuser_api_client.user)
+ order = order_with_lines
+ order_line_1, order_line_2 = order.lines.all()
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+
+ # when
+ # fulfill order
+ fulfill_order_variables = {
+ "order": order_id,
+ "input": {
+ "lines": [
+ {
+ "orderLineId": graphene.Node.to_global_id(
+ "OrderLine", order_line_1.id
+ ),
+ "stocks": [{"quantity": 3, "warehouse": warehouse_id}],
+ },
+ {
+ "orderLineId": graphene.Node.to_global_id(
+ "OrderLine", order_line_2.id
+ ),
+ "stocks": [{"quantity": 2, "warehouse": warehouse_id}],
+ },
+ ],
+ },
+ }
+
+ response = staff_api_client.post_graphql(
+ ORDER_FULFILL_MUTATION, fulfill_order_variables
+ )
+ fulfillment_id = get_graphql_content(response)["data"]["orderFulfill"][
+ "fulfillments"
+ ][0]["id"]
+
+ # update permission group - remove access to order channel
+ permission_group_update_variables = {
+ "id": graphene.Node.to_global_id("Group", permission_group_manage_orders.id),
+ "input": {
+ "restrictedAccessToChannels": True,
+ "addChannels": [graphene.Node.to_global_id("Channel", channel_PLN.id)],
+ },
+ }
+ superuser_api_client.post_graphql(
+ PERMISSION_GROUP_UPDATE_MUTATION, permission_group_update_variables
+ )
+
+ # try to cancel fulfillment
+ cancel_fulfillment_variables = {"id": fulfillment_id, "warehouseId": warehouse_id}
+ response = staff_api_client.post_graphql(
+ CANCEL_FULFILLMENT_MUTATION, cancel_fulfillment_variables
+ )
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_bulk_delete.py b/saleor/graphql/order/tests/mutations/test_draft_order_bulk_delete.py
index 34761d6cc4..1f79c1ec7d 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_bulk_delete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_bulk_delete.py
@@ -2,42 +2,94 @@ import graphene
from .....order import OrderStatus
from .....order import models as order_models
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
-MUTATION_DELETE_ORDER_LINES = """
-mutation draftOrderLinesBulkDelete($ids: [ID!]!) {
- draftOrderLinesBulkDelete(ids: $ids) {
- count
- errors {
- field
- message
+DRAFT_ORDER_BULK_DELETE = """
+ mutation draftOrderBulkDelete($ids: [ID!]!) {
+ draftOrderBulkDelete(ids: $ids) {
+ count
}
}
-}
"""
-def test_delete_draft_orders(staff_api_client, order_list, permission_manage_orders):
+def test_delete_draft_orders(
+ staff_api_client, order_list, permission_group_manage_orders
+):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_1, order_2, *orders = order_list
order_1.status = OrderStatus.DRAFT
order_2.status = OrderStatus.DRAFT
order_1.save()
order_2.save()
- query = """
- mutation draftOrderBulkDelete($ids: [ID!]!) {
- draftOrderBulkDelete(ids: $ids) {
- count
- }
+ query = DRAFT_ORDER_BULK_DELETE
+
+ variables = {
+ "ids": [graphene.Node.to_global_id("Order", order.id) for order in order_list]
}
- """
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ assert content["data"]["draftOrderBulkDelete"]["count"] == 2
+ assert not order_models.Order.objects.filter(
+ id__in=[order_1.id, order_2.id]
+ ).exists()
+ assert order_models.Order.objects.filter(
+ id__in=[order.id for order in orders]
+ ).count() == len(orders)
+
+
+def test_delete_draft_orders_by_user_no_channel_access(
+ staff_api_client,
+ order_list,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order_1, order_2, *orders = order_list
+ order_1.status = OrderStatus.DRAFT
+ order_1.channel = channel_PLN
+ order_2.status = OrderStatus.DRAFT
+ order_1.save()
+ order_2.save()
+
+ query = DRAFT_ORDER_BULK_DELETE
variables = {
"ids": [graphene.Node.to_global_id("Order", order.id) for order in order_list]
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_delete_draft_orders_by_app(
+ app_api_client, order_list, permission_manage_orders
+):
+ # given
+ order_1, order_2, *orders = order_list
+ order_1.status = OrderStatus.DRAFT
+ order_2.status = OrderStatus.DRAFT
+ order_1.save()
+ order_2.save()
+
+ query = DRAFT_ORDER_BULK_DELETE
+
+ variables = {
+ "ids": [graphene.Node.to_global_id("Order", order.id) for order in order_list]
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_orders,)
)
+
+ # then
content = get_graphql_content(response)
assert content["data"]["draftOrderBulkDelete"]["count"] == 2
@@ -49,9 +101,23 @@ def test_delete_draft_orders(staff_api_client, order_list, permission_manage_ord
).count() == len(orders)
+MUTATION_DELETE_ORDER_LINES = """
+ mutation draftOrderLinesBulkDelete($ids: [ID!]!) {
+ draftOrderLinesBulkDelete(ids: $ids) {
+ count
+ errors {
+ field
+ message
+ }
+ }
+ }
+"""
+
+
def test_fail_to_delete_non_draft_order_lines(
- staff_api_client, order_with_lines, permission_manage_orders
+ staff_api_client, order_with_lines, permission_group_manage_orders
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order_lines = [line for line in order.lines.all()]
# Ensure we cannot delete a non-draft order
@@ -64,9 +130,7 @@ def test_fail_to_delete_non_draft_order_lines(
for order_line in order_lines
]
}
- response = staff_api_client.post_graphql(
- MUTATION_DELETE_ORDER_LINES, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(MUTATION_DELETE_ORDER_LINES, variables)
content = get_graphql_content(response)
assert "errors" in content["data"]["draftOrderLinesBulkDelete"]
@@ -74,8 +138,9 @@ def test_fail_to_delete_non_draft_order_lines(
def test_delete_draft_order_lines(
- staff_api_client, order_with_lines, permission_manage_orders
+ staff_api_client, order_with_lines, permission_group_manage_orders
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order_lines = [line for line in order.lines.all()]
# Only lines in draft order can be deleted
@@ -89,9 +154,67 @@ def test_delete_draft_order_lines(
]
}
- response = staff_api_client.post_graphql(
- MUTATION_DELETE_ORDER_LINES, variables, permissions=[permission_manage_orders]
+ response = staff_api_client.post_graphql(MUTATION_DELETE_ORDER_LINES, variables)
+ content = get_graphql_content(response)
+
+ assert content["data"]["draftOrderLinesBulkDelete"]["count"] == 2
+ assert not order_models.OrderLine.objects.filter(
+ id__in=[order_line.pk for order_line in order_lines]
+ ).exists()
+
+
+def test_delete_draft_order_lines_by_user_no_channel_access(
+ staff_api_client,
+ order_with_lines,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = order_with_lines
+ order_lines = [line for line in order.lines.all()]
+ # Only lines in draft order can be deleted
+ order.status = OrderStatus.DRAFT
+ order.channel = channel_PLN
+ order.save(update_fields=["status", "channel"])
+
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("OrderLine", order_line.id)
+ for order_line in order_lines
+ ]
+ }
+
+ # when
+ response = staff_api_client.post_graphql(MUTATION_DELETE_ORDER_LINES, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_delete_draft_order_lines_by_app(
+ app_api_client, order_with_lines, permission_manage_orders
+):
+ # given
+ order = order_with_lines
+ order_lines = [line for line in order.lines.all()]
+ # Only lines in draft order can be deleted
+ order.status = OrderStatus.DRAFT
+ order.save()
+
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("OrderLine", order_line.id)
+ for order_line in order_lines
+ ]
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_DELETE_ORDER_LINES, variables, permissions=(permission_manage_orders,)
)
+
+ # then
content = get_graphql_content(response)
assert content["data"]["draftOrderLinesBulkDelete"]["count"] == 2
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
index f4b30f4054..1ff2c7b3fb 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -15,7 +15,7 @@ from .....product.models import ProductVariant
from .....warehouse.models import Allocation, PreorderAllocation, Stock
from .....warehouse.tests.utils import get_available_quantity_for_stock
from ....payment.types import PaymentChargeStatusEnum
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
DRAFT_ORDER_COMPLETE_MUTATION = """
mutation draftComplete($id: ID!) {
@@ -40,11 +40,12 @@ DRAFT_ORDER_COMPLETE_MUTATION = """
def test_draft_order_complete(
product_variant_out_of_stock_webhook_mock,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
draft_order,
):
order = draft_order
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Ensure no events were created
assert not OrderEvent.objects.exists()
@@ -54,9 +55,7 @@ def test_draft_order_complete(
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]["order"]
order.refresh_from_db()
@@ -86,15 +85,68 @@ def test_draft_order_complete(
)
+def test_draft_order_complete_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ draft_order,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = draft_order
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
+def test_draft_order_complete_by_app(
+ product_variant_out_of_stock_webhook_mock,
+ app_api_client,
+ draft_order,
+ permission_manage_orders,
+ channel_PLN,
+):
+ # given
+ order = draft_order
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ DRAFT_ORDER_COMPLETE_MUTATION,
+ variables,
+ permissions=(permission_manage_orders,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderComplete"]["order"]
+ order.refresh_from_db()
+ assert data["status"] == order.status.upper()
+ assert data["origin"] == OrderOrigin.DRAFT.upper()
+ assert order.search_vector
+
+
@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
def test_draft_order_complete_0_total(
product_variant_out_of_stock_webhook_mock,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
draft_order,
):
"""Ensure the payment status is FULLY_CHARGED when the total order price is 0."""
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
price = zero_taxed_money(order.currency)
order.shipping_price = price
@@ -116,9 +168,7 @@ def test_draft_order_complete_0_total(
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]["order"]
order.refresh_from_db()
@@ -154,10 +204,11 @@ def test_draft_order_complete_0_total(
def test_draft_order_complete_without_sku(
product_variant_out_of_stock_webhook_mock,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
draft_order,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
ProductVariant.objects.update(sku=None)
draft_order.lines.update(product_sku=None)
@@ -171,9 +222,7 @@ def test_draft_order_complete_without_sku(
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]["order"]
order.refresh_from_db()
@@ -206,9 +255,10 @@ def test_draft_order_complete_without_sku(
def test_draft_order_complete_with_out_of_stock_webhook(
product_variant_out_of_stock_webhook_mock,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
draft_order,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
first_line = order.lines.first()
first_line.quantity = 5
@@ -218,9 +268,7 @@ def test_draft_order_complete_with_out_of_stock_webhook(
assert not Allocation.objects.filter(order_line__order=order).exists()
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
total_stock = Stock.objects.aggregate(Sum("quantity"))["quantity__sum"]
total_allocation = Allocation.objects.filter(order_line__order=order).aggregate(
@@ -233,10 +281,11 @@ def test_draft_order_complete_with_out_of_stock_webhook(
def test_draft_order_from_reissue_complete(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
draft_order,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
order.origin = OrderOrigin.REISSUE
order.save(update_fields=["origin"])
@@ -249,9 +298,7 @@ def test_draft_order_from_reissue_complete(
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]["order"]
order.refresh_from_db()
@@ -279,10 +326,11 @@ def test_draft_order_from_reissue_complete(
def test_draft_order_complete_with_inactive_channel(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
draft_order,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
channel = order.channel
channel.is_active = False
@@ -290,9 +338,7 @@ def test_draft_order_complete_with_inactive_channel(
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]
assert data["errors"][0]["code"] == OrderErrorCode.CHANNEL_INACTIVE.name
@@ -301,10 +347,11 @@ def test_draft_order_complete_with_inactive_channel(
def test_draft_order_complete_with_unavailable_variant(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
draft_order,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
variant = order.lines.first().variant
variant.channel_listings.filter(channel=order.channel).delete()
@@ -313,9 +360,7 @@ def test_draft_order_complete_with_unavailable_variant(
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]
assert data["errors"][0]["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name
@@ -325,10 +370,11 @@ def test_draft_order_complete_with_unavailable_variant(
def test_draft_order_complete_channel_without_shipping_zones(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
draft_order,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
order.channel.shipping_zones.clear()
@@ -340,9 +386,7 @@ def test_draft_order_complete_channel_without_shipping_zones(
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]
@@ -357,10 +401,11 @@ def test_draft_order_complete_channel_without_shipping_zones(
def test_draft_order_complete_product_without_inventory_tracking(
staff_api_client,
shipping_method,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
draft_order_without_inventory_tracking,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order_without_inventory_tracking
order.shipping_method = shipping_method
order.save()
@@ -373,9 +418,7 @@ def test_draft_order_complete_product_without_inventory_tracking(
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]["order"]
@@ -404,11 +447,12 @@ def test_draft_order_complete_product_without_inventory_tracking(
def test_draft_order_complete_not_available_shipping_method(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
draft_order,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
order.channel.shipping_zones.clear()
@@ -422,9 +466,7 @@ def test_draft_order_complete_not_available_shipping_method(
variables = {"id": order_id}
# when
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
# then
content = get_graphql_content(response)
@@ -446,9 +488,10 @@ def test_draft_order_complete_with_excluded_shipping_method(
draft_order,
shipping_method,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
settings,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
webhook_reason = "archives-are-incomplete"
mocked_webhook.return_value = [
@@ -461,9 +504,7 @@ def test_draft_order_complete_with_excluded_shipping_method(
query = DRAFT_ORDER_COMPLETE_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]
assert (
@@ -478,9 +519,10 @@ def test_draft_order_complete_with_not_excluded_shipping_method(
draft_order,
shipping_method,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
settings,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
webhook_reason = "archives-are-incomplete"
other_shipping_method_id = "1337"
@@ -495,17 +537,16 @@ def test_draft_order_complete_with_not_excluded_shipping_method(
query = DRAFT_ORDER_COMPLETE_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]
assert len(data["errors"]) == 0
def test_draft_order_complete_out_of_stock_variant(
- staff_api_client, permission_manage_orders, staff_user, draft_order
+ staff_api_client, permission_group_manage_orders, staff_user, draft_order
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
# Ensure no events were created
@@ -518,9 +559,7 @@ def test_draft_order_complete_out_of_stock_variant(
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
error = content["data"]["draftOrderComplete"]["errors"][0]
order.refresh_from_db()
@@ -532,17 +571,16 @@ def test_draft_order_complete_out_of_stock_variant(
def test_draft_order_complete_existing_user_email_updates_user_field(
- staff_api_client, draft_order, customer_user, permission_manage_orders
+ staff_api_client, draft_order, customer_user, permission_group_manage_orders
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
order.user_email = customer_user.email
order.user = None
order.save()
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
assert "errors" not in content
order.refresh_from_db()
@@ -550,17 +588,16 @@ def test_draft_order_complete_existing_user_email_updates_user_field(
def test_draft_order_complete_anonymous_user_email_sets_user_field_null(
- staff_api_client, draft_order, permission_manage_orders
+ staff_api_client, draft_order, permission_group_manage_orders
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
order.user_email = "[email protected]"
order.user = None
order.save()
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
assert "errors" not in content
order.refresh_from_db()
@@ -568,17 +605,16 @@ def test_draft_order_complete_anonymous_user_email_sets_user_field_null(
def test_draft_order_complete_anonymous_user_no_email(
- staff_api_client, draft_order, permission_manage_orders
+ staff_api_client, draft_order, permission_group_manage_orders
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
order.user_email = ""
order.user = None
order.save()
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]["order"]
assert data["status"] == OrderStatus.UNFULFILLED.upper()
@@ -586,11 +622,12 @@ def test_draft_order_complete_anonymous_user_no_email(
def test_draft_order_complete_drops_shipping_address(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
draft_order,
address,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
order.shipping_address = address.get_copy()
order.billing_address = address.get_copy()
@@ -599,9 +636,7 @@ def test_draft_order_complete_drops_shipping_address(
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]["order"]
order.refresh_from_db()
@@ -612,9 +647,10 @@ def test_draft_order_complete_drops_shipping_address(
def test_draft_order_complete_unavailable_for_purchase(
- staff_api_client, permission_manage_orders, staff_user, draft_order
+ staff_api_client, permission_group_manage_orders, staff_user, draft_order
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
# Ensure no events were created
@@ -629,9 +665,7 @@ def test_draft_order_complete_unavailable_for_purchase(
variables = {"id": order_id}
# when
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
# then
content = get_graphql_content(response)
@@ -646,10 +680,11 @@ def test_draft_order_complete_unavailable_for_purchase(
def test_draft_order_complete_preorders(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
draft_order_with_preorder_lines,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order_with_preorder_lines
# Ensure no events were created
@@ -660,9 +695,7 @@ def test_draft_order_complete_preorders(
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]["order"]
order.refresh_from_db()
@@ -690,11 +723,12 @@ def test_draft_order_complete_preorders(
def test_draft_order_complete_insufficient_stock_preorders(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
draft_order_with_preorder_lines,
channel_USD,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order_with_preorder_lines
# Ensure no events were created
@@ -707,9 +741,7 @@ def test_draft_order_complete_insufficient_stock_preorders(
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
error = content["data"]["draftOrderComplete"]["errors"][0]
order.refresh_from_db()
@@ -722,14 +754,13 @@ def test_draft_order_complete_insufficient_stock_preorders(
def test_draft_order_complete_not_draft_order(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order_with_lines.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]
assert data["errors"][0]["code"] == OrderErrorCode.INVALID.name
@@ -738,10 +769,11 @@ def test_draft_order_complete_not_draft_order(
def test_draft_order_complete_display_gross_prices(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
draft_order,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
channel = order.channel
tax_config = channel.tax_configuration
@@ -756,9 +788,7 @@ def test_draft_order_complete_display_gross_prices(
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
content = get_graphql_content(response)
assert not content["data"]["draftOrderComplete"]["errors"]
order.refresh_from_db()
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
index e6205e6c05..0a4ec4e784 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -13,26 +13,14 @@ from .....order import events as order_events
from .....order.error_codes import OrderErrorCode
from .....order.models import Order, OrderEvent
from .....product.models import ProductVariant
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
DRAFT_ORDER_CREATE_MUTATION = """
mutation draftCreate(
- $user: ID, $discount: PositiveDecimal, $lines: [OrderLineCreateInput!],
- $shippingAddress: AddressInput, $billingAddress: AddressInput,
- $shippingMethod: ID, $voucher: ID, $customerNote: String, $channel: ID,
- $redirectUrl: String, $externalReference: String
+ $input: DraftOrderCreateInput!
) {
draftOrderCreate(
- input: {
- user: $user, discount: $discount,
- lines: $lines, shippingAddress: $shippingAddress,
- billingAddress: $billingAddress,
- shippingMethod: $shippingMethod, voucher: $voucher,
- channelId: $channel,
- redirectUrl: $redirectUrl,
- customerNote: $customerNote,
- externalReference: $externalReference
- }
+ input: $input
) {
errors {
field
@@ -83,7 +71,7 @@ DRAFT_ORDER_CREATE_MUTATION = """
def test_draft_order_create(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
customer_user,
product_without_shipping,
@@ -95,6 +83,7 @@ def test_draft_order_create(
):
variant_0 = variant
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
@@ -119,21 +108,21 @@ def test_draft_order_create(
external_reference = "test-ext-ref"
variables = {
- "user": user_id,
- "discount": discount,
- "lines": variant_list,
- "billingAddress": shipping_address,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
- "voucher": voucher_id,
- "customerNote": customer_note,
- "channel": channel_id,
- "redirectUrl": redirect_url,
- "externalReference": external_reference,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "channelId": channel_id,
+ "redirectUrl": redirect_url,
+ "externalReference": external_reference,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
assert not content["data"]["draftOrderCreate"]["errors"]
data = content["data"]["draftOrderCreate"]["order"]
@@ -189,9 +178,110 @@ def test_draft_order_create(
assert event_parameters["lines"][1]["quantity"] == 1
-def test_draft_order_create_with_same_variant_and_force_new_line(
+def test_draft_order_create_by_user_no_channel_access(
staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ staff_user,
+ customer_user,
+ product_without_shipping,
+ shipping_method,
+ product_available_in_many_channels,
+ voucher,
+ channel_PLN,
+ graphql_address_data,
+ warehouse,
+):
+ # given
+ variant = product_available_in_many_channels.variants.first()
+ query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variant_list = [
+ {"variantId": variant_id, "quantity": 2},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ redirect_url = "https://www.example.com"
+
+ variables = {
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "channelId": channel_id,
+ "redirectUrl": redirect_url,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_draft_order_create_by_app(
+ app_api_client,
permission_manage_orders,
+ customer_user,
+ product_without_shipping,
+ shipping_method_channel_PLN,
+ product_available_in_many_channels,
+ voucher,
+ channel_PLN,
+ graphql_address_data,
+ warehouse,
+):
+ # given
+ variant = product_available_in_many_channels.variants.first()
+ query = DRAFT_ORDER_CREATE_MUTATION
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variant_list = [
+ {"variantId": variant_id, "quantity": 2},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method_channel_PLN.id
+ )
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ redirect_url = "https://www.example.com"
+
+ variables = {
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "channelId": channel_id,
+ "redirectUrl": redirect_url,
+ }
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["draftOrderCreate"]["errors"]
+ data = content["data"]["draftOrderCreate"]["order"]
+ assert data["status"] == OrderStatus.DRAFT.upper()
+
+
+def test_draft_order_create_with_same_variant_and_force_new_line(
+ staff_api_client,
+ permission_group_manage_orders,
staff_user,
customer_user,
shipping_method,
@@ -202,6 +292,7 @@ def test_draft_order_create_with_same_variant_and_force_new_line(
):
variant_0 = variant
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
@@ -222,20 +313,20 @@ def test_draft_order_create_with_same_variant_and_force_new_line(
redirect_url = "https://www.example.com"
variables = {
- "user": user_id,
- "discount": discount,
- "lines": variant_list,
- "billingAddress": shipping_address,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
- "voucher": voucher_id,
- "customerNote": customer_note,
- "channel": channel_id,
- "redirectUrl": redirect_url,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "channelId": channel_id,
+ "redirectUrl": redirect_url,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
assert not content["data"]["draftOrderCreate"]["errors"]
data = content["data"]["draftOrderCreate"]["order"]
@@ -290,7 +381,7 @@ def test_draft_order_create_with_same_variant_and_force_new_line(
def test_draft_order_create_with_inactive_channel(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
customer_user,
product_without_shipping,
@@ -302,6 +393,7 @@ def test_draft_order_create_with_inactive_channel(
):
variant_0 = variant
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
@@ -325,18 +417,18 @@ def test_draft_order_create_with_inactive_channel(
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
variables = {
- "user": user_id,
- "discount": discount,
- "lines": variant_list,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
- "voucher": voucher_id,
- "customerNote": customer_note,
- "channel": channel_id,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "channelId": channel_id,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
assert not content["data"]["draftOrderCreate"]["errors"]
data = content["data"]["draftOrderCreate"]["order"]
@@ -365,7 +457,7 @@ def test_draft_order_create_with_inactive_channel(
def test_draft_order_create_without_sku(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
customer_user,
product_without_shipping,
@@ -377,6 +469,7 @@ def test_draft_order_create_without_sku(
):
variant_0 = variant
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
@@ -402,20 +495,20 @@ def test_draft_order_create_without_sku(
redirect_url = "https://www.example.com"
variables = {
- "user": user_id,
- "discount": discount,
- "lines": variant_list,
- "billingAddress": shipping_address,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
- "voucher": voucher_id,
- "customerNote": customer_note,
- "channel": channel_id,
- "redirectUrl": redirect_url,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "channelId": channel_id,
+ "redirectUrl": redirect_url,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
assert not content["data"]["draftOrderCreate"]["errors"]
data = content["data"]["draftOrderCreate"]["order"]
@@ -456,7 +549,7 @@ def test_draft_order_create_without_sku(
def test_draft_order_create_variant_with_0_price(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
customer_user,
product_without_shipping,
@@ -468,6 +561,7 @@ def test_draft_order_create_variant_with_0_price(
):
variant_0 = variant
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
@@ -486,15 +580,15 @@ def test_draft_order_create_variant_with_0_price(
shipping_address = graphql_address_data
shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
variables = {
- "user": user_id,
- "lines": variant_list,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
- "channel": channel_id,
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "channelId": channel_id,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
assert not content["data"]["draftOrderCreate"]["errors"]
data = content["data"]["draftOrderCreate"]["order"]
@@ -524,7 +618,7 @@ def test_draft_order_create_variant_with_0_price(
def test_draft_order_create_tax_error(
create_order_line_mock,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
customer_user,
product_without_shipping,
@@ -534,6 +628,7 @@ def test_draft_order_create_tax_error(
graphql_address_data,
channel_USD,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variant_0 = variant
err_msg = "Test error"
create_order_line_mock.side_effect = TaxError(err_msg)
@@ -558,18 +653,18 @@ def test_draft_order_create_tax_error(
shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
variables = {
- "user": user_id,
- "discount": discount,
- "lines": variant_list,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
- "voucher": voucher_id,
- "customerNote": customer_note,
- "channel": channel_id,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "channelId": channel_id,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderCreate"]
errors = data["errors"]
@@ -584,7 +679,7 @@ def test_draft_order_create_tax_error(
def test_draft_order_create_with_voucher_not_assigned_to_order_channel(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
customer_user,
shipping_method,
@@ -594,6 +689,7 @@ def test_draft_order_create_with_voucher_not_assigned_to_order_channel(
graphql_address_data,
):
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
user_id = graphene.Node.to_global_id("User", customer_user.id)
@@ -609,18 +705,18 @@ def test_draft_order_create_with_voucher_not_assigned_to_order_channel(
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
voucher.channel_listings.all().delete()
variables = {
- "user": user_id,
- "discount": discount,
- "lines": variant_list,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
- "voucher": voucher_id,
- "customerNote": customer_note,
- "channel": channel_id,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "channelId": channel_id,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
error = content["data"]["draftOrderCreate"]["errors"][0]
assert error["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name
@@ -629,7 +725,7 @@ def test_draft_order_create_with_voucher_not_assigned_to_order_channel(
def test_draft_order_create_with_product_and_variant_not_assigned_to_order_channel(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
shipping_method,
variant,
@@ -637,6 +733,7 @@ def test_draft_order_create_with_product_and_variant_not_assigned_to_order_chann
graphql_address_data,
):
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
user_id = graphene.Node.to_global_id("User", customer_user.id)
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
discount = "10"
@@ -650,17 +747,17 @@ def test_draft_order_create_with_product_and_variant_not_assigned_to_order_chann
variant.product.channel_listings.all().delete()
variant.channel_listings.all().delete()
variables = {
- "user": user_id,
- "discount": discount,
- "lines": variant_list,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
- "customerNote": customer_note,
- "channel": channel_id,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "customerNote": customer_note,
+ "channelId": channel_id,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
error = content["data"]["draftOrderCreate"]["errors"][0]
assert error["code"] == OrderErrorCode.PRODUCT_NOT_PUBLISHED.name
@@ -670,7 +767,7 @@ def test_draft_order_create_with_product_and_variant_not_assigned_to_order_chann
def test_draft_order_create_with_variant_not_assigned_to_order_channel(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
shipping_method,
variant,
@@ -678,6 +775,7 @@ def test_draft_order_create_with_variant_not_assigned_to_order_channel(
graphql_address_data,
):
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
user_id = graphene.Node.to_global_id("User", customer_user.id)
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
@@ -691,17 +789,17 @@ def test_draft_order_create_with_variant_not_assigned_to_order_channel(
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
variant.channel_listings.all().delete()
variables = {
- "user": user_id,
- "discount": discount,
- "lines": variant_list,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
- "customerNote": customer_note,
- "channel": channel_id,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "customerNote": customer_note,
+ "channelId": channel_id,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
error = content["data"]["draftOrderCreate"]["errors"][0]
assert error["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name
@@ -711,7 +809,7 @@ def test_draft_order_create_with_variant_not_assigned_to_order_channel(
def test_draft_order_create_without_channel(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
customer_user,
product_without_shipping,
@@ -722,6 +820,7 @@ def test_draft_order_create_without_channel(
):
variant_0 = variant
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
user_id = graphene.Node.to_global_id("User", customer_user.id)
variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
@@ -734,12 +833,12 @@ def test_draft_order_create_without_channel(
{"variantId": variant_1_id, "quantity": 1},
]
variables = {
- "user": user_id,
- "lines": variant_list,
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
error = content["data"]["draftOrderCreate"]["errors"][0]
assert error["code"] == OrderErrorCode.REQUIRED.name
@@ -748,7 +847,7 @@ def test_draft_order_create_without_channel(
def test_draft_order_create_with_negative_quantity_line(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
customer_user,
product_without_shipping,
@@ -760,6 +859,7 @@ def test_draft_order_create_with_negative_quantity_line(
):
variant_0 = variant
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
user_id = graphene.Node.to_global_id("User", customer_user.id)
variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
@@ -774,13 +874,13 @@ def test_draft_order_create_with_negative_quantity_line(
{"variantId": variant_1_id, "quantity": 1},
]
variables = {
- "user": user_id,
- "lines": variant_list,
- "channel": channel_id,
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "channelId": channel_id,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
error = content["data"]["draftOrderCreate"]["errors"][0]
assert error["code"] == OrderErrorCode.ZERO_QUANTITY.name
@@ -789,7 +889,7 @@ def test_draft_order_create_with_negative_quantity_line(
def test_draft_order_create_with_channel_with_unpublished_product(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
customer_user,
product_without_shipping,
@@ -801,6 +901,7 @@ def test_draft_order_create_with_channel_with_unpublished_product(
):
variant_0 = variant
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
@@ -826,19 +927,19 @@ def test_draft_order_create_with_channel_with_unpublished_product(
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
variables = {
- "user": user_id,
- "discount": discount,
- "channel": channel_id,
- "lines": variant_list,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
- "voucher": voucher_id,
- "customerNote": customer_note,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "channelId": channel_id,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
error = content["data"]["draftOrderCreate"]["errors"][0]
@@ -849,7 +950,7 @@ def test_draft_order_create_with_channel_with_unpublished_product(
def test_draft_order_create_with_channel_with_unpublished_product_by_date(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
customer_user,
product_without_shipping,
@@ -861,6 +962,7 @@ def test_draft_order_create_with_channel_with_unpublished_product_by_date(
):
variant_0 = variant
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
@@ -886,19 +988,19 @@ def test_draft_order_create_with_channel_with_unpublished_product_by_date(
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
variables = {
- "user": user_id,
- "discount": discount,
- "channel": channel_id,
- "lines": variant_list,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
- "voucher": voucher_id,
- "customerNote": customer_note,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "channelId": channel_id,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
error = content["data"]["draftOrderCreate"]["errors"][0]
@@ -909,7 +1011,7 @@ def test_draft_order_create_with_channel_with_unpublished_product_by_date(
def test_draft_order_create_with_channel(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
customer_user,
product_without_shipping,
@@ -921,6 +1023,7 @@ def test_draft_order_create_with_channel(
):
variant_0 = variant
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
@@ -943,18 +1046,18 @@ def test_draft_order_create_with_channel(
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
variables = {
- "user": user_id,
- "discount": discount,
- "channel": channel_id,
- "lines": variant_list,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
- "voucher": voucher_id,
- "customerNote": customer_note,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "channelId": channel_id,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
assert not content["data"]["draftOrderCreate"]["errors"]
data = content["data"]["draftOrderCreate"]["order"]
@@ -984,7 +1087,7 @@ def test_draft_order_create_with_channel(
def test_draft_order_create_product_without_shipping(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
customer_user,
product_without_shipping,
@@ -995,6 +1098,7 @@ def test_draft_order_create_product_without_shipping(
):
# given
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
@@ -1015,20 +1119,20 @@ def test_draft_order_create_product_without_shipping(
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
variables = {
- "user": user_id,
- "discount": discount,
- "channel": channel_id,
- "lines": variant_list,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
- "voucher": voucher_id,
- "customerNote": customer_note,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "channelId": channel_id,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ }
}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
@@ -1057,7 +1161,7 @@ def test_draft_order_create_product_without_shipping(
def test_draft_order_create_invalid_billing_address(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
customer_user,
product_without_shipping,
@@ -1069,6 +1173,7 @@ def test_draft_order_create_invalid_billing_address(
):
variant_0 = variant
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
@@ -1093,20 +1198,20 @@ def test_draft_order_create_invalid_billing_address(
redirect_url = "https://www.example.com"
variables = {
- "user": user_id,
- "discount": discount,
- "lines": variant_list,
- "billingAddress": billing_address,
- "shippingAddress": graphql_address_data,
- "shippingMethod": shipping_id,
- "voucher": voucher_id,
- "customerNote": customer_note,
- "channel": channel_id,
- "redirectUrl": redirect_url,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "billingAddress": billing_address,
+ "shippingAddress": graphql_address_data,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "channelId": channel_id,
+ "redirectUrl": redirect_url,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
errors = content["data"]["draftOrderCreate"]["errors"]
assert len(errors) == 1
@@ -1117,7 +1222,7 @@ def test_draft_order_create_invalid_billing_address(
def test_draft_order_create_invalid_shipping_address(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_user,
customer_user,
product_without_shipping,
@@ -1129,6 +1234,7 @@ def test_draft_order_create_invalid_shipping_address(
):
variant_0 = variant
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
@@ -1153,20 +1259,20 @@ def test_draft_order_create_invalid_shipping_address(
redirect_url = "https://www.example.com"
variables = {
- "user": user_id,
- "discount": discount,
- "lines": variant_list,
- "billingAddress": graphql_address_data,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
- "voucher": voucher_id,
- "customerNote": customer_note,
- "channel": channel_id,
- "redirectUrl": redirect_url,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "billingAddress": graphql_address_data,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "channelId": channel_id,
+ "redirectUrl": redirect_url,
+ }
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
errors = content["data"]["draftOrderCreate"]["errors"]
assert len(errors) == 1
@@ -1179,7 +1285,7 @@ def test_draft_order_create_invalid_shipping_address(
def test_draft_order_create_price_recalculation(
mock_fetch_order_prices_if_expired,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
product_available_in_many_channels,
product_variant_list,
@@ -1188,6 +1294,7 @@ def test_draft_order_create_price_recalculation(
voucher,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
fake_order = Mock()
fake_order.total = zero_taxed_money(channel_PLN.currency_code)
response = Mock(return_value=(fake_order, None))
@@ -1215,19 +1322,19 @@ def test_draft_order_create_price_recalculation(
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
variables = {
- "user": user_id,
- "discount": discount,
- "lines": lines,
- "billingAddress": address,
- "shippingAddress": address,
- "voucher": voucher_id,
- "channel": channel_id,
+ "input": {
+ "user": user_id,
+ "discount": discount,
+ "lines": lines,
+ "billingAddress": address,
+ "shippingAddress": address,
+ "voucher": voucher_id,
+ "channelId": channel_id,
+ }
}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
@@ -1240,7 +1347,7 @@ def test_draft_order_create_price_recalculation(
def test_draft_order_create_update_display_gross_prices(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
variant,
channel_USD,
graphql_address_data,
@@ -1248,6 +1355,7 @@ def test_draft_order_create_update_display_gross_prices(
# given
# display_gross_prices is disabled and there is no country-specific configuration
# order.display_gross_prices should be also disabled as a result
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
tax_config = channel_USD.tax_configuration
tax_config.display_gross_prices = False
@@ -1262,16 +1370,16 @@ def test_draft_order_create_update_display_gross_prices(
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
variables = {
- "lines": variant_list,
- "billingAddress": graphql_address_data,
- "shippingAddress": graphql_address_data,
- "channel": channel_id,
+ "input": {
+ "lines": variant_list,
+ "billingAddress": graphql_address_data,
+ "shippingAddress": graphql_address_data,
+ "channelId": channel_id,
+ }
}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
# then
content = get_graphql_content(response)
@@ -1285,24 +1393,23 @@ def test_draft_order_create_update_display_gross_prices(
def test_draft_order_create_with_non_unique_external_reference(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
channel_USD,
order,
):
# given
query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
ext_ref = "test-ext-ref"
order.external_reference = ext_ref
order.save(update_fields=["external_reference"])
- variables = {"channel": channel_id, "externalReference": ext_ref}
+ variables = {"input": {"channelId": channel_id, "externalReference": ext_ref}}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_delete.py b/saleor/graphql/order/tests/mutations/test_draft_order_delete.py
index 55b2b278eb..fc62c5ff77 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_delete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_delete.py
@@ -3,51 +3,34 @@ import pytest
from .....order import OrderStatus
from .....order.error_codes import OrderErrorCode
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
-
-def test_draft_order_delete(staff_api_client, permission_manage_orders, draft_order):
- order = draft_order
- query = """
- mutation draftDelete($id: ID!) {
- draftOrderDelete(id: $id) {
- order {
- id
- }
+DRAFT_ORDER_DELETE_MUTATION = """
+ mutation draftDelete($id: ID!) {
+ draftOrderDelete(id: $id) {
+ order {
+ id
+ }
+ errors {
+ code
+ field
}
}
- """
- order_id = graphene.Node.to_global_id("Order", order.id)
- variables = {"id": order_id}
- staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
- with pytest.raises(order._meta.model.DoesNotExist):
- order.refresh_from_db()
+ }
+"""
-def test_draft_order_delete_product(
- app_api_client, permission_manage_products, draft_order
+def test_draft_order_delete(
+ staff_api_client, permission_group_manage_orders, draft_order
):
- query = """
- mutation DeleteProduct($id: ID!) {
- productDelete(id: $id) {
- product {
- id
- }
- }
- }
- """
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
- line = order.lines.first()
- product = line.variant.product
- product_id = graphene.Node.to_global_id("Product", product.id)
- variables = {"id": product_id}
- response = app_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- assert content["data"]["productDelete"]["product"]["id"] == product_id
+ query = DRAFT_ORDER_DELETE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+ staff_api_client.post_graphql(query, variables)
+ with pytest.raises(order._meta.model.DoesNotExist):
+ order.refresh_from_db()
@pytest.mark.parametrize(
@@ -64,29 +47,16 @@ def test_draft_order_delete_product(
],
)
def test_draft_order_delete_non_draft_order(
- staff_api_client, permission_manage_orders, order_with_lines, order_status
+ staff_api_client, permission_group_manage_orders, order_with_lines, order_status
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.status = order_status
order.save(update_fields=["status"])
- query = """
- mutation draftDelete($id: ID!) {
- draftOrderDelete(id: $id) {
- order {
- id
- }
- errors {
- code
- field
- }
- }
- }
- """
+ query = DRAFT_ORDER_DELETE_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
account_errors = content["data"]["draftOrderDelete"]["errors"]
assert len(account_errors) == 1
@@ -94,6 +64,75 @@ def test_draft_order_delete_non_draft_order(
assert account_errors[0]["code"] == OrderErrorCode.INVALID.name
+def test_draft_order_delete_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ draft_order,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = draft_order
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ query = DRAFT_ORDER_DELETE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_draft_order_delete_by_app(
+ app_api_client, permission_manage_orders, draft_order, channel_PLN
+):
+ # given
+ order = draft_order
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ query = DRAFT_ORDER_DELETE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ app_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ with pytest.raises(order._meta.model.DoesNotExist):
+ order.refresh_from_db()
+
+
+def test_draft_order_delete_product(
+ app_api_client, permission_manage_products, draft_order
+):
+ query = """
+ mutation DeleteProduct($id: ID!) {
+ productDelete(id: $id) {
+ product {
+ id
+ }
+ }
+ }
+ """
+ order = draft_order
+ line = order.lines.first()
+ product = line.variant.product
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ variables = {"id": product_id}
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["productDelete"]["product"]["id"] == product_id
+
+
DRAFT_ORDER_DELETE_BY_EXTERNAL_REFERENCE = """
mutation draftDelete($id: ID, $externalReference: String) {
draftOrderDelete(id: $id, externalReference: $externalReference) {
@@ -111,9 +150,10 @@ DRAFT_ORDER_DELETE_BY_EXTERNAL_REFERENCE = """
def test_draft_order_delete_by_external_reference(
- staff_api_client, permission_manage_orders, draft_order
+ staff_api_client, permission_group_manage_orders, draft_order
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
query = DRAFT_ORDER_DELETE_BY_EXTERNAL_REFERENCE
ext_ref = "test-ext-ref"
@@ -122,9 +162,7 @@ def test_draft_order_delete_by_external_reference(
variables = {"externalReference": ext_ref}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
@@ -136,16 +174,15 @@ def test_draft_order_delete_by_external_reference(
def test_draft_order_delete_by_both_id_and_external_reference(
- staff_api_client, permission_manage_orders
+ staff_api_client, permission_group_manage_orders
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = DRAFT_ORDER_DELETE_BY_EXTERNAL_REFERENCE
variables = {"externalReference": "whatever", "id": "whatever"}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
@@ -157,17 +194,16 @@ def test_draft_order_delete_by_both_id_and_external_reference(
def test_draft_order_delete_by_external_reference_not_existing(
- staff_api_client, permission_manage_orders
+ staff_api_client, permission_group_manage_orders
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = DRAFT_ORDER_DELETE_BY_EXTERNAL_REFERENCE
ext_ref = "non-existing-ext-ref"
variables = {"externalReference": ext_ref}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_update.py b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
index 507688b8f7..e3f1316a4a 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
@@ -6,9 +6,9 @@ from .....core.taxes import zero_money
from .....order import OrderStatus
from .....order.error_codes import OrderErrorCode
from .....order.models import OrderEvent
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
-DRAFT_UPDATE_QUERY = """
+DRAFT_ORDER_UPDATE_MUTATION = """
mutation draftUpdate(
$id: ID!,
$input: DraftOrderInput!,
@@ -24,6 +24,7 @@ DRAFT_UPDATE_QUERY = """
}
order {
userEmail
+ externalReference
channel {
id
}
@@ -34,12 +35,13 @@ DRAFT_UPDATE_QUERY = """
def test_draft_order_update_existing_channel_id(
- staff_api_client, permission_manage_orders, order_with_lines, channel_PLN
+ staff_api_client, permission_group_manage_orders, order_with_lines, channel_PLN
):
order = order_with_lines
order.status = OrderStatus.DRAFT
order.save()
- query = DRAFT_UPDATE_QUERY
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ query = DRAFT_ORDER_UPDATE_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
variables = {
@@ -49,9 +51,7 @@ def test_draft_order_update_existing_channel_id(
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
error = content["data"]["draftOrderUpdate"]["errors"][0]
@@ -60,13 +60,14 @@ def test_draft_order_update_existing_channel_id(
def test_draft_order_update_voucher_not_available(
- staff_api_client, permission_manage_orders, order_with_lines, voucher
+ staff_api_client, permission_group_manage_orders, order_with_lines, voucher
):
order = order_with_lines
order.status = OrderStatus.DRAFT
order.save()
assert order.voucher is None
- query = DRAFT_UPDATE_QUERY
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ query = DRAFT_ORDER_UPDATE_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
voucher.channel_listings.all().delete()
@@ -77,9 +78,7 @@ def test_draft_order_update_voucher_not_available(
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
error = content["data"]["draftOrderUpdate"]["errors"][0]
@@ -87,39 +86,13 @@ def test_draft_order_update_voucher_not_available(
assert error["field"] == "voucher"
-DRAFT_ORDER_UPDATE_MUTATION = """
- mutation draftUpdate(
- $id: ID!, $voucher: ID!, $customerNote: String, $shippingAddress: AddressInput,
- $externalReference: String
- ) {
- draftOrderUpdate(
- id: $id,
- input: {
- voucher: $voucher,
- customerNote: $customerNote,
- shippingAddress: $shippingAddress,
- externalReference: $externalReference
- }) {
- errors {
- field
- message
- code
- }
- order {
- userEmail
- externalReference
- }
- }
- }
-"""
-
-
def test_draft_order_update(
- staff_api_client, permission_manage_orders, draft_order, voucher
+ staff_api_client, permission_group_manage_orders, draft_order, voucher
):
order = draft_order
assert not order.voucher
assert not order.customer_note
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = DRAFT_ORDER_UPDATE_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
@@ -127,14 +100,14 @@ def test_draft_order_update(
external_reference = "test-ext-ref"
variables = {
"id": order_id,
- "voucher": voucher_id,
- "customerNote": customer_note,
- "externalReference": external_reference,
+ "input": {
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "externalReference": external_reference,
+ },
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderUpdate"]
assert not data["errors"]
@@ -150,17 +123,19 @@ def test_draft_order_update(
def test_draft_order_update_with_non_draft_order(
- staff_api_client, permission_manage_orders, order_with_lines, voucher
+ staff_api_client, permission_group_manage_orders, order_with_lines, voucher
):
order = order_with_lines
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = DRAFT_ORDER_UPDATE_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
customer_note = "Test customer note"
- variables = {"id": order_id, "voucher": voucher_id, "customerNote": customer_note}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ variables = {
+ "id": order_id,
+ "input": {"voucher": voucher_id, "customerNote": customer_note},
+ }
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
error = content["data"]["draftOrderUpdate"]["errors"][0]
assert error["field"] == "id"
@@ -169,7 +144,7 @@ def test_draft_order_update_with_non_draft_order(
def test_draft_order_update_invalid_address(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
draft_order,
voucher,
graphql_address_data,
@@ -178,19 +153,20 @@ def test_draft_order_update_invalid_address(
assert not order.voucher
assert not order.customer_note
graphql_address_data["postalCode"] = "TEST TEST invalid postal code 12345"
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = DRAFT_ORDER_UPDATE_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
variables = {
"id": order_id,
- "voucher": voucher_id,
- "shippingAddress": graphql_address_data,
+ "input": {
+ "voucher": voucher_id,
+ "shippingAddress": graphql_address_data,
+ },
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderUpdate"]
assert len(data["errors"]) == 2
@@ -202,9 +178,75 @@ def test_draft_order_update_invalid_address(
assert {error["field"] for error in data["errors"]} == {"postalCode"}
+def test_draft_order_update_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ draft_order,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = draft_order
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ assert not order.customer_note
+
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ customer_note = "Test customer note"
+ variables = {
+ "id": order_id,
+ "input": {
+ "customerNote": customer_note,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_draft_order_update_by_app(
+ app_api_client, permission_manage_orders, draft_order, channel_PLN
+):
+ # given
+ order = draft_order
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ assert not order.customer_note
+
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ customer_note = "Test customer note"
+ variables = {
+ "id": order_id,
+ "input": {
+ "customerNote": customer_note,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderUpdate"]
+ assert not data["errors"]
+ order.refresh_from_db()
+ assert order.customer_note == customer_note
+ assert order.search_vector
+
+
def test_draft_order_update_doing_nothing_generates_no_events(
- staff_api_client, permission_manage_orders, order_with_lines
+ staff_api_client, permission_group_manage_orders, order_with_lines
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
assert not OrderEvent.objects.exists()
query = """
@@ -218,9 +260,7 @@ def test_draft_order_update_doing_nothing_generates_no_events(
}
"""
order_id = graphene.Node.to_global_id("Order", order_with_lines.id)
- response = staff_api_client.post_graphql(
- query, {"id": order_id}, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, {"id": order_id})
get_graphql_content(response)
# Ensure not event was created
@@ -228,8 +268,9 @@ def test_draft_order_update_doing_nothing_generates_no_events(
def test_draft_order_update_free_shipping_voucher(
- staff_api_client, permission_manage_orders, draft_order, voucher_free_shipping
+ staff_api_client, permission_group_manage_orders, draft_order, voucher_free_shipping
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
assert not order.voucher
query = """
@@ -261,9 +302,7 @@ def test_draft_order_update_free_shipping_voucher(
"id": order_id,
"voucher": voucher_id,
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderUpdate"]
assert not data["errors"]
@@ -297,9 +336,10 @@ DRAFT_ORDER_UPDATE_USER_EMAIL_MUTATION = """
def test_draft_order_update_when_not_existing_customer_email_provided(
- staff_api_client, permission_manage_orders, draft_order
+ staff_api_client, permission_group_manage_orders, draft_order
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
assert order.user
@@ -309,9 +349,7 @@ def test_draft_order_update_when_not_existing_customer_email_provided(
variables = {"id": order_id, "userEmail": email}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderUpdate"]
order.refresh_from_db()
@@ -323,9 +361,10 @@ def test_draft_order_update_when_not_existing_customer_email_provided(
def test_draft_order_update_assign_user_when_existing_customer_email_provided(
- staff_api_client, permission_manage_orders, draft_order
+ staff_api_client, permission_group_manage_orders, draft_order
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
user = order.user
user_email = user.email
@@ -338,9 +377,7 @@ def test_draft_order_update_assign_user_when_existing_customer_email_provided(
variables = {"id": order_id, "userEmail": user_email}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderUpdate"]
order.refresh_from_db()
@@ -380,9 +417,10 @@ DRAFT_ORDER_UPDATE_BY_EXTERNAL_REFERENCE = """
def test_draft_order_update_by_external_reference(
- staff_api_client, permission_manage_orders, draft_order, voucher_free_shipping
+ staff_api_client, permission_group_manage_orders, draft_order, voucher_free_shipping
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = DRAFT_ORDER_UPDATE_BY_EXTERNAL_REFERENCE
order = draft_order
@@ -399,9 +437,7 @@ def test_draft_order_update_by_external_reference(
}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
@@ -415,9 +451,10 @@ def test_draft_order_update_by_external_reference(
def test_draft_order_update_by_both_id_and_external_reference(
- staff_api_client, permission_manage_orders, voucher_free_shipping
+ staff_api_client, permission_group_manage_orders, voucher_free_shipping
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = DRAFT_ORDER_UPDATE_BY_EXTERNAL_REFERENCE
variables = {
@@ -427,9 +464,7 @@ def test_draft_order_update_by_both_id_and_external_reference(
}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
@@ -442,9 +477,10 @@ def test_draft_order_update_by_both_id_and_external_reference(
def test_draft_order_update_by_external_reference_not_existing(
- staff_api_client, permission_manage_orders, voucher_free_shipping
+ staff_api_client, permission_group_manage_orders, voucher_free_shipping
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = DRAFT_ORDER_UPDATE_BY_EXTERNAL_REFERENCE
ext_ref = "non-existing-ext-ref"
variables = {
@@ -453,9 +489,7 @@ def test_draft_order_update_by_external_reference_not_existing(
}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
@@ -466,11 +500,12 @@ def test_draft_order_update_by_external_reference_not_existing(
def test_draft_order_update_with_non_unique_external_reference(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
draft_order,
order_list,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = DRAFT_ORDER_UPDATE_BY_EXTERNAL_REFERENCE
draft_order_id = graphene.Node.to_global_id("Order", draft_order.pk)
@@ -482,9 +517,7 @@ def test_draft_order_update_with_non_unique_external_reference(
variables = {"id": draft_order_id, "input": {"externalReference": ext_ref}}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
@@ -524,9 +557,10 @@ DRAFT_ORDER_UPDATE_MUTATION_SHIPPING_METHOD = """
def test_draft_order_update_shipping_method(
- staff_api_client, permission_manage_orders, draft_order, shipping_method
+ staff_api_client, permission_group_manage_orders, draft_order, shipping_method
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
order.shipping_method = None
order.base_shipping_price = zero_money(order.currency)
@@ -541,9 +575,7 @@ def test_draft_order_update_shipping_method(
}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
# then
content = get_graphql_content(response)
@@ -573,9 +605,10 @@ def test_draft_order_update_shipping_method(
def test_draft_order_update_no_shipping_method_channel_listings(
- staff_api_client, permission_manage_orders, draft_order, shipping_method
+ staff_api_client, permission_group_manage_orders, draft_order, shipping_method
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
order.shipping_method = None
order.base_shipping_price = zero_money(order.currency)
@@ -592,9 +625,7 @@ def test_draft_order_update_no_shipping_method_channel_listings(
}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
# then
content = get_graphql_content(response)
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py b/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py
index 6529519ded..1018c84114 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py
@@ -10,7 +10,7 @@ from .....order.fetch import OrderLineInfo
from .....order.models import OrderLine
from .....plugins.manager import get_plugins_manager
from .....product.models import Product
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
APPROVE_FULFILLMENT_MUTATION = """
mutation approveFulfillment(
@@ -43,16 +43,80 @@ def test_fulfillment_approve(
mock_fulfillment_approved,
staff_api_client,
fulfillment,
+ permission_group_manage_orders,
+):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
+ fulfillment.save(update_fields=["status"])
+ query = APPROVE_FULFILLMENT_MUTATION
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
+ variables = {"id": fulfillment_id, "notifyCustomer": True}
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentApprove"]
+ assert not data["errors"]
+ assert data["fulfillment"]["status"] == FulfillmentStatus.FULFILLED.upper()
+ assert data["order"]["status"] == OrderStatus.FULFILLED.upper()
+ fulfillment.refresh_from_db()
+ assert fulfillment.status == FulfillmentStatus.FULFILLED
+
+ assert mock_email_fulfillment.call_count == 1
+ events = fulfillment.order.events.all()
+ assert len(events) == 1
+ event = events[0]
+ assert event.type == OrderEvents.FULFILLMENT_FULFILLED_ITEMS
+ assert event.user == staff_api_client.user
+ mock_fulfillment_approved.assert_called_once_with(fulfillment)
+
+
+def test_fulfillment_approve_by_user_no_channel_access(
+ staff_api_client,
+ fulfillment,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = fulfillment.order
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
+ fulfillment.save(update_fields=["status"])
+
+ query = APPROVE_FULFILLMENT_MUTATION
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
+ variables = {"id": fulfillment_id, "notifyCustomer": True}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.plugins.manager.PluginsManager.fulfillment_approved")
+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+def test_fulfillment_approve_by_app(
+ mock_email_fulfillment,
+ mock_fulfillment_approved,
+ app_api_client,
+ fulfillment,
permission_manage_orders,
):
+ # given
fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
fulfillment.save(update_fields=["status"])
query = APPROVE_FULFILLMENT_MUTATION
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
variables = {"id": fulfillment_id, "notifyCustomer": True}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_orders,)
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentApprove"]
assert not data["errors"]
@@ -66,7 +130,8 @@ def test_fulfillment_approve(
assert len(events) == 1
event = events[0]
assert event.type == OrderEvents.FULFILLMENT_FULFILLED_ITEMS
- assert event.user == staff_api_client.user
+ assert event.app == app_api_client.app
+ assert event.user is None
mock_fulfillment_approved.assert_called_once_with(fulfillment)
@@ -75,8 +140,9 @@ def test_fulfillment_approve_delete_products_before_approval_allow_stock_exceede
mock_email_fulfillment,
staff_api_client,
fulfillment,
- permission_manage_orders,
+ permission_group_manage_orders,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
fulfillment.save(update_fields=["status"])
@@ -89,9 +155,7 @@ def test_fulfillment_approve_delete_products_before_approval_allow_stock_exceede
"notifyCustomer": True,
"allowStockToBeExceeded": True,
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentApprove"]
assert not data["errors"]
@@ -115,8 +179,9 @@ def test_fulfillment_approve_delete_products_before_approval_allow_stock_exceede
mock_fulfillment_approved,
staff_api_client,
fulfillment,
- permission_manage_orders,
+ permission_group_manage_orders,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
fulfillment.save(update_fields=["status"])
@@ -129,9 +194,7 @@ def test_fulfillment_approve_delete_products_before_approval_allow_stock_exceede
"notifyCustomer": True,
"allowStockToBeExceeded": False,
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
errors = content["data"]["orderFulfillmentApprove"]["errors"]
@@ -167,10 +230,11 @@ def test_fulfillment_approve_gift_cards_created(
mock_email_fulfillment,
staff_api_client,
fulfillment,
- permission_manage_orders,
+ permission_group_manage_orders,
gift_card_shippable_order_line,
gift_card_non_shippable_order_line,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
fulfillment.save(update_fields=["status"])
@@ -206,9 +270,7 @@ def test_fulfillment_approve_gift_cards_created(
variables = {"id": fulfillment_id, "notifyCustomer": True}
assert GiftCard.objects.count() == 0
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentApprove"]
assert not data["errors"]
@@ -237,9 +299,10 @@ def test_fulfillment_approve_when_stock_is_exceeded_and_flag_enabled(
mock_email_fulfillment,
staff_api_client,
fulfillment,
- permission_manage_orders,
+ permission_group_manage_orders,
):
# make stocks exceeded
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
for stock in [line.stock for line in fulfillment.lines.all()]:
stock.quantity = -99
stock.save()
@@ -255,9 +318,7 @@ def test_fulfillment_approve_when_stock_is_exceeded_and_flag_enabled(
"notifyCustomer": True,
"allowStockToBeExceeded": True,
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentApprove"]
assert not data["errors"]
@@ -279,9 +340,10 @@ def test_fulfillment_approve_when_stock_is_exceeded_and_flag_disabled(
mock_email_fulfillment,
staff_api_client,
fulfillment,
- permission_manage_orders,
+ permission_group_manage_orders,
):
# make stocks exceeded
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
for stock in [line.stock for line in fulfillment.lines.all()]:
stock.quantity = -99
stock.save()
@@ -296,9 +358,7 @@ def test_fulfillment_approve_when_stock_is_exceeded_and_flag_disabled(
"notifyCustomer": True,
"allowStockToBeExceeded": False,
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response, ignore_errors=True)
errors = content["data"]["orderFulfillmentApprove"]["errors"]
@@ -328,9 +388,10 @@ def test_fulfillment_approve_partial_order_fulfill(
mock_fulfillment_approved,
staff_api_client,
fulfillment_awaiting_approval,
- permission_manage_orders,
+ permission_group_manage_orders,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = APPROVE_FULFILLMENT_MUTATION
order = fulfillment_awaiting_approval.order
@@ -357,9 +418,7 @@ def test_fulfillment_approve_partial_order_fulfill(
variables = {"id": fulfillment_id, "notifyCustomer": False}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
# then
content = get_graphql_content(response)
@@ -377,14 +436,13 @@ def test_fulfillment_approve_partial_order_fulfill(
def test_fulfillment_approve_invalid_status(
staff_api_client,
fulfillment,
- permission_manage_orders,
+ permission_group_manage_orders,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = APPROVE_FULFILLMENT_MUTATION
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
variables = {"id": fulfillment_id, "notifyCustomer": True}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentApprove"]
assert data["errors"][0]["code"] == OrderErrorCode.INVALID.name
@@ -394,8 +452,9 @@ def test_fulfillment_approve_order_unpaid(
staff_api_client,
fulfillment,
site_settings,
- permission_manage_orders,
+ permission_group_manage_orders,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
site_settings.fulfillment_allow_unpaid = False
site_settings.save(update_fields=["fulfillment_allow_unpaid"])
fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
@@ -403,19 +462,18 @@ def test_fulfillment_approve_order_unpaid(
query = APPROVE_FULFILLMENT_MUTATION
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
variables = {"id": fulfillment_id, "notifyCustomer": True}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentApprove"]
assert data["errors"][0]["code"] == OrderErrorCode.CANNOT_FULFILL_UNPAID_ORDER.name
def test_fulfillment_approve_preorder(
- staff_api_client, fulfillment, permission_manage_orders, site_settings
+ staff_api_client, fulfillment, permission_group_manage_orders, site_settings
):
"""Fulfillment with WAITING_FOR_APPROVAL status can not be fulfilled
if it contains variant in preorder."""
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
site_settings.fulfillment_auto_approve = False
site_settings.save(update_fields=["fulfillment_auto_approve"])
@@ -429,9 +487,7 @@ def test_fulfillment_approve_preorder(
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
variables = {"id": fulfillment_id, "notifyCustomer": False}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentApprove"]
assert data["errors"]
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_cancel.py b/saleor/graphql/order/tests/mutations/test_fulfillment_cancel.py
index 9b79c28990..966f7cfcba 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_cancel.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_cancel.py
@@ -6,7 +6,7 @@ from .....order import FulfillmentStatus, OrderEvents, OrderStatus
from .....order.error_codes import OrderErrorCode
from .....order.models import Fulfillment
from .....warehouse.models import Allocation, Stock
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
CANCEL_FULFILLMENT_MUTATION = """
mutation cancelFulfillment($id: ID!, $warehouseId: ID) {
@@ -27,15 +27,19 @@ CANCEL_FULFILLMENT_MUTATION = """
def test_cancel_fulfillment(
- staff_api_client, fulfillment, staff_user, permission_manage_orders, warehouse
+ staff_api_client, fulfillment, staff_user, permission_group_manage_orders, warehouse
):
+ # given
query = CANCEL_FULFILLMENT_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
variables = {"id": fulfillment_id, "warehouseId": warehouse_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentCancel"]
assert data["fulfillment"]["status"] == FulfillmentStatus.CANCELED.upper()
@@ -56,23 +60,90 @@ def test_cancel_fulfillment(
).exists()
+def test_cancel_fulfillment_by_user_no_channel_access(
+ staff_api_client,
+ fulfillment,
+ staff_user,
+ permission_group_all_perms_channel_USD_only,
+ warehouse,
+ channel_PLN,
+):
+ # given
+ query = CANCEL_FULFILLMENT_MUTATION
+
+ order = fulfillment.order
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ variables = {"id": fulfillment_id, "warehouseId": warehouse_id}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_cancel_fulfillment_by_app(
+ app_api_client,
+ fulfillment,
+ staff_user,
+ warehouse,
+ permission_manage_orders,
+):
+ # given
+ query = CANCEL_FULFILLMENT_MUTATION
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ variables = {"id": fulfillment_id, "warehouseId": warehouse_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentCancel"]
+ assert data["fulfillment"]["status"] == FulfillmentStatus.CANCELED.upper()
+ assert data["order"]["status"] == OrderStatus.UNFULFILLED.upper()
+ event_cancelled, event_restocked_items = fulfillment.order.events.all()
+ assert event_cancelled.type == (OrderEvents.FULFILLMENT_CANCELED)
+ assert event_cancelled.parameters == {"composed_id": fulfillment.composed_id}
+ assert event_cancelled.user is None
+ assert event_cancelled.app == app_api_client.app
+
+ assert event_restocked_items.type == (OrderEvents.FULFILLMENT_RESTOCKED_ITEMS)
+ assert event_restocked_items.parameters == {
+ "quantity": fulfillment.get_total_quantity(),
+ "warehouse": str(warehouse.pk),
+ }
+ assert event_restocked_items.user is None
+ assert event_restocked_items.app == app_api_client.app
+ assert Fulfillment.objects.filter(
+ pk=fulfillment.pk, status=FulfillmentStatus.CANCELED
+ ).exists()
+
+
def test_cancel_fulfillment_for_order_with_gift_card_lines(
staff_api_client,
fulfillment,
gift_card_shippable_order_line,
staff_user,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
):
query = CANCEL_FULFILLMENT_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = gift_card_shippable_order_line.order
order_fulfillment = order.fulfillments.first()
fulfillment_id = graphene.Node.to_global_id("Fulfillment", order_fulfillment.id)
warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
variables = {"id": fulfillment_id, "warehouseId": warehouse_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentCancel"]
assert not data["fulfillment"]
@@ -82,7 +153,7 @@ def test_cancel_fulfillment_for_order_with_gift_card_lines(
def test_cancel_fulfillment_no_warehouse_id(
- staff_api_client, fulfillment, permission_manage_orders
+ staff_api_client, fulfillment, permission_group_manage_orders
):
query = """
mutation cancelFulfillment($id: ID!) {
@@ -100,11 +171,10 @@ def test_cancel_fulfillment_no_warehouse_id(
}
}
"""
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
variables = {"id": fulfillment_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
errors = content["data"]["orderFulfillmentCancel"]["errors"]
assert len(errors) == 1
@@ -115,16 +185,15 @@ def test_cancel_fulfillment_no_warehouse_id(
@patch("saleor.order.actions.restock_fulfillment_lines")
def test_cancel_fulfillment_awaiting_approval(
- mock_restock_lines, staff_api_client, fulfillment, permission_manage_orders
+ mock_restock_lines, staff_api_client, fulfillment, permission_group_manage_orders
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
fulfillment.save(update_fields=["status"])
query = CANCEL_FULFILLMENT_MUTATION
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
variables = {"id": fulfillment_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentCancel"]
assert data["fulfillment"] is None
@@ -141,18 +210,17 @@ def test_cancel_fulfillment_awaiting_approval_warehouse_specified(
mock_restock_lines,
staff_api_client,
fulfillment,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
fulfillment.save(update_fields=["status"])
query = CANCEL_FULFILLMENT_MUTATION
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
variables = {"id": fulfillment_id, "warehouseId": warehouse_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentCancel"]
assert data["fulfillment"] is None
@@ -165,17 +233,16 @@ def test_cancel_fulfillment_awaiting_approval_warehouse_specified(
def test_cancel_fulfillment_canceled_state(
- staff_api_client, fulfillment, permission_manage_orders, warehouse
+ staff_api_client, fulfillment, permission_group_manage_orders, warehouse
):
query = CANCEL_FULFILLMENT_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
fulfillment.status = FulfillmentStatus.CANCELED
fulfillment.save(update_fields=["status"])
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
variables = {"id": fulfillment_id, "warehouseId": warehouse_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
errors = content["data"]["orderFulfillmentCancel"]["errors"]
assert len(errors) == 1
@@ -185,9 +252,10 @@ def test_cancel_fulfillment_canceled_state(
def test_cancel_fulfillment_warehouse_without_stock(
- order_line, warehouse, staff_api_client, permission_manage_orders, staff_user
+ order_line, warehouse, staff_api_client, permission_group_manage_orders, staff_user
):
query = CANCEL_FULFILLMENT_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_line.order
fulfillment = order.fulfillments.create(tracking_number="123")
fulfillment.lines.create(order_line=order_line, quantity=order_line.quantity)
@@ -202,9 +270,7 @@ def test_cancel_fulfillment_warehouse_without_stock(
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
variables = {"id": fulfillment_id, "warehouseId": warehouse_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentCancel"]["fulfillment"]
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py b/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
index 3cfd0c866e..9b4baa32ae 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
@@ -14,7 +14,8 @@ from .....payment import ChargeStatus, PaymentError
from .....payment.interface import RefundData
from .....tests.utils import flush_post_commit_hooks
from .....warehouse.models import Allocation, Stock
-from ....tests.utils import get_graphql_content
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import assert_no_permission, get_graphql_content
ORDER_FULFILL_REFUND_MUTATION = """
mutation OrderFulfillmentRefundProducts(
@@ -47,13 +48,92 @@ mutation OrderFulfillmentRefundProducts(
"""
+def test_fulfillment_refund_products_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ order_with_lines,
+ channel_PLN,
+ payment_dummy,
+):
+ # given
+ order_with_lines.channel = channel_PLN
+ order_with_lines.save(update_fields=["channel"])
+
+ payment_dummy.total = order_with_lines.total_gross_amount
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ order_with_lines.payments.add(payment_dummy)
+
+ order_id = to_global_id_or_none(order_with_lines)
+ amount_to_refund = Decimal("11.00")
+ variables = {
+ "order": order_id,
+ "input": {"amountToRefund": amount_to_refund, "includeShippingCosts": True},
+ }
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_fulfillment_refund_products_with_transaction_action_request_by_app(
+ mocked_refund,
+ app_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+ payment_dummy,
+):
+ # given
+ payment_dummy.total = fulfilled_order.total_gross_amount
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ fulfilled_order.payments.add(payment_dummy)
+
+ order_id = to_global_id_or_none(fulfilled_order)
+ amount_to_refund = Decimal("11.00")
+ variables = {
+ "order": order_id,
+ "input": {"amountToRefund": amount_to_refund, "includeShippingCosts": True},
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ ORDER_FULFILL_REFUND_MUTATION,
+ variables,
+ permissions=(permission_manage_orders,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentRefundProducts"]
+ errors = data["errors"]
+ assert not errors
+
+ mocked_refund.assert_called_with(
+ payment_dummy,
+ ANY,
+ amount=quantize_price(amount_to_refund, fulfilled_order.currency),
+ channel_slug=fulfilled_order.channel.slug,
+ refund_data=RefundData(
+ refund_shipping_costs=True,
+ refund_amount_is_automatically_calculated=False,
+ ),
+ )
+
+
@patch("saleor.order.actions.gateway.refund")
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
def test_fulfillment_refund_products_with_back_in_stock_webhook(
back_in_stock_webhook_trigger,
mock_refunded,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
payment_dummy,
):
@@ -70,7 +150,7 @@ def test_fulfillment_refund_products_with_back_in_stock_webhook(
"order": order_id,
"input": {"orderLines": [{"orderLineId": line_id, "quantity": 1}]},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentRefundProducts"]
@@ -83,7 +163,7 @@ def test_fulfillment_refund_products_with_back_in_stock_webhook(
def test_fulfillment_refund_gift_card_products(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
payment_dummy,
):
@@ -107,7 +187,7 @@ def test_fulfillment_refund_gift_card_products(
}
# when
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# then
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
@@ -122,11 +202,11 @@ def test_fulfillment_refund_gift_card_products(
def test_fulfillment_refund_products_order_without_payment(
- staff_api_client, permission_manage_orders, fulfilled_order
+ staff_api_client, permission_group_manage_orders, fulfilled_order
):
order_id = graphene.Node.to_global_id("Order", fulfilled_order.pk)
variables = {"order": order_id, "input": {"amountToRefund": "11.00"}}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentRefundProducts"]
@@ -142,7 +222,7 @@ def test_fulfillment_refund_products_order_without_payment(
def test_fulfillment_refund_products_amount_and_shipping_costs(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -156,7 +236,7 @@ def test_fulfillment_refund_products_amount_and_shipping_costs(
"order": order_id,
"input": {"amountToRefund": amount_to_refund, "includeShippingCosts": True},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
mocked_refund.assert_called_with(
@@ -173,7 +253,7 @@ def test_fulfillment_refund_products_amount_and_shipping_costs(
def test_fulfillment_refund_products_amount_costs_for_order_with_gift_card_lines(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -193,7 +273,7 @@ def test_fulfillment_refund_products_amount_costs_for_order_with_gift_card_lines
"order": order_id,
"input": {"amountToRefund": amount_to_refund, "includeShippingCosts": True},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
@@ -211,7 +291,7 @@ def test_fulfillment_refund_products_amount_costs_for_order_with_gift_card_lines
def test_fulfillment_refund_products_refund_raising_payment_error(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -228,7 +308,7 @@ def test_fulfillment_refund_products_refund_raising_payment_error(
"order": order_id,
"input": {"amountToRefund": amount_to_refund, "includeShippingCosts": True},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
@@ -245,7 +325,7 @@ def test_fulfillment_refund_products_refund_raising_payment_error(
def test_fulfillment_refund_products_order_lines(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
payment_dummy,
):
@@ -261,7 +341,7 @@ def test_fulfillment_refund_products_order_lines(
"order": order_id,
"input": {"orderLines": [{"orderLineId": line_id, "quantity": 2}]},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentRefundProducts"]
@@ -290,7 +370,7 @@ def test_fulfillment_refund_products_order_lines(
def test_fulfillment_refund_products_order_lines_quantity_bigger_than_total(
- staff_api_client, permission_manage_orders, order_with_lines, payment_dummy
+ staff_api_client, permission_group_manage_orders, order_with_lines, payment_dummy
):
payment_dummy.total = order_with_lines.total_gross_amount
payment_dummy.captured_amount = payment_dummy.total
@@ -304,7 +384,7 @@ def test_fulfillment_refund_products_order_lines_quantity_bigger_than_total(
"order": order_id,
"input": {"orderLines": [{"orderLineId": line_id, "quantity": 200}]},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentRefundProducts"]
@@ -318,7 +398,7 @@ def test_fulfillment_refund_products_order_lines_quantity_bigger_than_total(
def test_fulfillment_refund_products_order_lines_quantity_bigger_than_unfulfilled(
- staff_api_client, permission_manage_orders, order_with_lines, payment_dummy
+ staff_api_client, permission_group_manage_orders, order_with_lines, payment_dummy
):
payment_dummy.total = order_with_lines.total_gross_amount
payment_dummy.captured_amount = payment_dummy.total
@@ -335,7 +415,7 @@ def test_fulfillment_refund_products_order_lines_quantity_bigger_than_unfulfille
"order": order_id,
"input": {"orderLines": [{"orderLineId": line_id, "quantity": 1}]},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentRefundProducts"]
@@ -352,7 +432,7 @@ def test_fulfillment_refund_products_order_lines_quantity_bigger_than_unfulfille
def test_fulfillment_refund_products_fulfillment_lines(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -377,7 +457,7 @@ def test_fulfillment_refund_products_fulfillment_lines(
]
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentRefundProducts"]
@@ -409,7 +489,7 @@ def test_fulfillment_refund_products_fulfillment_lines(
def test_fulfillment_refund_products_waiting_fulfillment_lines(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -439,7 +519,7 @@ def test_fulfillment_refund_products_waiting_fulfillment_lines(
]
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentRefundProducts"]
@@ -469,7 +549,7 @@ def test_fulfillment_refund_products_waiting_fulfillment_lines(
def test_fulfillment_refund_products_gift_card_fulfillment_line(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -496,7 +576,7 @@ def test_fulfillment_refund_products_gift_card_fulfillment_line(
]
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentRefundProducts"]
@@ -510,7 +590,7 @@ def test_fulfillment_refund_products_gift_card_fulfillment_line(
def test_fulfillment_refund_products_fulfillment_lines_quantity_bigger_than_total(
- staff_api_client, permission_manage_orders, fulfilled_order, payment_dummy
+ staff_api_client, permission_group_manage_orders, fulfilled_order, payment_dummy
):
payment_dummy.total = fulfilled_order.total_gross_amount
payment_dummy.captured_amount = payment_dummy.total
@@ -530,7 +610,7 @@ def test_fulfillment_refund_products_fulfillment_lines_quantity_bigger_than_tota
]
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentRefundProducts"]
@@ -544,7 +624,7 @@ def test_fulfillment_refund_products_fulfillment_lines_quantity_bigger_than_tota
def test_fulfillment_refund_products_amount_bigger_than_captured_amount(
- staff_api_client, permission_manage_orders, fulfilled_order, payment_dummy
+ staff_api_client, permission_group_manage_orders, fulfilled_order, payment_dummy
):
payment_dummy.total = fulfilled_order.total_gross_amount
payment_dummy.captured_amount = payment_dummy.total
@@ -565,7 +645,7 @@ def test_fulfillment_refund_products_amount_bigger_than_captured_amount(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentRefundProducts"]
@@ -582,7 +662,7 @@ def test_fulfillment_refund_products_amount_bigger_than_captured_amount(
def test_fulfillment_refund_products_fulfillment_lines_include_shipping_costs(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -608,7 +688,7 @@ def test_fulfillment_refund_products_fulfillment_lines_include_shipping_costs(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentRefundProducts"]
@@ -640,7 +720,7 @@ def test_fulfillment_refund_products_fulfillment_lines_include_shipping_costs(
def test_fulfillment_refund_products_order_lines_include_shipping_costs(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
payment_dummy,
):
@@ -659,7 +739,7 @@ def test_fulfillment_refund_products_order_lines_include_shipping_costs(
"orderLines": [{"orderLineId": line_id, "quantity": 2}],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentRefundProducts"]
@@ -692,7 +772,7 @@ def test_fulfillment_refund_products_order_lines_include_shipping_costs(
def test_fulfillment_refund_products_fulfillment_lines_custom_amount(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -719,7 +799,7 @@ def test_fulfillment_refund_products_fulfillment_lines_custom_amount(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentRefundProducts"]
@@ -752,7 +832,7 @@ def test_fulfillment_refund_products_fulfillment_lines_custom_amount(
def test_fulfillment_refund_products_order_lines_custom_amount(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
payment_dummy,
):
@@ -772,7 +852,7 @@ def test_fulfillment_refund_products_order_lines_custom_amount(
"orderLines": [{"orderLineId": line_id, "quantity": 2}],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentRefundProducts"]
@@ -806,7 +886,7 @@ def test_fulfillment_refund_products_fulfillment_lines_and_order_lines(
variant,
channel_USD,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -859,7 +939,7 @@ def test_fulfillment_refund_products_fulfillment_lines_and_order_lines(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
@@ -913,7 +993,7 @@ def test_fulfillment_refund_products_calls_order_refunded(
variant,
channel_USD,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -965,7 +1045,7 @@ def test_fulfillment_refund_products_calls_order_refunded(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
index f5f77e0929..5cec6da036 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
@@ -14,7 +14,8 @@ from .....payment import ChargeStatus, PaymentError
from .....payment.interface import RefundData
from .....tests.utils import flush_post_commit_hooks
from .....warehouse.models import Stock
-from ....tests.utils import get_graphql_content
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import assert_no_permission, get_graphql_content
ORDER_FULFILL_RETURN_MUTATION = """
mutation OrderFulfillmentReturnProducts(
@@ -68,15 +69,100 @@ mutation OrderFulfillmentReturnProducts(
"""
+def test_fulfillment_return_products_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ fulfilled_order,
+ channel_PLN,
+ payment_dummy,
+):
+ # given
+ fulfilled_order.channel = channel_PLN
+ fulfilled_order.save(update_fields=["channel"])
+
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ fulfilled_order.payments.add(payment_dummy)
+
+ order_id = to_global_id_or_none(fulfilled_order)
+ amount_to_refund = Decimal("11.00")
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "amountToRefund": amount_to_refund,
+ "includeShippingCosts": True,
+ },
+ }
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_fulfillment_return_products_by_app(
+ mocked_refund,
+ app_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+ payment_dummy,
+):
+ # given
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ fulfilled_order.payments.add(payment_dummy)
+
+ order_id = to_global_id_or_none(fulfilled_order)
+ amount_to_refund = Decimal("11.00")
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "amountToRefund": amount_to_refund,
+ "includeShippingCosts": True,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ ORDER_FULFILL_RETURN_MUTATION,
+ variables,
+ permissions=(permission_manage_orders,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ errors = data["errors"]
+ assert not errors
+
+ mocked_refund.assert_called_with(
+ payment_dummy,
+ ANY,
+ amount=quantize_price(amount_to_refund, fulfilled_order.currency),
+ channel_slug=fulfilled_order.channel.slug,
+ refund_data=RefundData(
+ refund_shipping_costs=True,
+ refund_amount_is_automatically_calculated=False,
+ ),
+ )
+
+
def test_fulfillment_return_products_order_without_payment(
- staff_api_client, permission_manage_orders, fulfilled_order
+ staff_api_client, permission_group_manage_orders, fulfilled_order
):
order_id = graphene.Node.to_global_id("Order", fulfilled_order.pk)
variables = {
"order": order_id,
"input": {"refund": True, "amountToRefund": "11.00"},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentReturnProducts"]
@@ -92,7 +178,7 @@ def test_fulfillment_return_products_order_without_payment(
def test_fulfillment_return_products_amount_and_shipping_costs(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -110,7 +196,7 @@ def test_fulfillment_return_products_amount_and_shipping_costs(
"includeShippingCosts": True,
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
mocked_refund.assert_called_with(
@@ -127,7 +213,7 @@ def test_fulfillment_return_products_amount_and_shipping_costs(
def test_fulfillment_return_products_amount_order_with_gift_card(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -151,7 +237,7 @@ def test_fulfillment_return_products_amount_order_with_gift_card(
"includeShippingCosts": True,
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
@@ -171,7 +257,7 @@ def test_fulfillment_return_products_amount_order_with_gift_card(
def test_fulfillment_return_products_refund_raising_payment_error(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -191,7 +277,7 @@ def test_fulfillment_return_products_refund_raising_payment_error(
"includeShippingCosts": True,
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
content = get_graphql_content(response)
@@ -205,7 +291,7 @@ def test_fulfillment_return_products_refund_raising_payment_error(
def test_fulfillment_return_products_order_lines(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
payment_dummy,
):
@@ -244,7 +330,7 @@ def test_fulfillment_return_products_order_lines(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
order_with_lines.refresh_from_db()
@@ -326,7 +412,7 @@ def test_fulfillment_return_products_order_lines(
def test_fulfillment_return_products_gift_card_order_line(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
payment_dummy,
):
@@ -358,7 +444,7 @@ def test_fulfillment_return_products_gift_card_order_line(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
@@ -375,7 +461,7 @@ def test_fulfillment_return_products_gift_card_order_line(
def test_fulfillment_return_products_order_lines_quantity_bigger_than_total(
- staff_api_client, permission_manage_orders, order_with_lines, payment_dummy
+ staff_api_client, permission_group_manage_orders, order_with_lines, payment_dummy
):
payment_dummy.total = order_with_lines.total_gross_amount
payment_dummy.captured_amount = payment_dummy.total
@@ -391,7 +477,7 @@ def test_fulfillment_return_products_order_lines_quantity_bigger_than_total(
"orderLines": [{"orderLineId": line_id, "quantity": 200, "replace": False}]
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentReturnProducts"]
@@ -405,7 +491,7 @@ def test_fulfillment_return_products_order_lines_quantity_bigger_than_total(
def test_fulfillment_return_products_order_lines_quantity_bigger_than_unfulfilled(
- staff_api_client, permission_manage_orders, order_with_lines, payment_dummy
+ staff_api_client, permission_group_manage_orders, order_with_lines, payment_dummy
):
payment_dummy.total = order_with_lines.total_gross_amount
payment_dummy.captured_amount = payment_dummy.total
@@ -422,7 +508,7 @@ def test_fulfillment_return_products_order_lines_quantity_bigger_than_unfulfille
"order": order_id,
"input": {"orderLines": [{"orderLineId": line_id, "quantity": 1}]},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentReturnProducts"]
@@ -439,7 +525,7 @@ def test_fulfillment_return_products_order_lines_quantity_bigger_than_unfulfille
def test_fulfillment_return_products_order_lines_custom_amount(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
payment_dummy,
):
@@ -460,7 +546,7 @@ def test_fulfillment_return_products_order_lines_custom_amount(
"orderLines": [{"orderLineId": line_id, "quantity": 2, "replace": False}],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentReturnProducts"]
@@ -495,7 +581,7 @@ def test_fulfillment_return_products_order_lines_custom_amount(
def test_fulfillment_return_products_fulfillment_lines(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -542,7 +628,7 @@ def test_fulfillment_return_products_fulfillment_lines(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
fulfilled_order.refresh_from_db()
@@ -629,7 +715,7 @@ def test_fulfillment_return_products_fulfillment_lines(
def test_fulfillment_return_products_gift_card_fulfillment_line(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -666,7 +752,7 @@ def test_fulfillment_return_products_gift_card_fulfillment_line(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
@@ -683,7 +769,7 @@ def test_fulfillment_return_products_gift_card_fulfillment_line(
def test_fulfillment_return_products_fulfillment_lines_quantity_bigger_than_total(
- staff_api_client, permission_manage_orders, fulfilled_order, payment_dummy
+ staff_api_client, permission_group_manage_orders, fulfilled_order, payment_dummy
):
payment_dummy.total = fulfilled_order.total_gross_amount
payment_dummy.captured_amount = payment_dummy.total
@@ -704,7 +790,7 @@ def test_fulfillment_return_products_fulfillment_lines_quantity_bigger_than_tota
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentReturnProducts"]
@@ -718,7 +804,7 @@ def test_fulfillment_return_products_fulfillment_lines_quantity_bigger_than_tota
def test_fulfillment_return_products_amount_bigger_than_captured_amount(
- staff_api_client, permission_manage_orders, fulfilled_order, payment_dummy
+ staff_api_client, permission_group_manage_orders, fulfilled_order, payment_dummy
):
payment_dummy.total = fulfilled_order.total_gross_amount
payment_dummy.captured_amount = payment_dummy.total
@@ -740,7 +826,7 @@ def test_fulfillment_return_products_amount_bigger_than_captured_amount(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentReturnProducts"]
@@ -754,7 +840,7 @@ def test_fulfillment_return_products_amount_bigger_than_captured_amount(
def test_fulfillment_return_products_lines_with_incorrect_status(
- staff_api_client, permission_manage_orders, fulfilled_order, payment_dummy
+ staff_api_client, permission_group_manage_orders, fulfilled_order, payment_dummy
):
payment_dummy.total = fulfilled_order.total_gross_amount
payment_dummy.captured_amount = payment_dummy.total
@@ -779,7 +865,7 @@ def test_fulfillment_return_products_lines_with_incorrect_status(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentReturnProducts"]
@@ -796,7 +882,7 @@ def test_fulfillment_return_products_lines_with_incorrect_status(
def test_fulfillment_return_products_fulfillment_lines_include_shipping_costs(
mocked_refund,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -823,7 +909,7 @@ def test_fulfillment_return_products_fulfillment_lines_include_shipping_costs(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentReturnProducts"]
@@ -860,7 +946,7 @@ def test_fulfillment_return_products_fulfillment_lines_and_order_lines(
variant,
channel_USD,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -917,7 +1003,7 @@ def test_fulfillment_return_products_fulfillment_lines_and_order_lines(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
@@ -982,7 +1068,7 @@ def test_fulfillment_return_products_calls_order_refunded(
variant,
channel_USD,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
payment_dummy,
):
@@ -1040,7 +1126,7 @@ def test_fulfillment_return_products_calls_order_refunded(
],
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_update_tracking.py b/saleor/graphql/order/tests/mutations/test_fulfillment_update_tracking.py
index 6fac89e3c3..04cf401e3b 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_update_tracking.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_update_tracking.py
@@ -2,7 +2,7 @@ from unittest.mock import ANY, patch
import graphene
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
FULFILLMENT_UPDATE_TRACKING_QUERY = """
mutation updateFulfillment(
@@ -27,15 +27,63 @@ def test_fulfillment_update_tracking(
send_fulfillment_update_mock,
staff_api_client,
fulfillment,
- permission_manage_orders,
+ permission_group_manage_orders,
):
query = FULFILLMENT_UPDATE_TRACKING_QUERY
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
tracking = "stationary tracking"
variables = {"id": fulfillment_id, "tracking": tracking}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentUpdateTracking"]["fulfillment"]
+ assert data["trackingNumber"] == tracking
+ send_fulfillment_update_mock.assert_not_called()
+
+
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_fulfillment_update_tracking_by_user_no_channel_access(
+ send_fulfillment_update_mock,
+ staff_api_client,
+ fulfillment,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+):
+ # given
+ query = FULFILLMENT_UPDATE_TRACKING_QUERY
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ order = fulfillment.order
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
+ tracking = "stationary tracking"
+ variables = {"id": fulfillment_id, "tracking": tracking}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.plugins.manager.PluginsManager.notify")
+def test_fulfillment_update_tracking_by_app(
+ send_fulfillment_update_mock, app_api_client, fulfillment, permission_manage_orders
+):
+ # given
+ query = FULFILLMENT_UPDATE_TRACKING_QUERY
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
+ tracking = "stationary tracking"
+ variables = {"id": fulfillment_id, "tracking": tracking}
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_orders,)
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentUpdateTracking"]["fulfillment"]
assert data["trackingNumber"] == tracking
@@ -49,15 +97,15 @@ def test_fulfillment_update_tracking_send_notification_true(
send_fulfillment_update_mock,
staff_api_client,
fulfillment,
- permission_manage_orders,
+ permission_group_manage_orders,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
tracking = "stationary tracking"
variables = {"id": fulfillment_id, "tracking": tracking, "notifyCustomer": True}
response = staff_api_client.post_graphql(
FULFILLMENT_UPDATE_TRACKING_QUERY,
variables,
- permissions=[permission_manage_orders],
)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentUpdateTracking"]["fulfillment"]
@@ -72,15 +120,15 @@ def test_fulfillment_update_tracking_send_notification_false(
send_fulfillment_update_mock,
staff_api_client,
fulfillment,
- permission_manage_orders,
+ permission_group_manage_orders,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
tracking = "stationary tracking"
variables = {"id": fulfillment_id, "tracking": tracking, "notifyCustomer": False}
response = staff_api_client.post_graphql(
FULFILLMENT_UPDATE_TRACKING_QUERY,
variables,
- permissions=[permission_manage_orders],
)
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentUpdateTracking"]["fulfillment"]
diff --git a/saleor/graphql/order/tests/mutations/test_order_add_note.py b/saleor/graphql/order/tests/mutations/test_order_add_note.py
index afa6f0e043..529fb6912c 100644
--- a/saleor/graphql/order/tests/mutations/test_order_add_note.py
+++ b/saleor/graphql/order/tests/mutations/test_order_add_note.py
@@ -7,7 +7,7 @@ from .....account.models import CustomerEvent
from .....order import OrderStatus
from .....order import events as order_events
from .....order.error_codes import OrderErrorCode
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
ORDER_ADD_NOTE_MUTATION = """
mutation addNote($id: ID!, $message: String!) {
@@ -24,6 +24,9 @@ ORDER_ADD_NOTE_MUTATION = """
user {
email
}
+ app {
+ name
+ }
message
}
}
@@ -35,20 +38,19 @@ ORDER_ADD_NOTE_MUTATION = """
def test_order_add_note_as_staff_user(
order_updated_webhook_mock,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
staff_user,
):
"""We are testing that adding a note to an order as a staff user is doing the
expected behaviors."""
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
assert not order.events.all()
order_id = graphene.Node.to_global_id("Order", order.id)
message = "nuclear note"
variables = {"id": order_id, "message": message}
- response = staff_api_client.post_graphql(
- ORDER_ADD_NOTE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(ORDER_ADD_NOTE_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderAddNote"]
@@ -81,17 +83,70 @@ def test_order_add_note_as_staff_user(
def test_order_add_note_fail_on_empty_message(
order_updated_webhook_mock,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
message,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order_with_lines.id)
variables = {"id": order_id, "message": message}
- response = staff_api_client.post_graphql(
- ORDER_ADD_NOTE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(ORDER_ADD_NOTE_MUTATION, variables)
content = get_graphql_content(response)
data = content["data"]["orderAddNote"]
assert data["errors"][0]["field"] == "message"
assert data["errors"][0]["code"] == OrderErrorCode.REQUIRED.name
order_updated_webhook_mock.assert_not_called()
+
+
+def test_order_add_note_as_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ order_with_lines,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ order = order_with_lines
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ message = "nuclear note"
+ variables = {"id": order_id, "message": message}
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_ADD_NOTE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+def test_order_add_note_by_app(
+ order_updated_webhook_mock,
+ app_api_client,
+ permission_manage_orders,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ assert not order.events.all()
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ message = "nuclear note"
+ variables = {"id": order_id, "message": message}
+
+ # when
+ response = app_api_client.post_graphql(
+ ORDER_ADD_NOTE_MUTATION, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderAddNote"]
+
+ assert data["order"]["id"] == order_id
+ assert data["event"]["user"] is None
+ assert data["event"]["app"]["name"] == app_api_client.app.name
+ assert data["event"]["message"] == message
+ order_updated_webhook_mock.assert_called_once_with(order)
diff --git a/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py b/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py
index bfabe409a8..7073f47b7a 100644
--- a/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py
+++ b/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py
@@ -4,7 +4,7 @@ import graphene
from .....order.models import OrderLine
from .....product.models import ProductVariant
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
MUTATION_ORDER_BULK_CANCEL = """
mutation CancelManyOrders($ids: [ID!]!) {
@@ -25,18 +25,17 @@ def test_order_bulk_cancel(
staff_api_client,
order_list,
fulfilled_order_with_all_cancelled_fulfillments,
- permission_manage_orders,
+ permission_group_manage_orders,
address,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
orders = order_list
orders.append(fulfilled_order_with_all_cancelled_fulfillments)
expected_count = sum(order.can_cancel() for order in orders)
variables = {
"ids": [graphene.Node.to_global_id("Order", order.id) for order in orders],
}
- response = staff_api_client.post_graphql(
- MUTATION_ORDER_BULK_CANCEL, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(MUTATION_ORDER_BULK_CANCEL, variables)
content = get_graphql_content(response)
data = content["data"]["orderBulkCancel"]
assert data["count"] == expected_count
@@ -51,13 +50,40 @@ def test_order_bulk_cancel(
mock_cancel_order.call_count == expected_count
+def test_order_bulk_cancel_by_user_no_channel_access(
+ staff_api_client,
+ order_list,
+ fulfilled_order_with_all_cancelled_fulfillments,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ orders = order_list
+ order_in_PLN = orders[0]
+ order_in_PLN.channel = channel_PLN
+ order_in_PLN.save(update_fields=["channel"])
+
+ orders.append(fulfilled_order_with_all_cancelled_fulfillments)
+ variables = {
+ "ids": [graphene.Node.to_global_id("Order", order.id) for order in orders],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(MUTATION_ORDER_BULK_CANCEL, variables)
+
+ # then
+ assert_no_permission(response)
+
+
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
def test_order_bulk_cancel_with_back_in_stock_webhook(
product_variant_back_in_stock_webhook_mock,
staff_api_client,
fulfilled_order_with_all_cancelled_fulfillments,
- permission_manage_orders,
+ permission_group_manage_orders,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"ids": [
graphene.Node.to_global_id(
@@ -65,9 +91,7 @@ def test_order_bulk_cancel_with_back_in_stock_webhook(
)
]
}
- staff_api_client.post_graphql(
- MUTATION_ORDER_BULK_CANCEL, variables, permissions=[permission_manage_orders]
- )
+ staff_api_client.post_graphql(MUTATION_ORDER_BULK_CANCEL, variables)
product_variant_back_in_stock_webhook_mock.assert_called_once()
@@ -88,7 +112,7 @@ def test_order_bulk_cancel_as_app(
"ids": [graphene.Node.to_global_id("Order", order.id) for order in orders],
}
response = app_api_client.post_graphql(
- MUTATION_ORDER_BULK_CANCEL, variables, permissions=[permission_manage_orders]
+ MUTATION_ORDER_BULK_CANCEL, variables, permissions=(permission_manage_orders,)
)
content = get_graphql_content(response)
data = content["data"]["orderBulkCancel"]
@@ -110,9 +134,10 @@ def test_order_bulk_cancel_without_sku(
staff_api_client,
order_list,
fulfilled_order_with_all_cancelled_fulfillments,
- permission_manage_orders,
+ permission_group_manage_orders,
address,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
ProductVariant.objects.update(sku=None)
OrderLine.objects.update(product_sku=None)
@@ -122,9 +147,7 @@ def test_order_bulk_cancel_without_sku(
variables = {
"ids": [graphene.Node.to_global_id("Order", order.id) for order in orders],
}
- response = staff_api_client.post_graphql(
- MUTATION_ORDER_BULK_CANCEL, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(MUTATION_ORDER_BULK_CANCEL, variables)
content = get_graphql_content(response)
data = content["data"]["orderBulkCancel"]
assert data["count"] == expected_count
diff --git a/saleor/graphql/order/tests/mutations/test_order_cancel.py b/saleor/graphql/order/tests/mutations/test_order_cancel.py
index 15f6f9997a..05028700cd 100644
--- a/saleor/graphql/order/tests/mutations/test_order_cancel.py
+++ b/saleor/graphql/order/tests/mutations/test_order_cancel.py
@@ -4,7 +4,7 @@ import graphene
from .....giftcard import GiftCardEvents
from .....giftcard.events import gift_cards_bought_event
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
MUTATION_ORDER_CANCEL = """
mutation cancelOrder($id: ID!) {
@@ -28,16 +28,15 @@ def test_order_cancel(
mock_clean_order_cancel,
mock_cancel_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
mock_clean_order_cancel.return_value = order
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- MUTATION_ORDER_CANCEL, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(MUTATION_ORDER_CANCEL, variables)
content = get_graphql_content(response)
data = content["data"]["orderCancel"]
assert not data["errors"]
@@ -80,19 +79,18 @@ def test_order_cancel_with_bought_gift_cards(
mock_clean_order_cancel,
mock_cancel_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
gift_card,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
mock_clean_order_cancel.return_value = order
gift_cards_bought_event([gift_card], order, staff_api_client.user, None)
assert gift_card.is_active is True
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- MUTATION_ORDER_CANCEL, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(MUTATION_ORDER_CANCEL, variables)
content = get_graphql_content(response)
data = content["data"]["orderCancel"]
assert not data["errors"]
@@ -105,3 +103,25 @@ def test_order_cancel_with_bought_gift_cards(
gift_card.refresh_from_db()
assert gift_card.is_active is False
assert gift_card.events.filter(type=GiftCardEvents.DEACTIVATED)
+
+
+def test_order_cancel_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ order_with_lines,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = order_with_lines
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(MUTATION_ORDER_CANCEL, variables)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/order/tests/mutations/test_order_capture.py b/saleor/graphql/order/tests/mutations/test_order_capture.py
index a859c143c6..ce3b3aadc7 100644
--- a/saleor/graphql/order/tests/mutations/test_order_capture.py
+++ b/saleor/graphql/order/tests/mutations/test_order_capture.py
@@ -9,7 +9,7 @@ from .....order.notifications import get_default_order_payload
from .....payment import ChargeStatus
from .....payment.models import Payment
from ....payment.types import PaymentChargeStatusEnum
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
ORDER_CAPTURE_MUTATION = """
mutation captureOrder($id: ID!, $amount: PositiveDecimal!) {
@@ -41,12 +41,13 @@ def test_order_capture(
mocked_notify,
fulfill_non_shippable_gift_cards_mock,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
payment_txn_preauth,
staff_user,
site_settings,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = payment_txn_preauth.order
order_id = graphene.Node.to_global_id("Order", order.id)
@@ -54,9 +55,7 @@ def test_order_capture(
variables = {"id": order_id, "amount": amount}
# when
- response = staff_api_client.post_graphql(
- ORDER_CAPTURE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(ORDER_CAPTURE_MUTATION, variables)
# then
content = get_graphql_content(response)
@@ -105,3 +104,54 @@ def test_order_capture(
fulfill_non_shippable_gift_cards_mock.assert_called_once_with(
order, list(order.lines.all()), site_settings, staff_api_client.user, None, ANY
)
+
+
+def test_order_capture_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ payment_txn_preauth,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = payment_txn_preauth.order
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ amount = float(payment_txn_preauth.total)
+ variables = {"id": order_id, "amount": amount}
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_CAPTURE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_order_capture_by_app(
+ app_api_client,
+ payment_txn_preauth,
+ permission_manage_orders,
+):
+ # given
+ order = payment_txn_preauth.order
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ amount = float(payment_txn_preauth.total)
+ variables = {"id": order_id, "amount": amount}
+
+ # when
+ response = app_api_client.post_graphql(
+ ORDER_CAPTURE_MUTATION, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderCapture"]["order"]
+ order.refresh_from_db()
+ assert data["paymentStatus"] == PaymentChargeStatusEnum.FULLY_CHARGED.name
+ payment_status_display = dict(ChargeStatus.CHOICES).get(ChargeStatus.FULLY_CHARGED)
+ assert data["paymentStatusDisplay"] == payment_status_display
+ assert data["isPaid"]
+ assert data["totalCaptured"]["amount"] == float(amount)
diff --git a/saleor/graphql/order/tests/mutations/test_order_confirm.py b/saleor/graphql/order/tests/mutations/test_order_confirm.py
index b691051344..166d575505 100644
--- a/saleor/graphql/order/tests/mutations/test_order_confirm.py
+++ b/saleor/graphql/order/tests/mutations/test_order_confirm.py
@@ -13,7 +13,7 @@ from .....order.notifications import get_default_order_payload
from .....order.utils import updates_amounts_for_order
from .....product.models import ProductVariant
from ....core.utils import to_global_id_or_none
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
ORDER_CONFIRM_MUTATION = """
mutation orderConfirm($id: ID!) {
@@ -39,7 +39,7 @@ def test_order_confirm(
handle_fully_paid_order_mock,
staff_api_client,
order_unconfirmed,
- permission_manage_orders,
+ permission_group_manage_orders,
payment_txn_preauth,
site_settings,
):
@@ -53,7 +53,7 @@ def test_order_confirm(
order_unconfirmed.save(update_fields=["total_charged_amount"])
updates_amounts_for_order(order_unconfirmed)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
assert not OrderEvent.objects.exists()
# when
@@ -110,7 +110,7 @@ def test_order_confirm_without_sku(
mocked_notify,
staff_api_client,
order_unconfirmed,
- permission_manage_orders,
+ permission_group_manage_orders,
payment_txn_preauth,
site_settings,
):
@@ -119,7 +119,7 @@ def test_order_confirm_without_sku(
payment_txn_preauth.order = order_unconfirmed
payment_txn_preauth.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
assert not OrderEvent.objects.exists()
response = staff_api_client.post_graphql(
ORDER_CONFIRM_MUTATION,
@@ -161,8 +161,10 @@ def test_order_confirm_without_sku(
)
-def test_order_confirm_unfulfilled(staff_api_client, order, permission_manage_orders):
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+def test_order_confirm_unfulfilled(
+ staff_api_client, order, permission_group_manage_orders
+):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(
ORDER_CONFIRM_MUTATION, {"id": graphene.Node.to_global_id("Order", order.id)}
)
@@ -178,9 +180,9 @@ def test_order_confirm_unfulfilled(staff_api_client, order, permission_manage_or
def test_order_confirm_no_products_in_order(
- staff_api_client, order_unconfirmed, permission_manage_orders
+ staff_api_client, order_unconfirmed, permission_group_manage_orders
):
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_unconfirmed.lines.set([])
response = staff_api_client.post_graphql(
ORDER_CONFIRM_MUTATION,
@@ -202,13 +204,13 @@ def test_order_confirm_wont_call_capture_for_non_active_payment(
capture_mock,
staff_api_client,
order_unconfirmed,
- permission_manage_orders,
+ permission_group_manage_orders,
payment_txn_preauth,
):
payment_txn_preauth.order = order_unconfirmed
payment_txn_preauth.is_active = False
payment_txn_preauth.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
assert not OrderEvent.objects.exists()
response = staff_api_client.post_graphql(
ORDER_CONFIRM_MUTATION,
@@ -231,7 +233,7 @@ def test_order_confirm_wont_call_capture_for_non_active_payment(
def test_order_confirm_update_display_gross_prices(
staff_api_client,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
):
# given
order = order_with_lines
@@ -249,7 +251,7 @@ def test_order_confirm_update_display_gross_prices(
tax_config.country_exceptions.all().delete()
# when
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(
ORDER_CONFIRM_MUTATION,
@@ -261,3 +263,106 @@ def test_order_confirm_update_display_gross_prices(
assert not content["data"]["orderConfirm"]["errors"]
order.refresh_from_db()
assert order.display_gross_prices == new_display_gross_prices
+
+
+def test_order_confirm_by_user_no_channel_access(
+ staff_api_client,
+ order_unconfirmed,
+ permission_group_all_perms_channel_USD_only,
+ payment_txn_preauth,
+ channel_PLN,
+):
+ # given
+ order_unconfirmed.total_charged = order_unconfirmed.total.gross
+ order_unconfirmed.channel = channel_PLN
+ order_unconfirmed.save(update_fields=["total_charged_amount", "channel"])
+
+ payment_txn_preauth.order = order_unconfirmed
+ payment_txn_preauth.captured_amount = order_unconfirmed.total.gross.amount
+ payment_txn_preauth.total = order_unconfirmed.total.gross.amount
+ payment_txn_preauth.save(update_fields=["order", "captured_amount", "total"])
+
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ assert not OrderEvent.objects.exists()
+
+ # when
+ response = staff_api_client.post_graphql(
+ ORDER_CONFIRM_MUTATION,
+ {"id": graphene.Node.to_global_id("Order", order_unconfirmed.id)},
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.order.actions.handle_fully_paid_order")
+@patch("saleor.plugins.manager.PluginsManager.notify")
+@patch("saleor.payment.gateway.capture")
+def test_order_confirm_by_app(
+ capture_mock,
+ mocked_notify,
+ handle_fully_paid_order_mock,
+ app_api_client,
+ order_unconfirmed,
+ permission_manage_orders,
+ payment_txn_preauth,
+ site_settings,
+):
+ # given
+ payment_txn_preauth.order = order_unconfirmed
+ payment_txn_preauth.captured_amount = order_unconfirmed.total.gross.amount
+ payment_txn_preauth.total = order_unconfirmed.total.gross.amount
+ payment_txn_preauth.save(update_fields=["order", "captured_amount", "total"])
+
+ order_unconfirmed.total_charged = order_unconfirmed.total.gross
+ order_unconfirmed.save(update_fields=["total_charged_amount"])
+ updates_amounts_for_order(order_unconfirmed)
+
+ assert not OrderEvent.objects.exists()
+
+ # when
+ response = app_api_client.post_graphql(
+ ORDER_CONFIRM_MUTATION,
+ {"id": graphene.Node.to_global_id("Order", order_unconfirmed.id)},
+ permissions=(permission_manage_orders,),
+ )
+
+ # then
+ order_data = get_graphql_content(response)["data"]["orderConfirm"]["order"]
+
+ assert order_data["status"] == OrderStatus.UNFULFILLED.upper()
+ order_unconfirmed.refresh_from_db()
+ assert order_unconfirmed.status == OrderStatus.UNFULFILLED
+ assert OrderEvent.objects.count() == 2
+ assert OrderEvent.objects.filter(
+ order=order_unconfirmed,
+ app=app_api_client.app,
+ type=order_events.OrderEvents.CONFIRMED,
+ ).exists()
+
+ assert OrderEvent.objects.filter(
+ order=order_unconfirmed,
+ app=app_api_client.app,
+ type=order_events.OrderEvents.PAYMENT_CAPTURED,
+ parameters__amount=payment_txn_preauth.get_total().amount,
+ ).exists()
+
+ capture_mock.assert_called_once_with(
+ payment_txn_preauth, ANY, channel_slug=order_unconfirmed.channel.slug
+ )
+ expected_payload = {
+ "order": get_default_order_payload(order_unconfirmed, ""),
+ "recipient_email": order_unconfirmed.user.email,
+ "requester_user_id": None,
+ "requester_app_id": to_global_id_or_none(app_api_client.app),
+ **get_site_context_payload(site_settings.site),
+ }
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ORDER_CONFIRMED,
+ expected_payload,
+ channel_slug=order_unconfirmed.channel.slug,
+ )
+ order_info = fetch_order_info(order_unconfirmed)
+ handle_fully_paid_order_mock.assert_called_once_with(
+ ANY, order_info, None, app_api_client.app, site_settings
+ )
diff --git a/saleor/graphql/order/tests/mutations/test_order_discount.py b/saleor/graphql/order/tests/mutations/test_order_discount.py
index 7e4dc9fad0..f0890d4b16 100644
--- a/saleor/graphql/order/tests/mutations/test_order_discount.py
+++ b/saleor/graphql/order/tests/mutations/test_order_discount.py
@@ -12,7 +12,7 @@ from .....order import OrderEvents, OrderStatus
from .....order.error_codes import OrderErrorCode
from .....order.interface import OrderTaxedPricesData
from ....discount.enums import DiscountValueTypeEnum
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
ORDER_DISCOUNT_ADD = """
mutation OrderDiscountAdd($orderId: ID!, $input: OrderDiscountCommonInput!){
@@ -48,13 +48,13 @@ mutation OrderDiscountAdd($orderId: ID!, $input: OrderDiscountCommonInput!){
],
)
def test_add_order_discount_incorrect_values(
- value, value_type, draft_order, staff_api_client, permission_manage_orders
+ value, value_type, draft_order, staff_api_client, permission_group_manage_orders
):
variables = {
"orderId": graphene.Node.to_global_id("Order", draft_order.pk),
"input": {"valueType": value_type, "value": value},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)
content = get_graphql_content(response)
data = content["data"]["orderDiscountAdd"]
@@ -69,14 +69,14 @@ def test_add_order_discount_incorrect_values(
def test_add_fixed_order_discount_order_is_not_draft(
- order_with_lines, staff_api_client, permission_manage_orders
+ order_with_lines, staff_api_client, permission_group_manage_orders
):
value = Decimal("10")
variables = {
"orderId": graphene.Node.to_global_id("Order", order_with_lines.pk),
"input": {"valueType": DiscountValueTypeEnum.FIXED.name, "value": value},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)
content = get_graphql_content(response)
data = content["data"]["orderDiscountAdd"]
@@ -90,7 +90,7 @@ def test_add_fixed_order_discount_order_is_not_draft(
@pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
def test_add_fixed_order_discount_to_order(
- status, draft_order, staff_api_client, permission_manage_orders
+ status, draft_order, staff_api_client, permission_group_manage_orders
):
order = draft_order
order.status = status
@@ -101,7 +101,7 @@ def test_add_fixed_order_discount_to_order(
"orderId": graphene.Node.to_global_id("Order", order.pk),
"input": {"valueType": DiscountValueTypeEnum.FIXED.name, "value": value},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)
content = get_graphql_content(response)
data = content["data"]["orderDiscountAdd"]
@@ -137,7 +137,7 @@ def test_add_fixed_order_discount_to_order(
@pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
def test_add_percentage_order_discount_to_order(
- status, draft_order, staff_api_client, permission_manage_orders
+ status, draft_order, staff_api_client, permission_group_manage_orders
):
order = draft_order
order.status = status
@@ -153,7 +153,7 @@ def test_add_percentage_order_discount_to_order(
"reason": reason,
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)
content = get_graphql_content(response)
data = content["data"]["orderDiscountAdd"]
@@ -192,6 +192,83 @@ def test_add_percentage_order_discount_to_order(
assert discount_data["amount_value"] == str(order_discount.amount.amount)
+def test_add_order_discount_to_order_by_user_no_channel_access(
+ draft_order,
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+):
+ # given
+ order = draft_order
+ order.status = OrderStatus.UNCONFIRMED
+ order.channel = channel_PLN
+ order.save(update_fields=["status", "channel"])
+ value = Decimal("10.000")
+ variables = {
+ "orderId": graphene.Node.to_global_id("Order", order.pk),
+ "input": {"valueType": DiscountValueTypeEnum.FIXED.name, "value": value},
+ }
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_add_fixed_order_discount_to_order_by_app(
+ draft_order, app_api_client, permission_manage_orders
+):
+ # given
+ order = draft_order
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status"])
+ total_before_order_discount = order.total
+ value = Decimal("10.000")
+ variables = {
+ "orderId": graphene.Node.to_global_id("Order", order.pk),
+ "input": {"valueType": DiscountValueTypeEnum.FIXED.name, "value": value},
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ ORDER_DISCOUNT_ADD, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderDiscountAdd"]
+
+ order.refresh_from_db()
+ expected_net = total_before_order_discount.net.amount - value
+
+ errors = data["errors"]
+ assert len(errors) == 0
+
+ # Use `net` values in comparison due to that fixture have taxes incluted in
+ # prices but after recalculation taxes are removed because in tests we
+ # don't use any tax app.
+ assert order.undiscounted_total.net == total_before_order_discount.net
+ assert expected_net == order.total.net.amount
+
+ assert order.discounts.count() == 1
+ order_discount = order.discounts.first()
+ assert order_discount.value == value
+ assert order_discount.value_type == DiscountValueType.FIXED
+ assert order_discount.amount.amount == value
+ assert order_discount.reason is None
+
+ event = order.events.get()
+ assert event.type == OrderEvents.ORDER_DISCOUNT_ADDED
+ parameters = event.parameters
+ discount_data = parameters.get("discount")
+
+ assert discount_data["value"] == str(value)
+ assert discount_data["value_type"] == DiscountValueTypeEnum.FIXED.value
+ assert discount_data["amount_value"] == str(order_discount.amount.amount)
+
+
ORDER_DISCOUNT_UPDATE = """
mutation OrderDiscountUpdate($discountId: ID!, $input: OrderDiscountCommonInput!){
orderDiscountUpdate(discountId:$discountId, input: $input){
@@ -223,7 +300,7 @@ def test_update_percentage_order_discount_to_order(
status,
draft_order_with_fixed_discount_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
order = draft_order_with_fixed_discount_order
order.status = status
@@ -241,7 +318,7 @@ def test_update_percentage_order_discount_to_order(
"reason": reason,
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_DISCOUNT_UPDATE, variables)
content = get_graphql_content(response)
data = content["data"]["orderDiscountUpdate"]
@@ -287,7 +364,7 @@ def test_update_fixed_order_discount_to_order(
status,
draft_order_with_fixed_discount_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
order = draft_order_with_fixed_discount_order
mocked_function.return_value = order.shipping_price
@@ -304,7 +381,7 @@ def test_update_fixed_order_discount_to_order(
"value": value,
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_DISCOUNT_UPDATE, variables)
content = get_graphql_content(response)
data = content["data"]["orderDiscountUpdate"]
@@ -341,7 +418,9 @@ def test_update_fixed_order_discount_to_order(
def test_update_order_discount_order_is_not_draft(
- draft_order_with_fixed_discount_order, staff_api_client, permission_manage_orders
+ draft_order_with_fixed_discount_order,
+ staff_api_client,
+ permission_group_manage_orders,
):
draft_order_with_fixed_discount_order.status = OrderStatus.UNFULFILLED
draft_order_with_fixed_discount_order.save()
@@ -356,7 +435,7 @@ def test_update_order_discount_order_is_not_draft(
"value": value,
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_DISCOUNT_UPDATE, variables)
content = get_graphql_content(response)
data = content["data"]["orderDiscountUpdate"]
@@ -381,7 +460,7 @@ def test_update_order_discount_incorrect_values(
value_type,
draft_order_with_fixed_discount_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
order_discount = draft_order_with_fixed_discount_order.discounts.get()
@@ -392,7 +471,7 @@ def test_update_order_discount_incorrect_values(
"value": value,
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_DISCOUNT_UPDATE, variables)
content = get_graphql_content(response)
data = content["data"]["orderDiscountUpdate"]
@@ -405,6 +484,104 @@ def test_update_order_discount_incorrect_values(
assert error["code"] == OrderErrorCode.INVALID.name
+def test_update_order_discount__by_user_no_channel_access(
+ draft_order_with_fixed_discount_order,
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+):
+ # given
+ order = draft_order_with_fixed_discount_order
+ order.status = OrderStatus.UNCONFIRMED
+ order.channel = channel_PLN
+ order.save(update_fields=["status", "channel"])
+ order_discount = draft_order_with_fixed_discount_order.discounts.get()
+
+ reason = "The reason of the discount"
+ value = Decimal("10.000")
+ variables = {
+ "discountId": graphene.Node.to_global_id("OrderDiscount", order_discount.pk),
+ "input": {
+ "valueType": DiscountValueTypeEnum.PERCENTAGE.name,
+ "value": value,
+ "reason": reason,
+ },
+ }
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_UPDATE, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_update_percentage_order_discount_to_order_by_app(
+ draft_order_with_fixed_discount_order,
+ app_api_client,
+ permission_manage_orders,
+):
+ # given
+ order = draft_order_with_fixed_discount_order
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status"])
+ order_discount = draft_order_with_fixed_discount_order.discounts.get()
+ current_undiscounted_total = order.undiscounted_total
+
+ reason = "The reason of the discount"
+ value = Decimal("10.000")
+ variables = {
+ "discountId": graphene.Node.to_global_id("OrderDiscount", order_discount.pk),
+ "input": {
+ "valueType": DiscountValueTypeEnum.PERCENTAGE.name,
+ "value": value,
+ "reason": reason,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ ORDER_DISCOUNT_UPDATE, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderDiscountUpdate"]
+
+ order.refresh_from_db()
+
+ discount = partial(percentage_discount, percentage=value)
+ expected_net_total = discount(current_undiscounted_total.net)
+ expected_gross_total = discount(current_undiscounted_total.gross)
+ expected_total = TaxedMoney(expected_net_total, expected_gross_total)
+
+ errors = data["errors"]
+ assert len(errors) == 0
+
+ # Use `net` values in comparison due to that fixture have taxes included in
+ # prices but after recalculation taxes are removed because in tests we
+ # don't use any tax app.
+ assert order.undiscounted_total.net == current_undiscounted_total.net
+ assert expected_net_total == order.total.net
+
+ assert order.discounts.count() == 1
+ order_discount = order.discounts.first()
+ assert order_discount.value == value
+ assert order_discount.value_type == DiscountValueType.PERCENTAGE
+ discount_amount = current_undiscounted_total.net - expected_total.net
+ assert order_discount.amount == discount_amount
+ assert order_discount.reason == reason
+
+ event = order.events.get()
+ assert event.type == OrderEvents.ORDER_DISCOUNT_UPDATED
+ parameters = event.parameters
+ discount_data = parameters.get("discount")
+
+ assert discount_data["value"] == str(value)
+ assert discount_data["value_type"] == DiscountValueTypeEnum.PERCENTAGE.value
+ assert discount_data["amount_value"] == str(discount_amount.amount)
+
+
ORDER_DISCOUNT_DELETE = """
mutation OrderDiscountDelete($discountId: ID!){
orderDiscountDelete(discountId: $discountId){
@@ -426,7 +603,7 @@ def test_delete_order_discount_from_order(
status,
draft_order_with_fixed_discount_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
order = draft_order_with_fixed_discount_order
order.status = status
@@ -444,7 +621,7 @@ def test_delete_order_discount_from_order(
variables = {
"discountId": graphene.Node.to_global_id("OrderDiscount", order_discount.pk),
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_DISCOUNT_DELETE, variables)
content = get_graphql_content(response)
data = content["data"]["orderDiscountDelete"]
@@ -464,7 +641,9 @@ def test_delete_order_discount_from_order(
def test_delete_order_discount_order_is_not_draft(
- draft_order_with_fixed_discount_order, staff_api_client, permission_manage_orders
+ draft_order_with_fixed_discount_order,
+ staff_api_client,
+ permission_group_manage_orders,
):
draft_order_with_fixed_discount_order.status = OrderStatus.UNFULFILLED
draft_order_with_fixed_discount_order.save()
@@ -474,7 +653,7 @@ def test_delete_order_discount_order_is_not_draft(
variables = {
"discountId": graphene.Node.to_global_id("OrderDiscount", order_discount.pk),
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_DISCOUNT_DELETE, variables)
content = get_graphql_content(response)
data = content["data"]["orderDiscountDelete"]
@@ -489,6 +668,83 @@ def test_delete_order_discount_order_is_not_draft(
assert error["code"] == OrderErrorCode.CANNOT_DISCOUNT.name
+def test_delete_order_discount_from_order_by_user_no_channel_access(
+ draft_order_with_fixed_discount_order,
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+):
+ # given
+ order = draft_order_with_fixed_discount_order
+ order.status = OrderStatus.UNCONFIRMED
+ order.channel = channel_PLN
+ order.save(update_fields=["status", "channel"])
+
+ order_discount = draft_order_with_fixed_discount_order.discounts.get()
+ name = "discount translated"
+ translated_name = "discount translated name"
+ order_discount.name = name
+ order_discount.translated_name = translated_name
+ order_discount.save(update_fields=["name", "translated_name"])
+
+ variables = {
+ "discountId": graphene.Node.to_global_id("OrderDiscount", order_discount.pk),
+ }
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_DELETE, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_delete_order_discount_from_order_by_app(
+ draft_order_with_fixed_discount_order,
+ app_api_client,
+ permission_manage_orders,
+):
+ # given
+ order = draft_order_with_fixed_discount_order
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status"])
+
+ order_discount = draft_order_with_fixed_discount_order.discounts.get()
+ name = "discount translated"
+ translated_name = "discount translated name"
+ order_discount.name = name
+ order_discount.translated_name = translated_name
+ order_discount.save(update_fields=["name", "translated_name"])
+
+ current_undiscounted_total = order.undiscounted_total
+
+ variables = {
+ "discountId": graphene.Node.to_global_id("OrderDiscount", order_discount.pk),
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ ORDER_DISCOUNT_DELETE, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderDiscountDelete"]
+
+ order.refresh_from_db()
+
+ errors = data["errors"]
+ assert len(errors) == 0
+
+ assert order.undiscounted_total == current_undiscounted_total
+ assert order.total == current_undiscounted_total
+
+ event = order.events.get()
+ assert event.type == OrderEvents.ORDER_DISCOUNT_DELETED
+
+ assert order.search_vector
+
+
ORDER_LINE_DISCOUNT_UPDATE = """
mutation OrderLineDiscountUpdate($input: OrderDiscountCommonInput!, $orderLineId: ID!){
orderLineDiscountUpdate(orderLineId: $orderLineId, input: $input){
@@ -514,7 +770,7 @@ def test_update_order_line_discount(
status,
draft_order_with_fixed_discount_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
# given
order = draft_order_with_fixed_discount_order
@@ -543,7 +799,7 @@ def test_update_order_line_discount(
"reason": reason,
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_UPDATE, variables)
@@ -582,12 +838,99 @@ def test_update_order_line_discount(
assert discount_data["amount_value"] == str(unit_discount.amount)
+def test_update_order_line_discount_by_user_no_channel_access(
+ draft_order_with_fixed_discount_order,
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+):
+ # given
+ order = draft_order_with_fixed_discount_order
+ order.channel = channel_PLN
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status", "channel"])
+ line_to_discount = order.lines.first()
+
+ value = Decimal("5")
+ reason = "New reason for unit discount"
+ variables = {
+ "orderLineId": graphene.Node.to_global_id("OrderLine", line_to_discount.pk),
+ "input": {
+ "valueType": DiscountValueTypeEnum.FIXED.name,
+ "value": value,
+ "reason": reason,
+ },
+ }
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_UPDATE, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_update_order_line_discount_by_app(
+ draft_order_with_fixed_discount_order,
+ app_api_client,
+ permission_manage_orders,
+ channel_PLN,
+):
+ # given
+ order = draft_order_with_fixed_discount_order
+ order.channel = channel_PLN
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status", "channel"])
+ line_to_discount = order.lines.first()
+
+ value = Decimal("5")
+ reason = "New reason for unit discount"
+ variables = {
+ "orderLineId": graphene.Node.to_global_id("OrderLine", line_to_discount.pk),
+ "input": {
+ "valueType": DiscountValueTypeEnum.FIXED.name,
+ "value": value,
+ "reason": reason,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ ORDER_LINE_DISCOUNT_UPDATE, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderLineDiscountUpdate"]
+
+ line_to_discount.refresh_from_db()
+
+ errors = data["errors"]
+ assert not errors
+
+ unit_discount = line_to_discount.unit_discount
+
+ event = order.events.get()
+ assert event.type == OrderEvents.ORDER_LINE_DISCOUNT_UPDATED
+ parameters = event.parameters
+ lines = parameters.get("lines", {})
+ assert len(lines) == 1
+
+ line_data = lines[0]
+ assert line_data.get("line_pk") == str(line_to_discount.pk)
+ discount_data = line_data.get("discount")
+
+ assert discount_data["value"] == str(value)
+ assert discount_data["value_type"] == DiscountValueTypeEnum.FIXED.value
+ assert discount_data["amount_value"] == str(unit_discount.amount)
+
+
@pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
def test_update_order_line_discount_line_with_discount(
status,
draft_order_with_fixed_discount_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
# given
order = draft_order_with_fixed_discount_order
@@ -637,7 +980,7 @@ def test_update_order_line_discount_line_with_discount(
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_UPDATE, variables)
@@ -681,7 +1024,9 @@ def test_update_order_line_discount_line_with_discount(
def test_update_order_line_discount_order_is_not_draft(
- draft_order_with_fixed_discount_order, staff_api_client, permission_manage_orders
+ draft_order_with_fixed_discount_order,
+ staff_api_client,
+ permission_group_manage_orders,
):
draft_order_with_fixed_discount_order.status = OrderStatus.UNFULFILLED
draft_order_with_fixed_discount_order.save()
@@ -696,7 +1041,7 @@ def test_update_order_line_discount_order_is_not_draft(
"reason": "New reason for unit discount",
},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_UPDATE, variables)
content = get_graphql_content(response)
data = content["data"]["orderLineDiscountUpdate"]
@@ -738,7 +1083,7 @@ def test_delete_discount_from_order_line(
status,
draft_order_with_fixed_discount_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
order = draft_order_with_fixed_discount_order
order.status = status
@@ -767,8 +1112,126 @@ def test_delete_discount_from_order_line(
variables = {
"orderLineId": graphene.Node.to_global_id("OrderLine", line.pk),
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_REMOVE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderLineDiscountRemove"]
+
+ errors = data["errors"]
+ assert len(errors) == 0
+
+ line.refresh_from_db()
+
+ assert line.unit_price == line_undiscounted_price
+ assert line.total_price == line_undiscounted_total_price
+ unit_discount = line.unit_discount
+ currency = order.currency
+ assert unit_discount == Money(Decimal(0), currency=currency)
+
+ event = order.events.get()
+ assert event.type == OrderEvents.ORDER_LINE_DISCOUNT_REMOVED
+ parameters = event.parameters
+ lines = parameters.get("lines", {})
+ assert len(lines) == 1
+
+ line_data = lines[0]
+ assert line_data.get("line_pk") == str(line.pk)
+
+
+@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_unit")
+@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_total")
+def test_delete_discount_from_order_line_by_user_no_channel_access(
+ mocked_calculate_order_line_total,
+ mocked_calculate_order_line_unit,
+ draft_order_with_fixed_discount_order,
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+):
+ # given
+ order = draft_order_with_fixed_discount_order
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order.channel = channel_PLN
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status", "channel"])
+ line = order.lines.first()
+
+ line_undiscounted_price = TaxedMoney(
+ line.undiscounted_base_unit_price, line.undiscounted_base_unit_price
+ )
+ line_undiscounted_total_price = line_undiscounted_price * line.quantity
+
+ mocked_calculate_order_line_unit.return_value = OrderTaxedPricesData(
+ undiscounted_price=line_undiscounted_price,
+ price_with_discounts=line_undiscounted_price,
+ )
+ mocked_calculate_order_line_total.return_value = OrderTaxedPricesData(
+ undiscounted_price=line_undiscounted_total_price,
+ price_with_discounts=line_undiscounted_total_price,
+ )
+
+ line.unit_discount_amount = Decimal("2.5")
+ line.unit_discount_type = DiscountValueType.FIXED
+ line.unit_discount_value = Decimal("2.5")
+ line.save()
+
+ variables = {
+ "orderLineId": graphene.Node.to_global_id("OrderLine", line.pk),
+ }
+
+ # when
response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_REMOVE, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_unit")
+@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_total")
+def test_delete_discount_from_order_line_by_app(
+ mocked_calculate_order_line_total,
+ mocked_calculate_order_line_unit,
+ draft_order_with_fixed_discount_order,
+ app_api_client,
+ permission_manage_orders,
+ channel_PLN,
+):
+ # given
+ order = draft_order_with_fixed_discount_order
+ order.channel = channel_PLN
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status", "channel"])
+ line = order.lines.first()
+
+ line_undiscounted_price = TaxedMoney(
+ line.undiscounted_base_unit_price, line.undiscounted_base_unit_price
+ )
+ line_undiscounted_total_price = line_undiscounted_price * line.quantity
+
+ mocked_calculate_order_line_unit.return_value = OrderTaxedPricesData(
+ undiscounted_price=line_undiscounted_price,
+ price_with_discounts=line_undiscounted_price,
+ )
+ mocked_calculate_order_line_total.return_value = OrderTaxedPricesData(
+ undiscounted_price=line_undiscounted_total_price,
+ price_with_discounts=line_undiscounted_total_price,
+ )
+
+ line.unit_discount_amount = Decimal("2.5")
+ line.unit_discount_type = DiscountValueType.FIXED
+ line.unit_discount_value = Decimal("2.5")
+ line.save()
+
+ variables = {
+ "orderLineId": graphene.Node.to_global_id("OrderLine", line.pk),
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ ORDER_LINE_DISCOUNT_REMOVE, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
content = get_graphql_content(response)
data = content["data"]["orderLineDiscountRemove"]
@@ -794,8 +1257,11 @@ def test_delete_discount_from_order_line(
def test_delete_order_line_discount_order_is_not_draft(
- draft_order_with_fixed_discount_order, staff_api_client, permission_manage_orders
+ draft_order_with_fixed_discount_order,
+ staff_api_client,
+ permission_group_manage_orders,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
draft_order_with_fixed_discount_order.status = OrderStatus.UNFULFILLED
draft_order_with_fixed_discount_order.save()
@@ -809,7 +1275,6 @@ def test_delete_order_line_discount_order_is_not_draft(
variables = {
"orderLineId": graphene.Node.to_global_id("OrderLine", line.pk),
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_REMOVE, variables)
content = get_graphql_content(response)
data = content["data"]["orderLineDiscountRemove"]
diff --git a/saleor/graphql/order/tests/mutations/test_order_fulfill.py b/saleor/graphql/order/tests/mutations/test_order_fulfill.py
index b3090f8323..d534c510a5 100644
--- a/saleor/graphql/order/tests/mutations/test_order_fulfill.py
+++ b/saleor/graphql/order/tests/mutations/test_order_fulfill.py
@@ -12,9 +12,9 @@ from .....order.models import Fulfillment, FulfillmentLine
from .....product.models import ProductVariant
from .....tests.utils import flush_post_commit_hooks
from .....warehouse.models import Allocation, Stock
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
-ORDER_FULFILL_QUERY = """
+ORDER_FULFILL_MUTATION = """
mutation fulfillOrder(
$order: ID, $input: OrderFulfillInput!
) {
@@ -22,6 +22,9 @@ ORDER_FULFILL_QUERY = """
order: $order,
input: $input
) {
+ fulfillments {
+ id
+ }
errors {
field
code
@@ -39,12 +42,13 @@ def test_order_fulfill_with_out_of_stock_webhook(
product_variant_out_of_stock_webhooks,
staff_api_client,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
):
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order.id)
_, order_line2 = order.lines.all()
order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id)
@@ -61,9 +65,7 @@ def test_order_fulfill_with_out_of_stock_webhook(
],
},
}
- staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ staff_api_client.post_graphql(query, variables)
stock = order_line2.variant.stocks.filter(warehouse=warehouse).first()
product_variant_out_of_stock_webhooks.assert_called_once_with(stock)
@@ -77,14 +79,15 @@ def test_order_fulfill(
staff_api_client,
staff_user,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
site_settings,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
site_settings.fulfillment_auto_approve = fulfillment_auto_approve
site_settings.save(update_fields=["fulfillment_auto_approve"])
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
order_line, order_line2 = order.lines.all()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -106,9 +109,7 @@ def test_order_fulfill(
],
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert not data["errors"]
@@ -133,6 +134,51 @@ def test_order_fulfill(
)
+def test_order_fulfill_no_channel_access(
+ staff_api_client,
+ order_with_lines,
+ permission_group_all_perms_channel_USD_only,
+ warehouse,
+ site_settings,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = order_with_lines
+ query = ORDER_FULFILL_MUTATION
+
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ order_line, order_line2 = order.lines.all()
+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
+ order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id)
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ variables = {
+ "order": order_id,
+ "input": {
+ "notifyCustomer": True,
+ "lines": [
+ {
+ "orderLineId": order_line_id,
+ "stocks": [{"quantity": 3, "warehouse": warehouse_id}],
+ },
+ {
+ "orderLineId": order_line2_id,
+ "stocks": [{"quantity": 2, "warehouse": warehouse_id}],
+ },
+ ],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
@pytest.mark.parametrize("fulfillment_auto_approve", [True, False])
@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill_with_tracking_number(
@@ -141,14 +187,15 @@ def test_order_fulfill_with_tracking_number(
staff_api_client,
staff_user,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
site_settings,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
site_settings.fulfillment_auto_approve = fulfillment_auto_approve
site_settings.save(update_fields=["fulfillment_auto_approve"])
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
order_line, order_line2 = order.lines.all()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -171,9 +218,7 @@ def test_order_fulfill_with_tracking_number(
"trackingNumber": "test_tracking_number",
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert not data["errors"]
@@ -202,11 +247,12 @@ def test_order_fulfill_with_stock_exceeded_with_flag_disabled(
staff_api_client,
staff_user,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
):
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order.id)
order_line, order_line2 = order.lines.all()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -241,9 +287,7 @@ def test_order_fulfill_with_stock_exceeded_with_flag_disabled(
],
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert data["errors"]
@@ -260,11 +304,12 @@ def test_order_fulfill_with_stock_exceeded_with_flag_enabled(
staff_api_client,
staff_user,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
):
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order.id)
order_line, order_line2 = order.lines.all()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -293,9 +338,7 @@ def test_order_fulfill_with_stock_exceeded_with_flag_enabled(
],
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert not data["errors"]
@@ -317,16 +360,16 @@ def test_order_fulfill_with_stock_exceeded_with_flag_enabled(
def test_order_fulfill_with_allow_stock_to_be_exceeded_flag_enabled_and_deleted_stocks(
- staff_api_client, staff_user, permission_manage_orders, order_fulfill_data
+ staff_api_client, staff_user, permission_group_manage_orders, order_fulfill_data
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_fulfill_data.order
Stock.objects.filter(warehouse=order_fulfill_data.warehouse).delete()
response = staff_api_client.post_graphql(
- ORDER_FULFILL_QUERY,
+ ORDER_FULFILL_MUTATION,
order_fulfill_data.variables,
- permissions=[permission_manage_orders],
)
get_graphql_content(response)
order.refresh_from_db()
@@ -341,17 +384,17 @@ def test_order_fulfill_with_allow_stock_to_be_exceeded_flag_enabled_and_deleted_
def test_order_fulfill_with_allow_stock_to_be_exceeded_flag_disabled_deleted_stocks(
- staff_api_client, staff_user, permission_manage_orders, order_fulfill_data
+ staff_api_client, staff_user, permission_group_manage_orders, order_fulfill_data
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_fulfill_data.order
order_fulfill_data.variables["input"]["allowStockToBeExceeded"] = False
Stock.objects.filter(warehouse=order_fulfill_data.warehouse).delete()
response = staff_api_client.post_graphql(
- ORDER_FULFILL_QUERY,
+ ORDER_FULFILL_MUTATION,
order_fulfill_data.variables,
- permissions=[permission_manage_orders],
)
get_graphql_content(response)
order.refresh_from_db()
@@ -367,16 +410,16 @@ def test_order_fulfill_with_allow_stock_to_be_exceeded_flag_disabled_deleted_sto
def test_order_fulfill_with_allow_stock_to_be_exceeded_flag_enabled_and_deleted_variant(
- staff_api_client, staff_user, permission_manage_orders, order_fulfill_data
+ staff_api_client, staff_user, permission_group_manage_orders, order_fulfill_data
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_fulfill_data.order
order.lines.first().variant.delete()
response = staff_api_client.post_graphql(
- ORDER_FULFILL_QUERY,
+ ORDER_FULFILL_MUTATION,
order_fulfill_data.variables,
- permissions=[permission_manage_orders],
)
get_graphql_content(response)
order.refresh_from_db()
@@ -391,17 +434,17 @@ def test_order_fulfill_with_allow_stock_to_be_exceeded_flag_enabled_and_deleted_
def test_order_fulfill_with_allow_stock_to_be_exceeded_flag_disabled_deleted_variant(
- staff_api_client, staff_user, permission_manage_orders, order_fulfill_data
+ staff_api_client, staff_user, permission_group_manage_orders, order_fulfill_data
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_fulfill_data.order
order_fulfill_data.variables["input"]["allowStockToBeExceeded"] = False
order.lines.first().variant.delete()
response = staff_api_client.post_graphql(
- ORDER_FULFILL_QUERY,
+ ORDER_FULFILL_MUTATION,
order_fulfill_data.variables,
- permissions=[permission_manage_orders],
)
get_graphql_content(response)
order.refresh_from_db()
@@ -422,11 +465,12 @@ def test_order_fulfill_above_available_quantity(
staff_api_client,
staff_user,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
):
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order.id)
order_line, order_line2 = order.lines.all()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -457,9 +501,7 @@ def test_order_fulfill_above_available_quantity(
],
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
error = data["errors"][0]
@@ -479,7 +521,7 @@ def test_order_fulfill_as_app(
site_settings,
):
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
order_line, order_line2 = order.lines.all()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -502,7 +544,7 @@ def test_order_fulfill_as_app(
},
}
response = app_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
+ query, variables, permissions=(permission_manage_orders,)
)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
@@ -534,12 +576,13 @@ def test_order_fulfill_many_warehouses(
staff_api_client,
staff_user,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouses,
site_settings,
):
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
warehouse1, warehouse2 = warehouses
order_line1, order_line2 = order.lines.all()
@@ -568,9 +611,7 @@ def test_order_fulfill_many_warehouses(
],
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert not data["errors"]
@@ -605,11 +646,12 @@ def test_order_fulfill_with_gift_cards(
order,
gift_card_non_shippable_order_line,
gift_card_shippable_order_line,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
):
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_line, order_line2 = (
gift_card_non_shippable_order_line,
gift_card_shippable_order_line,
@@ -633,9 +675,7 @@ def test_order_fulfill_with_gift_cards(
],
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
flush_post_commit_hooks()
data = content["data"]["orderFulfill"]
@@ -690,11 +730,12 @@ def test_order_fulfill_with_gift_card_lines_waiting_for_approval(
order,
gift_card_non_shippable_order_line,
gift_card_shippable_order_line,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
site_settings,
):
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
site_settings.fulfillment_auto_approve = False
site_settings.save(update_fields=["fulfillment_auto_approve"])
@@ -724,9 +765,7 @@ def test_order_fulfill_with_gift_card_lines_waiting_for_approval(
],
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert not data["errors"]
@@ -746,7 +785,7 @@ def test_order_fulfill_with_gift_cards_by_app(
warehouse,
site_settings,
):
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
order_line = gift_card_shippable_order_line
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -765,7 +804,7 @@ def test_order_fulfill_with_gift_cards_by_app(
},
}
response = app_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
+ query, variables, permissions=(permission_manage_orders,)
)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
@@ -786,7 +825,7 @@ def test_order_fulfill_with_gift_cards_multiple_warehouses(
shipping_zone,
site_settings,
):
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
order_line = gift_card_shippable_order_line
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -826,7 +865,7 @@ def test_order_fulfill_with_gift_cards_multiple_warehouses(
},
}
response = app_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
+ query, variables, permissions=(permission_manage_orders,)
)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
@@ -842,12 +881,13 @@ def test_order_fulfill_without_notification(
staff_api_client,
staff_user,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
site_settings,
):
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order.id)
order_line = order.lines.first()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -864,9 +904,7 @@ def test_order_fulfill_without_notification(
],
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert not data["errors"]
@@ -894,13 +932,14 @@ def test_order_fulfill_lines_with_empty_quantity(
staff_api_client,
staff_user,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
warehouse_no_shipping_zone,
site_settings,
):
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order.id)
order_line, order_line2 = order.lines.all()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -932,9 +971,7 @@ def test_order_fulfill_lines_with_empty_quantity(
},
}
variables["input"]["lines"][0]["stocks"][0]["quantity"] = 0
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert not data["errors"]
@@ -964,15 +1001,16 @@ def test_order_fulfill_without_sku(
staff_api_client,
staff_user,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
site_settings,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
ProductVariant.objects.update(sku=None)
site_settings.fulfillment_auto_approve = fulfillment_auto_approve
site_settings.save(update_fields=["fulfillment_auto_approve"])
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
order.lines.update(product_sku=None)
order_id = graphene.Node.to_global_id("Order", order.id)
order_line, order_line2 = order.lines.all()
@@ -995,9 +1033,7 @@ def test_order_fulfill_without_sku(
],
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert not data["errors"]
@@ -1028,10 +1064,11 @@ def test_order_fulfill_zero_quantity(
staff_api_client,
staff_user,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
):
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order_with_lines.id)
order_line = order_with_lines.lines.first()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -1047,9 +1084,7 @@ def test_order_fulfill_zero_quantity(
]
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert data["errors"]
@@ -1065,12 +1100,13 @@ def test_order_fulfill_zero_quantity(
def test_order_fulfill_channel_without_shipping_zones(
staff_api_client,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
):
order = order_with_lines
order.channel.shipping_zones.clear()
- query = ORDER_FULFILL_QUERY
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ query = ORDER_FULFILL_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
order_line = order.lines.first()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -1087,9 +1123,7 @@ def test_order_fulfill_channel_without_shipping_zones(
],
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert len(data["errors"]) == 1
@@ -1104,10 +1138,11 @@ def test_order_fulfill_fulfilled_order(
staff_api_client,
staff_user,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
):
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order_with_lines.id)
order_line = order_with_lines.lines.first()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -1123,9 +1158,7 @@ def test_order_fulfill_fulfilled_order(
]
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert data["errors"]
@@ -1143,13 +1176,14 @@ def test_order_fulfill_unpaid_order_and_disallow_unpaid(
mock_create_fulfillments,
staff_api_client,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
site_settings,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
site_settings.fulfillment_allow_unpaid = False
site_settings.save(update_fields=["fulfillment_allow_unpaid"])
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
order_id = graphene.Node.to_global_id("Order", order_with_lines.id)
order_line = order_with_lines.lines.first()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -1165,9 +1199,7 @@ def test_order_fulfill_unpaid_order_and_disallow_unpaid(
]
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert data["errors"]
@@ -1185,11 +1217,12 @@ def test_order_fulfill_warehouse_with_insufficient_stock_exception(
mock_create_fulfillments,
staff_api_client,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse_no_shipping_zone,
):
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order.id)
order_line = order.lines.first()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -1219,9 +1252,7 @@ def test_order_fulfill_warehouse_with_insufficient_stock_exception(
]
)
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert data["errors"]
@@ -1239,11 +1270,12 @@ def test_order_fulfill_warehouse_duplicated_warehouse_id(
mock_create_fulfillments,
staff_api_client,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
):
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order.id)
order_line = order.lines.first()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -1262,9 +1294,7 @@ def test_order_fulfill_warehouse_duplicated_warehouse_id(
]
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert data["errors"]
@@ -1283,11 +1313,12 @@ def test_order_fulfill_warehouse_duplicated_order_line_id(
mock_create_fulfillments,
staff_api_client,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
):
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order.id)
order_line = order.lines.first()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
@@ -1307,9 +1338,7 @@ def test_order_fulfill_warehouse_duplicated_order_line_id(
]
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert data["errors"]
@@ -1327,10 +1356,11 @@ def test_order_fulfill_preorder(
staff_api_client,
staff_user,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
):
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order_with_lines.id)
order_line = order_with_lines.lines.first()
variant = order_line.variant
@@ -1350,9 +1380,7 @@ def test_order_fulfill_preorder(
]
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert data["errors"]
@@ -1367,15 +1395,16 @@ def test_order_fulfill_preorder(
def test_order_fulfill_preorder_waiting_fulfillment(
staff_api_client,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
warehouse,
site_settings,
):
"""If fulfillment_auto_approve is set to False,
it's possible to fulfill lines to WAITING_FOR_APPROVAL status."""
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
site_settings.fulfillment_auto_approve = False
site_settings.save(update_fields=["fulfillment_auto_approve"])
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
order_id = graphene.Node.to_global_id("Order", order_with_lines.id)
order_line = order_with_lines.lines.first()
variant = order_line.variant
@@ -1395,9 +1424,7 @@ def test_order_fulfill_preorder_waiting_fulfillment(
]
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert not data["errors"]
@@ -1414,10 +1441,11 @@ def test_create_digital_fulfillment(
staff_api_client,
order_with_lines,
warehouse,
- permission_manage_orders,
+ permission_group_manage_orders,
):
order = order_with_lines
- query = ORDER_FULFILL_QUERY
+ query = ORDER_FULFILL_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", order.id)
order_line = order.lines.first()
order_line.variant = digital_content.product_variant
@@ -1450,9 +1478,7 @@ def test_create_digital_fulfillment(
],
},
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
get_graphql_content(response)
assert mock_email_fulfillment.call_count == 1
diff --git a/saleor/graphql/order/tests/mutations/test_order_line_delete.py b/saleor/graphql/order/tests/mutations/test_order_line_delete.py
index fde867a86b..3cc6e8316b 100644
--- a/saleor/graphql/order/tests/mutations/test_order_line_delete.py
+++ b/saleor/graphql/order/tests/mutations/test_order_line_delete.py
@@ -8,7 +8,7 @@ from .....order import OrderStatus
from .....order import events as order_events
from .....order.models import OrderEvent
from .....warehouse.models import Stock
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
from ..utils import assert_proper_webhook_called_once
ORDER_LINE_DELETE_MUTATION = """
@@ -43,9 +43,10 @@ ORDER_LINE_DELETE_MUTATION = """
def test_order_line_remove_with_back_in_stock_webhook(
back_in_stock_webhook_mock,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
Stock.objects.update(quantity=3)
first_stock = Stock.objects.first()
assert (
@@ -68,9 +69,7 @@ def test_order_line_remove_with_back_in_stock_webhook(
line_id = graphene.Node.to_global_id("OrderLine", line.id)
variables = {"id": line_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderLineDelete"]
assert OrderEvent.objects.count() == 1
@@ -98,10 +97,11 @@ def test_order_line_remove(
draft_order_updated_webhook_mock,
status,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
query = ORDER_LINE_DELETE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.status = status
order.save(update_fields=["status"])
@@ -109,9 +109,7 @@ def test_order_line_remove(
line_id = graphene.Node.to_global_id("OrderLine", line.id)
variables = {"id": line_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderLineDelete"]
assert OrderEvent.objects.count() == 1
@@ -123,6 +121,70 @@ def test_order_line_remove(
)
+def test_order_line_remove_by_usr_no_channel_access(
+ order_with_lines,
+ permission_group_all_perms_channel_USD_only,
+ staff_api_client,
+ channel_PLN,
+):
+ # given
+ query = ORDER_LINE_DELETE_MUTATION
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = order_with_lines
+ order.channel = channel_PLN
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status", "channel"])
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.id)
+ variables = {"id": line_id}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+def test_order_line_remove_by_app(
+ order_updated_webhook_mock,
+ draft_order_updated_webhook_mock,
+ order_with_lines,
+ permission_manage_orders,
+ app_api_client,
+ channel_PLN,
+):
+ # given
+ query = ORDER_LINE_DELETE_MUTATION
+ order = order_with_lines
+ order.channel = channel_PLN
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status", "channel"])
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.id)
+ variables = {"id": line_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderLineDelete"]
+ assert OrderEvent.objects.count() == 1
+ assert OrderEvent.objects.last().type == order_events.OrderEvents.REMOVED_PRODUCTS
+ assert data["orderLine"]["id"] == line_id
+ assert line not in order.lines.all()
+ assert_proper_webhook_called_once(
+ order,
+ OrderStatus.UNCONFIRMED,
+ draft_order_updated_webhook_mock,
+ order_updated_webhook_mock,
+ )
+
+
@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
def test_invalid_order_when_removing_lines(
@@ -130,16 +192,15 @@ def test_invalid_order_when_removing_lines(
draft_order_update_webhook_mock,
staff_api_client,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
):
query = ORDER_LINE_DELETE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
line = order.lines.first()
line_id = graphene.Node.to_global_id("OrderLine", line.id)
variables = {"id": line_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderLineDelete"]
assert data["errors"]
@@ -150,8 +211,9 @@ def test_invalid_order_when_removing_lines(
def test_draft_order_properly_recalculate_total_after_shipping_product_removed(
staff_api_client,
draft_order,
- permission_manage_orders,
+ permission_group_manage_orders,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
line = order.lines.get(product_sku="SKU_AA")
line.is_shipping_required = True
@@ -162,9 +224,7 @@ def test_draft_order_properly_recalculate_total_after_shipping_product_removed(
line_2_id = graphene.Node.to_global_id("OrderLine", line_2.id)
variables = {"id": line_2_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderLineDelete"]
diff --git a/saleor/graphql/order/tests/mutations/test_order_line_update.py b/saleor/graphql/order/tests/mutations/test_order_line_update.py
index 0e4753537a..2514a51287 100644
--- a/saleor/graphql/order/tests/mutations/test_order_line_update.py
+++ b/saleor/graphql/order/tests/mutations/test_order_line_update.py
@@ -39,7 +39,7 @@ ORDER_LINE_UPDATE_MUTATION = """
def test_order_line_update_with_out_of_stock_webhook_for_two_lines_success_scenario(
out_of_stock_mock,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
Stock.objects.update(quantity=5)
@@ -53,7 +53,7 @@ def test_order_line_update_with_out_of_stock_webhook_for_two_lines_success_scena
first_line_id = graphene.Node.to_global_id("OrderLine", first_line.id)
second_line_id = graphene.Node.to_global_id("OrderLine", second_line.id)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"lineId": first_line_id, "quantity": new_quantity}
staff_api_client.post_graphql(query, variables)
@@ -69,7 +69,7 @@ def test_order_line_update_with_out_of_stock_webhook_for_two_lines_success_scena
def test_order_line_update_with_out_of_stock_webhook_success_scenario(
out_of_stock_mock,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
query = ORDER_LINE_UPDATE_MUTATION
@@ -80,7 +80,7 @@ def test_order_line_update_with_out_of_stock_webhook_success_scenario(
new_quantity = 5
line_id = graphene.Node.to_global_id("OrderLine", line.id)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"lineId": line_id, "quantity": new_quantity}
staff_api_client.post_graphql(query, variables)
@@ -92,7 +92,7 @@ def test_order_line_update_with_out_of_stock_webhook_success_scenario(
def test_order_line_update_with_back_in_stock_webhook_fail_scenario(
product_variant_back_in_stock_webhook_mock,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
query = ORDER_LINE_UPDATE_MUTATION
@@ -103,7 +103,7 @@ def test_order_line_update_with_back_in_stock_webhook_fail_scenario(
new_quantity = 1
line_id = graphene.Node.to_global_id("OrderLine", line.id)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"lineId": line_id, "quantity": new_quantity}
staff_api_client.post_graphql(query, variables)
@@ -115,7 +115,7 @@ def test_order_line_update_with_back_in_stock_webhook_fail_scenario(
def test_order_line_update_with_back_in_stock_webhook_called_once_success_scenario(
back_in_stock_mock,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
first_allocated = Allocation.objects.first()
@@ -131,7 +131,7 @@ def test_order_line_update_with_back_in_stock_webhook_called_once_success_scenar
line_id = graphene.Node.to_global_id("OrderLine", line.id)
variables = {"lineId": line_id, "quantity": new_quantity}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
staff_api_client.post_graphql(query, variables)
back_in_stock_mock.assert_called_once_with(first_allocated.stock)
@@ -141,7 +141,7 @@ def test_order_line_update_with_back_in_stock_webhook_called_once_success_scenar
def test_order_line_update_with_back_in_stock_webhook_called_twice_success_scenario(
product_variant_back_in_stock_webhook_mock,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
first_allocation = Allocation.objects.first()
@@ -157,7 +157,7 @@ def test_order_line_update_with_back_in_stock_webhook_called_twice_success_scena
first_line_id = graphene.Node.to_global_id("OrderLine", first_line.id)
second_line_id = graphene.Node.to_global_id("OrderLine", second_line.id)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"lineId": first_line_id, "quantity": new_quantity}
staff_api_client.post_graphql(query, variables)
@@ -177,7 +177,7 @@ def test_order_line_update(
draft_order_updated_webhook_mock,
status,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
staff_user,
):
@@ -204,7 +204,7 @@ def test_order_line_update(
draft_order_updated_webhook_mock.assert_not_called()
# assign permissions
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderLineUpdate"]
@@ -230,11 +230,81 @@ def test_order_line_update(
assert data["errors"][0]["field"] == "quantity"
+def test_order_line_update_by_user_no_channel_access(
+ order_with_lines,
+ permission_group_all_perms_channel_USD_only,
+ staff_api_client,
+ staff_user,
+ channel_PLN,
+):
+ # given
+ query = ORDER_LINE_UPDATE_MUTATION
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ order.channel = channel_PLN
+ order.save(update_fields=["status", "channel"])
+
+ line = order.lines.first()
+ new_quantity = 1
+ line_id = graphene.Node.to_global_id("OrderLine", line.id)
+ variables = {"lineId": line_id, "quantity": new_quantity}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+def test_order_line_update_by_app(
+ order_updated_webhook_mock,
+ draft_order_updated_webhook_mock,
+ order_with_lines,
+ permission_manage_orders,
+ app_api_client,
+ channel_PLN,
+):
+ # given
+ query = ORDER_LINE_UPDATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ order.channel = channel_PLN
+ order.save(update_fields=["status", "channel"])
+
+ line = order.lines.first()
+ new_quantity = 1
+ line_id = graphene.Node.to_global_id("OrderLine", line.id)
+ variables = {"lineId": line_id, "quantity": new_quantity}
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderLineUpdate"]
+ assert data["orderLine"]["quantity"] == new_quantity
+ assert_proper_webhook_called_once(
+ order,
+ order.status,
+ draft_order_updated_webhook_mock,
+ order_updated_webhook_mock,
+ )
+ removed_items_event = OrderEvent.objects.last() # type: OrderEvent
+ assert removed_items_event.type == order_events.OrderEvents.REMOVED_PRODUCTS
+ assert removed_items_event.app == app_api_client.app
+ assert removed_items_event.user is None
+
+
@pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
def test_order_line_update_without_sku(
status,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
staff_user,
):
@@ -261,7 +331,7 @@ def test_order_line_update_without_sku(
assert_no_permission(response)
# assign permissions
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderLineUpdate"]
@@ -296,16 +366,15 @@ def test_invalid_order_when_updating_lines(
draft_order_update_webhook_mock,
order_with_lines,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
query = ORDER_LINE_UPDATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
line = order.lines.first()
line_id = graphene.Node.to_global_id("OrderLine", line.id)
variables = {"lineId": line_id, "quantity": 1}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderLineUpdate"]
assert data["errors"]
diff --git a/saleor/graphql/order/tests/mutations/test_order_lines_create.py b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
index a00a8a761a..2f60f25c75 100644
--- a/saleor/graphql/order/tests/mutations/test_order_lines_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
@@ -66,7 +66,7 @@ ORDER_LINES_CREATE_MUTATION = """
def test_order_lines_create_with_out_of_stock_webhook(
product_variant_out_of_stock_webhook_mock,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
query = ORDER_LINES_CREATE_MUTATION
@@ -80,7 +80,7 @@ def test_order_lines_create_with_out_of_stock_webhook(
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
staff_api_client.post_graphql(query, variables)
quantity_allocated = Allocation.objects.aggregate(Sum("quantity_allocated"))[
@@ -99,7 +99,7 @@ def test_order_lines_create_with_out_of_stock_webhook(
def test_order_lines_create_for_variant_with_many_stocks_with_out_of_stock_webhook(
product_variant_out_of_stock_webhook_mock,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
variant_with_many_stocks,
):
@@ -113,7 +113,7 @@ def test_order_lines_create_for_variant_with_many_stocks_with_out_of_stock_webho
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
staff_api_client.post_graphql(query, variables)
product_variant_out_of_stock_webhook_mock.assert_called_once_with(
Stock.objects.all()[3]
@@ -130,7 +130,7 @@ def test_order_lines_create(
draft_order_updated_webhook_mock,
status,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
variant_with_many_stocks,
):
@@ -152,7 +152,7 @@ def test_order_lines_create(
assert not OrderEvent.objects.exists()
# assign permissions
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(query, variables)
assert_proper_webhook_called_once(
order, status, draft_order_updated_webhook_mock, order_updated_webhook_mock
@@ -183,6 +183,86 @@ def test_order_lines_create(
product_variant_out_of_stock_webhook_mock.assert_not_called()
+def test_order_lines_create_by_user_no_channel_access(
+ order_with_lines,
+ permission_group_all_perms_channel_USD_only,
+ staff_api_client,
+ variant_with_many_stocks,
+ channel_PLN,
+):
+ # given
+ query = ORDER_LINES_CREATE_MUTATION
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ order = order_with_lines
+ order.channel = channel_PLN
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status", "channel"])
+
+ variant = variant_with_many_stocks
+ quantity = 1
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+def test_order_lines_create_by_app(
+ order_updated_webhook_mock,
+ draft_order_updated_webhook_mock,
+ order_with_lines,
+ permission_manage_orders,
+ app_api_client,
+ variant_with_many_stocks,
+ channel_PLN,
+):
+ # given
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status"])
+ variant = variant_with_many_stocks
+ quantity = 1
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderLinesCreate"]
+ assert data["orderLines"][0]["productSku"] == variant.sku
+ assert data["orderLines"][0]["productVariantId"] == variant.get_global_id()
+ assert data["orderLines"][0]["quantity"] == quantity
+
+ assert OrderEvent.objects.count() == 1
+ event = OrderEvent.objects.last()
+ assert event.type == order_events.OrderEvents.ADDED_PRODUCTS
+ assert len(event.parameters["lines"]) == 1
+ line = OrderLine.objects.last()
+ assert event.parameters["lines"] == [
+ {"item": str(line), "line_pk": str(line.pk), "quantity": quantity}
+ ]
+ assert_proper_webhook_called_once(
+ order,
+ OrderStatus.UNCONFIRMED,
+ draft_order_updated_webhook_mock,
+ order_updated_webhook_mock,
+ )
+
+
@pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@@ -193,7 +273,7 @@ def test_order_lines_create_for_just_published_product(
draft_order_updated_webhook_mock,
status,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
variant_with_many_stocks,
):
@@ -210,7 +290,7 @@ def test_order_lines_create_for_just_published_product(
quantity = 1
order_id = graphene.Node.to_global_id("Order", order.id)
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}
# when
@@ -235,10 +315,11 @@ def test_order_lines_create_with_unavailable_variant(
order_updated_webhook_mock,
draft_order_updated_webhoook_mock,
draft_order,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
query = ORDER_LINES_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
channel = order.channel
line = order.lines.first()
@@ -249,9 +330,7 @@ def test_order_lines_create_with_unavailable_variant(
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
error = content["data"]["orderLinesCreate"]["errors"][0]
assert error["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name
@@ -269,7 +348,7 @@ def test_order_lines_create_with_existing_variant(
draft_order_updated_webhook_mock,
status,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
query = ORDER_LINES_CREATE_MUTATION
@@ -292,7 +371,7 @@ def test_order_lines_create_with_existing_variant(
draft_order_updated_webhook_mock.assert_not_called()
# assign permissions
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(query, variables)
assert OrderEvent.objects.count() == 1
assert OrderEvent.objects.last().type == order_events.OrderEvents.ADDED_PRODUCTS
@@ -314,7 +393,7 @@ def test_order_lines_create_with_same_variant_and_force_new_line(
draft_order_updated_webhook_mock,
status,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
query = ORDER_LINES_CREATE_MUTATION
@@ -344,7 +423,7 @@ def test_order_lines_create_with_same_variant_and_force_new_line(
draft_order_updated_webhook_mock.assert_not_called()
# assign permissions
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(query, variables)
assert order.lines.count() == 3
@@ -368,7 +447,7 @@ def test_order_lines_create_when_variant_already_in_multiple_lines(
draft_order_updated_webhook_mock,
status,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
order = order_with_lines
@@ -395,7 +474,7 @@ def test_order_lines_create_when_variant_already_in_multiple_lines(
}
# assign permissions
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDER_LINES_CREATE_MUTATION, variables)
@@ -420,7 +499,7 @@ def test_order_lines_create_variant_on_sale(
draft_order_updated_webhook_mock,
status,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
variant_with_many_stocks,
sale,
@@ -440,7 +519,7 @@ def test_order_lines_create_variant_on_sale(
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(query, variables)
@@ -486,11 +565,12 @@ def test_order_lines_create_with_product_and_variant_not_assigned_to_channel(
draft_order_updated_webhook_mock,
status,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
variant,
):
query = ORDER_LINES_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.status = status
order.save(update_fields=["status"])
@@ -502,9 +582,7 @@ def test_order_lines_create_with_product_and_variant_not_assigned_to_channel(
variant.product.channel_listings.all().delete()
variant.channel_listings.all().delete()
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
error = content["data"]["orderLinesCreate"]["errors"][0]
assert error["code"] == OrderErrorCode.PRODUCT_NOT_PUBLISHED.name
@@ -523,7 +601,7 @@ def test_order_lines_create_with_variant_not_assigned_to_channel(
status,
order_with_lines,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
shipping_method,
variant,
@@ -531,6 +609,7 @@ def test_order_lines_create_with_variant_not_assigned_to_channel(
graphql_address_data,
):
query = ORDER_LINES_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.status = status
order.save(update_fields=["status"])
@@ -541,9 +620,7 @@ def test_order_lines_create_with_variant_not_assigned_to_channel(
variables = {"orderId": order_id, "variantId": variant_id, "quantity": 1}
variant.channel_listings.all().delete()
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
error = content["data"]["orderLinesCreate"]["errors"][0]
assert error["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name
@@ -559,7 +636,7 @@ def test_order_lines_create_without_sku(
product_variant_out_of_stock_webhook_mock,
status,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
variant_with_many_stocks,
):
@@ -582,7 +659,7 @@ def test_order_lines_create_without_sku(
assert not OrderEvent.objects.exists()
# assign permissions
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(query, variables)
assert OrderEvent.objects.count() == 1
assert OrderEvent.objects.last().type == order_events.OrderEvents.ADDED_PRODUCTS
@@ -610,18 +687,17 @@ def test_invalid_order_when_creating_lines(
draft_order_updated_webhook_mock,
order_with_lines,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
query = ORDER_LINES_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
line = order.lines.first()
variant = line.variant
order_id = graphene.Node.to_global_id("Order", order.id)
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
variables = {"orderId": order_id, "variantId": variant_id, "quantity": 1}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderLinesCreate"]
assert data["errors"]
diff --git a/saleor/graphql/order/tests/mutations/test_order_mark_as_paid.py b/saleor/graphql/order/tests/mutations/test_order_mark_as_paid.py
index 0747e37b52..acab14f4d7 100644
--- a/saleor/graphql/order/tests/mutations/test_order_mark_as_paid.py
+++ b/saleor/graphql/order/tests/mutations/test_order_mark_as_paid.py
@@ -7,9 +7,9 @@ from .....order import OrderStatus
from .....order import events as order_events
from .....order.error_codes import OrderErrorCode
from .....payment import TransactionEventType
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
-MUTATION_MARK_ORDER_AS_PAID = """
+MARK_ORDER_AS_PAID_MUTATION = """
mutation markPaid($id: ID!, $transaction: String) {
orderMarkAsPaid(id: $id, transactionReference: $transaction) {
errors {
@@ -33,15 +33,14 @@ MUTATION_MARK_ORDER_AS_PAID = """
def test_paid_order_mark_as_paid_with_payment(
- staff_api_client, permission_manage_orders, payment_txn_preauth
+ staff_api_client, permission_group_manage_orders, payment_txn_preauth
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = payment_txn_preauth.order
- query = MUTATION_MARK_ORDER_AS_PAID
+ query = MARK_ORDER_AS_PAID_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
errors = content["data"]["orderMarkAsPaid"]["errors"]
msg = "Orders with payments can not be manually marked as paid."
@@ -53,17 +52,16 @@ def test_paid_order_mark_as_paid_with_payment(
def test_order_mark_as_paid_with_external_reference_with_payment(
- staff_api_client, permission_manage_orders, order_with_lines, staff_user
+ staff_api_client, permission_group_manage_orders, order_with_lines, staff_user
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
transaction_reference = "searchable-id"
order = order_with_lines
- query = MUTATION_MARK_ORDER_AS_PAID
+ query = MARK_ORDER_AS_PAID_MUTATION
assert not order.is_fully_paid()
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id, "transaction": transaction_reference}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderMarkAsPaid"]["order"]
@@ -88,26 +86,25 @@ def test_order_mark_as_paid_with_external_reference_with_payment(
def test_order_mark_as_paid_with_payment(
order_mark_as_paid_strategy,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
staff_user,
):
# given
order = order_with_lines
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
channel = order.channel
channel.order_mark_as_paid_strategy = order_mark_as_paid_strategy
channel.save(update_fields=["order_mark_as_paid_strategy"])
- query = MUTATION_MARK_ORDER_AS_PAID
+ query = MARK_ORDER_AS_PAID_MUTATION
assert not order.is_fully_paid()
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
# then
content = get_graphql_content(response)
@@ -120,6 +117,63 @@ def test_order_mark_as_paid_with_payment(
assert event_order_paid.user == staff_user
+def test_paid_order_mark_as_paid_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ order_with_lines,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = order_with_lines
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ query = MARK_ORDER_AS_PAID_MUTATION
+
+ assert not order.is_fully_paid()
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ query = MARK_ORDER_AS_PAID_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_order_mark_as_paid_by_app(
+ app_api_client, permission_manage_orders, order_with_lines
+):
+ # given
+ order = order_with_lines
+ query = MARK_ORDER_AS_PAID_MUTATION
+ assert not order.is_fully_paid()
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderMarkAsPaid"]["order"]
+ order.refresh_from_db()
+ assert data["isPaid"] is True is order.is_fully_paid()
+
+ event_order_paid = order.events.first()
+ assert event_order_paid.type == order_events.OrderEvents.ORDER_MARKED_AS_PAID
+ assert event_order_paid.user is None
+ assert event_order_paid.app == app_api_client.app
+
+
@pytest.mark.parametrize(
"order_mark_as_paid_strategy",
[MarkAsPaidStrategy.TRANSACTION_FLOW, MarkAsPaidStrategy.PAYMENT_FLOW],
@@ -127,11 +181,12 @@ def test_order_mark_as_paid_with_payment(
def test_order_mark_as_paid_no_billing_address_with_payment(
order_mark_as_paid_strategy,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
staff_user,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order_with_lines.billing_address = None
order_with_lines.save()
@@ -140,14 +195,12 @@ def test_order_mark_as_paid_no_billing_address_with_payment(
channel.order_mark_as_paid_strategy = order_mark_as_paid_strategy
channel.save(update_fields=["order_mark_as_paid_strategy"])
- query = MUTATION_MARK_ORDER_AS_PAID
+ query = MARK_ORDER_AS_PAID_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
# then
content = get_graphql_content(response)
@@ -156,9 +209,10 @@ def test_order_mark_as_paid_no_billing_address_with_payment(
def test_draft_order_mark_as_paid_check_price_recalculation_with_payment(
- staff_api_client, permission_manage_orders, order_with_lines, staff_user
+ staff_api_client, permission_group_manage_orders, order_with_lines, staff_user
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
# we need to change order total and set it as invalidated prices.
# we couldn't use `order.total.gross` because this test don't use any tax app
@@ -169,14 +223,12 @@ def test_draft_order_mark_as_paid_check_price_recalculation_with_payment(
order.should_refresh_prices = True
order.status = OrderStatus.DRAFT
order.save()
- query = MUTATION_MARK_ORDER_AS_PAID
+ query = MARK_ORDER_AS_PAID_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
@@ -192,9 +244,10 @@ def test_draft_order_mark_as_paid_check_price_recalculation_with_payment(
def test_paid_order_mark_as_paid_with_transaction(
- staff_api_client, permission_manage_orders, order_with_lines
+ staff_api_client, permission_group_manage_orders, order_with_lines
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
channel = order.channel
channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
@@ -202,14 +255,12 @@ def test_paid_order_mark_as_paid_with_transaction(
order.payment_transactions.create(charged_value=order.total.gross.amount)
- query = MUTATION_MARK_ORDER_AS_PAID
+ query = MARK_ORDER_AS_PAID_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
# then
content = get_graphql_content(response)
@@ -223,24 +274,23 @@ def test_paid_order_mark_as_paid_with_transaction(
def test_order_mark_as_paid_with_external_reference_with_transaction(
- staff_api_client, permission_manage_orders, order_with_lines, staff_user
+ staff_api_client, permission_group_manage_orders, order_with_lines, staff_user
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
channel = order.channel
channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
channel.save(update_fields=["order_mark_as_paid_strategy"])
transaction_reference = "searchable-id"
- query = MUTATION_MARK_ORDER_AS_PAID
+ query = MARK_ORDER_AS_PAID_MUTATION
assert not order.is_fully_paid()
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id, "transaction": transaction_reference}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
# then
content = get_graphql_content(response)
@@ -263,22 +313,21 @@ def test_order_mark_as_paid_with_external_reference_with_transaction(
def test_order_mark_as_paid_with_transaction_creates_transaction_event(
- staff_api_client, permission_manage_orders, order_with_lines, staff_user
+ staff_api_client, permission_group_manage_orders, order_with_lines
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
channel = order.channel
channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
channel.save(update_fields=["order_mark_as_paid_strategy"])
- query = MUTATION_MARK_ORDER_AS_PAID
+ query = MARK_ORDER_AS_PAID_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
# then
get_graphql_content(response)
@@ -293,9 +342,10 @@ def test_order_mark_as_paid_with_transaction_creates_transaction_event(
def test_draft_order_mark_as_paid_check_price_recalculation_transaction(
- staff_api_client, permission_manage_orders, order_with_lines, staff_user
+ staff_api_client, permission_group_manage_orders, order_with_lines, staff_user
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
# we need to change order total and set it as invalidated prices.
# we couldn't use `order.total.gross` because this test don't use any tax app
@@ -311,14 +361,12 @@ def test_draft_order_mark_as_paid_check_price_recalculation_transaction(
channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
channel.save(update_fields=["order_mark_as_paid_strategy"])
- query = MUTATION_MARK_ORDER_AS_PAID
+ query = MARK_ORDER_AS_PAID_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
diff --git a/saleor/graphql/order/tests/mutations/test_order_price_expiration.py b/saleor/graphql/order/tests/mutations/test_order_price_expiration.py
index 1c84ffe081..13d3db4865 100644
--- a/saleor/graphql/order/tests/mutations/test_order_price_expiration.py
+++ b/saleor/graphql/order/tests/mutations/test_order_price_expiration.py
@@ -39,12 +39,13 @@ def order_with_lines(order_with_lines):
def test_draft_order_update_shipping_address_invalidate_prices(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
draft_order,
voucher,
graphql_address_data,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = DRAFT_ORDER_UPDATE_MUTATION
variables = {
"id": Node.to_global_id("Order", draft_order.id),
@@ -53,11 +54,7 @@ def test_draft_order_update_shipping_address_invalidate_prices(
}
# when
- content = get_graphql_content(
- staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
- )
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
# then
assert not content["data"]["draftOrderUpdate"]["errors"]
@@ -67,12 +64,13 @@ def test_draft_order_update_shipping_address_invalidate_prices(
def test_draft_order_update_billing_address_invalidate_prices(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
draft_order,
voucher,
graphql_address_data,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = DRAFT_ORDER_UPDATE_MUTATION
variables = {
"id": Node.to_global_id("Order", draft_order.id),
@@ -81,11 +79,7 @@ def test_draft_order_update_billing_address_invalidate_prices(
}
# when
- content = get_graphql_content(
- staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
- )
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
# then
assert not content["data"]["draftOrderUpdate"]["errors"]
@@ -122,11 +116,12 @@ mutation orderUpdate(
def test_order_update_shipping_address_invalidate_prices(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
graphql_address_data,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.user = None
order.save()
@@ -137,11 +132,7 @@ def test_order_update_shipping_address_invalidate_prices(
}
# when
- content = get_graphql_content(
- staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
- )
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
# then
assert not content["data"]["orderUpdate"]["errors"]
@@ -151,11 +142,12 @@ def test_order_update_shipping_address_invalidate_prices(
def test_order_update_billing_address_invalidate_prices(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
graphql_address_data,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.user = None
order.save()
@@ -166,11 +158,7 @@ def test_order_update_billing_address_invalidate_prices(
}
# when
- content = get_graphql_content(
- staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
- )
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
# then
assert not content["data"]["orderUpdate"]["errors"]
@@ -204,10 +192,11 @@ mutation OrderLinesCreate(
def test_order_lines_create_invalidate_prices(
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = ORDER_LINES_CREATE_MUTATION
order = order_with_lines
line = order.lines.first()
@@ -219,11 +208,7 @@ def test_order_lines_create_invalidate_prices(
}
# when
- content = get_graphql_content(
- staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
- )
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
# then
assert not content["data"]["orderLinesCreate"]["errors"]
@@ -253,22 +238,19 @@ mutation OrderLineUpdate(
def test_order_line_update_invalidate_prices(
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
staff_user,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = ORDER_LINE_UPDATE_MUTATION
order = order_with_lines
line = order.lines.first()
variables = {"lineId": Node.to_global_id("OrderLine", line.id), "quantity": 1}
# when
- content = get_graphql_content(
- staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
- )
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
# then
assert not content["data"]["orderLineUpdate"]["errors"]
@@ -293,20 +275,17 @@ mutation OrderLineDelete(
def test_order_line_remove(
- order_with_lines, permission_manage_orders, staff_api_client
+ order_with_lines, permission_group_manage_orders, staff_api_client
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
line = order.lines.first()
query = ORDER_LINE_DELETE_MUTATION
variables = {"id": Node.to_global_id("OrderLine", line.id)}
# when
- content = get_graphql_content(
- staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
- )
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
# then
assert not content["data"]["orderLineDelete"]["errors"]
diff --git a/saleor/graphql/order/tests/mutations/test_order_refund.py b/saleor/graphql/order/tests/mutations/test_order_refund.py
index 5c47c6593f..c9e8e38237 100644
--- a/saleor/graphql/order/tests/mutations/test_order_refund.py
+++ b/saleor/graphql/order/tests/mutations/test_order_refund.py
@@ -9,7 +9,7 @@ from .....order.error_codes import OrderErrorCode
from .....payment import ChargeStatus
from .....tests.utils import flush_post_commit_hooks
from ....payment.types import PaymentChargeStatusEnum
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
ORDER_REFUND_MUTATION = """
mutation refundOrder($id: ID!, $amount: PositiveDecimal!) {
@@ -37,20 +37,19 @@ def test_order_refund(
mock_order_refunded,
mock_order_updated,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
payment_txn_captured,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = payment_txn_captured.order
query = ORDER_REFUND_MUTATION
- order_id = graphene.Node.to_global_id("Order", order.id)
amount = Decimal(10)
+ order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id, "amount": amount}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
# then
content = get_graphql_content(response)
@@ -91,10 +90,11 @@ def test_order_fully_refunded(
mock_order_refunded,
mock_order_updated,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
payment_txn_captured,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = payment_txn_captured.order
payment_txn_captured.total = order.total.gross.amount
payment_txn_captured.captured_amount = payment_txn_captured.total
@@ -106,8 +106,81 @@ def test_order_fully_refunded(
variables = {"id": order_id, "amount": amount}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderRefund"]["order"]
+ order.refresh_from_db()
+ assert data["status"] == order.status.upper()
+ assert data["paymentStatus"] == PaymentChargeStatusEnum.FULLY_REFUNDED.name
+ payment_status_display = dict(ChargeStatus.CHOICES).get(ChargeStatus.FULLY_REFUNDED)
+ assert data["paymentStatusDisplay"] == payment_status_display
+ assert data["isPaid"] is False
+
+ refund_order_event = order.events.filter(
+ type=order_events.OrderEvents.PAYMENT_REFUNDED
+ ).first()
+ assert refund_order_event.parameters["amount"] == str(amount)
+
+ refunded_fulfillment = order.fulfillments.filter(
+ status=FulfillmentStatus.REFUNDED
+ ).first()
+ assert refunded_fulfillment
+ assert refunded_fulfillment.total_refund_amount == payment_txn_captured.total
+ assert refunded_fulfillment.shipping_refund_amount is None
+
+ flush_post_commit_hooks()
+ mock_order_updated.assert_called_once_with(order)
+ mock_order_refunded.assert_called_once_with(order)
+ mock_order_fully_refunded.assert_called_once_with(order)
+
+
+def test_order_refund_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ payment_txn_captured,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = payment_txn_captured.order
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ query = ORDER_REFUND_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ amount = float(payment_txn_captured.total)
+ variables = {"id": order_id, "amount": amount}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+def test_order_refund_by_app(
+ mock_order_fully_refunded,
+ mock_order_refunded,
+ mock_order_updated,
+ app_api_client,
+ permission_manage_orders,
+ payment_txn_captured,
+):
+ # given
+ order = payment_txn_captured.order
+ query = ORDER_REFUND_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ amount = float(payment_txn_captured.total)
+ variables = {"id": order_id, "amount": amount}
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_orders,)
)
# then
@@ -139,16 +212,15 @@ def test_order_fully_refunded(
def test_order_refund_with_gift_card_lines(
- staff_api_client, permission_manage_orders, gift_card_shippable_order_line
+ staff_api_client, permission_group_manage_orders, gift_card_shippable_order_line
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = gift_card_shippable_order_line.order
query = ORDER_REFUND_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id, "amount": 10.0}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderRefund"]
assert not data["order"]
diff --git a/saleor/graphql/order/tests/mutations/test_order_update.py b/saleor/graphql/order/tests/mutations/test_order_update.py
index 273c4c1b43..b971e5e25e 100644
--- a/saleor/graphql/order/tests/mutations/test_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_order_update.py
@@ -5,7 +5,7 @@ import graphene
from .....order import OrderStatus
from .....order.error_codes import OrderErrorCode
from .....product.models import ProductVariant
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
ORDER_UPDATE_MUTATION = """
mutation orderUpdate(
@@ -37,6 +37,91 @@ ORDER_UPDATE_MUTATION = """
def test_order_update(
order_updated_webhook_mock,
staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines,
+ graphql_address_data,
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = order_with_lines
+ order.user = None
+ order.save()
+ email = "[email protected]"
+ assert not order.user_email == email
+ assert not order.shipping_address.first_name == graphql_address_data["firstName"]
+ assert not order.billing_address.last_name == graphql_address_data["lastName"]
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ external_reference = "test-ext-ref"
+
+ variables = {
+ "id": order_id,
+ "email": email,
+ "address": graphql_address_data,
+ "externalReference": external_reference,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_UPDATE_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ assert not content["data"]["orderUpdate"]["errors"]
+ data = content["data"]["orderUpdate"]["order"]
+ assert data["userEmail"] == email
+ assert data["externalReference"] == external_reference
+
+ order.refresh_from_db()
+ order.shipping_address.refresh_from_db()
+ order.billing_address.refresh_from_db()
+ assert order.shipping_address.first_name == graphql_address_data["firstName"]
+ assert order.billing_address.last_name == graphql_address_data["lastName"]
+ assert order.user_email == email
+ assert order.user is None
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.external_reference == external_reference
+ order_updated_webhook_mock.assert_called_once_with(order)
+
+
+def test_order_update_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ order_with_lines,
+ graphql_address_data,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = order_with_lines
+
+ order.user = None
+ order.channel = channel_PLN
+ order.save(update_fields=["channel", "user"])
+
+ email = "[email protected]"
+ assert not order.user_email == email
+ assert not order.shipping_address.first_name == graphql_address_data["firstName"]
+ assert not order.billing_address.last_name == graphql_address_data["lastName"]
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ external_reference = "test-ext-ref"
+
+ variables = {
+ "id": order_id,
+ "email": email,
+ "address": graphql_address_data,
+ "externalReference": external_reference,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_UPDATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+def test_order_update_by_app(
+ order_updated_webhook_mock,
+ app_api_client,
permission_manage_orders,
order_with_lines,
graphql_address_data,
@@ -60,8 +145,8 @@ def test_order_update(
}
# when
- response = staff_api_client.post_graphql(
- ORDER_UPDATE_MUTATION, variables, permissions=[permission_manage_orders]
+ response = app_api_client.post_graphql(
+ ORDER_UPDATE_MUTATION, variables, permissions=(permission_manage_orders,)
)
content = get_graphql_content(response)
@@ -87,19 +172,18 @@ def test_order_update(
def test_order_update_with_draft_order(
order_updated_webhook_mock,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
draft_order,
graphql_address_data,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
order.user = None
order.save()
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id, "email": email, "address": graphql_address_data}
- response = staff_api_client.post_graphql(
- ORDER_UPDATE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(ORDER_UPDATE_MUTATION, variables)
content = get_graphql_content(response)
error = content["data"]["orderUpdate"]["errors"][0]
assert error["field"] == "id"
@@ -111,10 +195,11 @@ def test_order_update_with_draft_order(
def test_order_update_without_sku(
plugin_mock,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
graphql_address_data,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
ProductVariant.objects.update(sku=None)
order_with_lines.lines.update(product_sku=None)
@@ -127,9 +212,7 @@ def test_order_update_without_sku(
assert not order.billing_address.last_name == graphql_address_data["lastName"]
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id, "email": email, "address": graphql_address_data}
- response = staff_api_client.post_graphql(
- ORDER_UPDATE_MUTATION, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(ORDER_UPDATE_MUTATION, variables)
content = get_graphql_content(response)
assert not content["data"]["orderUpdate"]["errors"]
data = content["data"]["orderUpdate"]["order"]
@@ -147,8 +230,12 @@ def test_order_update_without_sku(
def test_order_update_anonymous_user_no_user_email(
- staff_api_client, order_with_lines, permission_manage_orders, graphql_address_data
+ staff_api_client,
+ order_with_lines,
+ permission_group_manage_orders,
+ graphql_address_data,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.user = None
order.save()
@@ -173,9 +260,7 @@ def test_order_update_anonymous_user_no_user_email(
last_name = "Test lname"
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id, "address": graphql_address_data}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
get_graphql_content(response)
order.refresh_from_db()
order.shipping_address.refresh_from_db()
@@ -189,9 +274,10 @@ def test_order_update_user_email_existing_user(
staff_api_client,
order_with_lines,
customer_user,
- permission_manage_orders,
+ permission_group_manage_orders,
graphql_address_data,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.user = None
order.save()
@@ -215,9 +301,7 @@ def test_order_update_user_email_existing_user(
email = customer_user.email
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id, "address": graphql_address_data, "email": email}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
assert not content["data"]["orderUpdate"]["errors"]
data = content["data"]["orderUpdate"]["order"]
@@ -261,9 +345,10 @@ ORDER_UPDATE_BY_EXTERNAL_REFERENCE = """
def test_order_update_by_external_reference(
- staff_api_client, permission_manage_orders, order, graphql_address_data
+ staff_api_client, permission_group_manage_orders, order, graphql_address_data
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = ORDER_UPDATE_BY_EXTERNAL_REFERENCE
ext_ref = "test-ext-ref"
@@ -277,9 +362,7 @@ def test_order_update_by_external_reference(
}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
@@ -296,9 +379,10 @@ def test_order_update_by_external_reference(
def test_order_update_by_both_id_and_external_reference(
- staff_api_client, permission_manage_orders
+ staff_api_client, permission_group_manage_orders
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = ORDER_UPDATE_BY_EXTERNAL_REFERENCE
variables = {
@@ -308,9 +392,7 @@ def test_order_update_by_both_id_and_external_reference(
}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
@@ -323,9 +405,10 @@ def test_order_update_by_both_id_and_external_reference(
def test_order_update_by_external_reference_not_existing(
- staff_api_client, permission_manage_orders, voucher_free_shipping
+ staff_api_client, permission_group_manage_orders, voucher_free_shipping
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = ORDER_UPDATE_BY_EXTERNAL_REFERENCE
ext_ref = "non-existing-ext-ref"
variables = {
@@ -334,9 +417,7 @@ def test_order_update_by_external_reference_not_existing(
}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
@@ -346,9 +427,10 @@ def test_order_update_by_external_reference_not_existing(
def test_order_update_with_non_unique_external_reference(
- staff_api_client, permission_manage_orders, order, order_list
+ staff_api_client, permission_group_manage_orders, order, order_list
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
query = ORDER_UPDATE_BY_EXTERNAL_REFERENCE
ext_ref = "test-ext-ref"
@@ -360,9 +442,7 @@ def test_order_update_with_non_unique_external_reference(
variables = {"id": order_id, "input": {"externalReference": ext_ref}}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
diff --git a/saleor/graphql/order/tests/mutations/test_order_update_shipping.py b/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
index feb032e05d..ad3e371a16 100644
--- a/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
+++ b/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
@@ -7,7 +7,7 @@ from prices import TaxedMoney
from .....core.taxes import zero_money, zero_taxed_money
from .....order import OrderStatus
from .....order.error_codes import OrderErrorCode
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
ORDER_UPDATE_SHIPPING_QUERY = """
mutation orderUpdateShipping($order: ID!, $shippingMethod: ID) {
@@ -35,11 +35,12 @@ ORDER_UPDATE_SHIPPING_QUERY = """
def test_order_update_shipping(
status,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
shipping_method,
staff_user,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.base_shipping_price = zero_money(order.currency)
order.status = status
@@ -50,9 +51,7 @@ def test_order_update_shipping(
order_id = graphene.Node.to_global_id("Order", order.id)
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
variables = {"order": order_id, "shippingMethod": method_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderUpdateShipping"]
assert data["order"]["id"] == order_id
@@ -79,15 +78,94 @@ def test_order_update_shipping(
)
+def test_order_update_shipping_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ order_with_lines,
+ shipping_method,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = order_with_lines
+ order.base_shipping_price = zero_money(order.currency)
+ order.status = OrderStatus.UNCONFIRMED
+ order.channel = channel_PLN
+ order.save(update_fields=["channel", "status"])
+ assert order.shipping_method != shipping_method
+
+ query = ORDER_UPDATE_SHIPPING_QUERY
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ variables = {"order": order_id, "shippingMethod": method_id}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_order_update_shipping_by_app(
+ app_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ shipping_method,
+):
+ # given
+ order = order_with_lines
+ order.base_shipping_price = zero_money(order.currency)
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status"])
+ assert order.shipping_method != shipping_method
+
+ query = ORDER_UPDATE_SHIPPING_QUERY
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ variables = {"order": order_id, "shippingMethod": method_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderUpdateShipping"]
+ assert data["order"]["id"] == order_id
+
+ order.refresh_from_db()
+ shipping_total = shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).get_total()
+ shipping_price = TaxedMoney(shipping_total, shipping_total)
+ assert order.status == OrderStatus.UNCONFIRMED
+ assert order.shipping_method == shipping_method
+ assert order.base_shipping_price == shipping_total
+ assert order.shipping_price_net == shipping_price.net
+ assert order.shipping_price_gross == shipping_price.gross
+ assert order.shipping_tax_rate == Decimal("0.0")
+ assert order.shipping_method_name == shipping_method.name
+
+ shipping_tax_class = shipping_method.tax_class
+ assert order.shipping_tax_rate is not None
+ assert order.shipping_tax_class == shipping_tax_class
+ assert order.shipping_tax_class_metadata == shipping_tax_class.metadata
+ assert (
+ order.shipping_tax_class_private_metadata == shipping_tax_class.private_metadata
+ )
+
+
@pytest.mark.parametrize("status", [OrderStatus.UNCONFIRMED, OrderStatus.DRAFT])
def test_order_update_shipping_no_shipping_method_channel_listings(
status,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
shipping_method,
staff_user,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.status = status
order.save()
@@ -97,9 +175,7 @@ def test_order_update_shipping_no_shipping_method_channel_listings(
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
shipping_method.channel_listings.all().delete()
variables = {"order": order_id, "shippingMethod": method_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderUpdateShipping"]
errors = data["errors"]
@@ -110,12 +186,13 @@ def test_order_update_shipping_no_shipping_method_channel_listings(
def test_order_update_shipping_tax_included(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
shipping_method,
staff_user,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.status = OrderStatus.UNCONFIRMED
order.save(update_fields=["status"])
@@ -136,9 +213,7 @@ def test_order_update_shipping_tax_included(
order_id = graphene.Node.to_global_id("Order", order.id)
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
variables = {"order": order_id, "shippingMethod": method_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
# then
content = get_graphql_content(response)
@@ -162,8 +237,9 @@ def test_order_update_shipping_tax_included(
def test_order_update_shipping_clear_shipping_method(
- staff_api_client, permission_manage_orders, order, staff_user, shipping_method
+ staff_api_client, permission_group_manage_orders, order, staff_user, shipping_method
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order.shipping_method = shipping_method
order.status = OrderStatus.UNCONFIRMED
order.save(update_fields=["status"])
@@ -180,9 +256,7 @@ def test_order_update_shipping_clear_shipping_method(
query = ORDER_UPDATE_SHIPPING_QUERY
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"order": order_id, "shippingMethod": None}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderUpdateShipping"]
assert data["order"]["id"] == order_id
@@ -199,8 +273,9 @@ def test_order_update_shipping_clear_shipping_method(
def test_order_update_shipping_shipping_required(
- staff_api_client, permission_manage_orders, order_with_lines, staff_user
+ staff_api_client, permission_group_manage_orders, order_with_lines, staff_user
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.status = OrderStatus.UNCONFIRMED
order.save(update_fields=["status"])
@@ -208,9 +283,7 @@ def test_order_update_shipping_shipping_required(
query = ORDER_UPDATE_SHIPPING_QUERY
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"order": order_id, "shippingMethod": None}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderUpdateShipping"]
assert data["errors"][0]["field"] == "shippingMethod"
@@ -233,11 +306,12 @@ def test_order_update_shipping_shipping_required(
def test_order_update_shipping_not_editable_order(
status,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
shipping_method,
staff_user,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.status = status
order.save()
@@ -246,9 +320,7 @@ def test_order_update_shipping_not_editable_order(
order_id = graphene.Node.to_global_id("Order", order.id)
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
variables = {"order": order_id, "shippingMethod": method_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderUpdateShipping"]
assert data["errors"][0]["field"] == "id"
@@ -257,11 +329,12 @@ def test_order_update_shipping_not_editable_order(
def test_order_update_shipping_no_shipping_address(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
shipping_method,
staff_user,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.status = OrderStatus.UNCONFIRMED
order.save(update_fields=["status"])
@@ -272,9 +345,7 @@ def test_order_update_shipping_no_shipping_address(
order_id = graphene.Node.to_global_id("Order", order.id)
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
variables = {"order": order_id, "shippingMethod": method_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderUpdateShipping"]
assert data["errors"][0]["field"] == "order"
@@ -285,11 +356,12 @@ def test_order_update_shipping_no_shipping_address(
def test_order_update_shipping_incorrect_shipping_method(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
shipping_method,
staff_user,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.status = OrderStatus.UNCONFIRMED
order.save(update_fields=["status"])
@@ -302,9 +374,7 @@ def test_order_update_shipping_incorrect_shipping_method(
order_id = graphene.Node.to_global_id("Order", order.id)
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
variables = {"order": order_id, "shippingMethod": method_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderUpdateShipping"]
assert data["errors"][0]["field"] == "shippingMethod"
@@ -315,11 +385,12 @@ def test_order_update_shipping_incorrect_shipping_method(
def test_order_update_shipping_shipping_zone_without_channels(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
shipping_method,
staff_user,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
order.status = OrderStatus.UNCONFIRMED
order.save(update_fields=["status"])
@@ -328,9 +399,7 @@ def test_order_update_shipping_shipping_zone_without_channels(
order_id = graphene.Node.to_global_id("Order", order.id)
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
variables = {"order": order_id, "shippingMethod": method_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderUpdateShipping"]
errors = data["errors"]
@@ -341,11 +410,12 @@ def test_order_update_shipping_shipping_zone_without_channels(
def test_order_update_shipping_excluded_shipping_method_postal_code(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_unconfirmed,
staff_user,
shipping_method_excluded_by_postal_code,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_unconfirmed
order.shipping_method = shipping_method_excluded_by_postal_code
shipping_total = shipping_method_excluded_by_postal_code.channel_listings.get(
@@ -363,9 +433,7 @@ def test_order_update_shipping_excluded_shipping_method_postal_code(
"ShippingMethod", shipping_method_excluded_by_postal_code.id
)
variables = {"order": order_id, "shippingMethod": method_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["orderUpdateShipping"]
assert data["errors"][0]["field"] == "shippingMethod"
@@ -375,9 +443,10 @@ def test_order_update_shipping_excluded_shipping_method_postal_code(
def test_draft_order_clear_shipping_method(
- staff_api_client, draft_order, permission_manage_orders
+ staff_api_client, draft_order, permission_group_manage_orders
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
assert draft_order.shipping_method
assert draft_order.base_shipping_price != zero_money(draft_order.currency)
assert draft_order.shipping_price != zero_taxed_money(draft_order.currency)
@@ -386,9 +455,7 @@ def test_draft_order_clear_shipping_method(
variables = {"order": order_id, "shippingMethod": None}
# when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
# then
@@ -430,17 +497,17 @@ mutation OrderUpdateShipping(
],
)
def test_order_shipping_update_mutation_return_error_for_empty_value(
- draft_order, permission_manage_orders, staff_api_client, input, response_msg
+ draft_order, permission_group_manage_orders, staff_api_client, input, response_msg
):
query = ORDER_UPDATE_SHIPPING_QUERY_WITH_TOTAL
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"orderId": order_id, "shippingMethod": input}
response = staff_api_client.post_graphql(
query,
variables,
- permissions=(permission_manage_orders,),
)
content = get_graphql_content(response)
data = content["data"]["orderUpdateShipping"]
@@ -450,18 +517,18 @@ def test_order_shipping_update_mutation_return_error_for_empty_value(
def test_order_shipping_update_mutation_properly_recalculate_total(
draft_order,
- permission_manage_orders,
+ permission_group_manage_orders,
staff_api_client,
):
query = ORDER_UPDATE_SHIPPING_QUERY_WITH_TOTAL
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"orderId": order_id, "shippingMethod": {"shippingMethod": None}}
response = staff_api_client.post_graphql(
query,
variables,
- permissions=(permission_manage_orders,),
)
content = get_graphql_content(response)
data = content["data"]["orderUpdateShipping"]
diff --git a/saleor/graphql/order/tests/mutations/test_order_void.py b/saleor/graphql/order/tests/mutations/test_order_void.py
index 2a142dbce9..2137c2e32c 100644
--- a/saleor/graphql/order/tests/mutations/test_order_void.py
+++ b/saleor/graphql/order/tests/mutations/test_order_void.py
@@ -7,7 +7,7 @@ from .....order.error_codes import OrderErrorCode
from .....payment import ChargeStatus
from .....plugins.manager import PluginsManager
from ....payment.types import PaymentChargeStatusEnum
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
ORDER_VOID = """
mutation voidOrder($id: ID!) {
@@ -31,14 +31,13 @@ ORDER_VOID = """
def test_order_void(
- staff_api_client, permission_manage_orders, payment_txn_preauth, staff_user
+ staff_api_client, permission_group_manage_orders, payment_txn_preauth, staff_user
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = payment_txn_preauth.order
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- ORDER_VOID, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(ORDER_VOID, variables)
content = get_graphql_content(response)
data = content["data"]["orderVoid"]["order"]
assert data["paymentStatus"] == PaymentChargeStatusEnum.NOT_CHARGED.name
@@ -50,18 +49,68 @@ def test_order_void(
order.refresh_from_db()
+def test_order_void_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ payment_txn_preauth,
+ staff_user,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ order = payment_txn_preauth.order
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_VOID, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_order_void_by_app(
+ app_api_client, permission_manage_orders, payment_txn_preauth
+):
+ # given
+ order = payment_txn_preauth.order
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ ORDER_VOID, variables, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderVoid"]["order"]
+ assert data["paymentStatus"] == PaymentChargeStatusEnum.NOT_CHARGED.name
+ payment_status_display = dict(ChargeStatus.CHOICES).get(ChargeStatus.NOT_CHARGED)
+ assert data["paymentStatusDisplay"] == payment_status_display
+ event_payment_voided = order.events.last()
+ assert event_payment_voided.type == order_events.OrderEvents.PAYMENT_VOIDED
+ assert event_payment_voided.user is None
+ assert event_payment_voided.app == app_api_client.app
+
+
@patch.object(PluginsManager, "void_payment")
def test_order_void_payment_error(
- mock_void_payment, staff_api_client, permission_manage_orders, payment_txn_preauth
+ mock_void_payment,
+ staff_api_client,
+ permission_group_manage_orders,
+ payment_txn_preauth,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
msg = "Oops! Something went wrong."
order = payment_txn_preauth.order
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
mock_void_payment.side_effect = ValueError(msg)
- response = staff_api_client.post_graphql(
- ORDER_VOID, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(ORDER_VOID, variables)
content = get_graphql_content(response)
errors = content["data"]["orderVoid"]["errors"]
assert errors[0]["field"] == "payment"
diff --git a/saleor/graphql/order/tests/queries/test_draft_order.py b/saleor/graphql/order/tests/queries/test_draft_order.py
index f9e680e055..2c1e8aec9a 100644
--- a/saleor/graphql/order/tests/queries/test_draft_order.py
+++ b/saleor/graphql/order/tests/queries/test_draft_order.py
@@ -1,22 +1,121 @@
-from .....order.models import Order
-from ....tests.utils import get_graphql_content
+import pytest
+from .....order.models import Order
+from ....tests.utils import assert_no_permission, get_graphql_content
-def test_draft_order_query(staff_api_client, permission_manage_orders, orders):
- query = """
+DRAFT_ORDER_QUERY = """
query DraftOrdersQuery {
draftOrders(first: 10) {
edges {
node {
id
+ number
}
}
}
}
- """
+"""
+
+
+def draft_orders_in_different_channels(
+ draft_order_list, channel_USD, channel_JPY, channel_PLN
+):
+ draft_order_list[0].channel = channel_USD
+ draft_order_list[1].channel = channel_JPY
+ draft_order_list[2].channel = channel_PLN
+
+ Order.objects.bulk_update(draft_order_list, ["channel"])
+ return draft_order_list
+
+
+def test_draft_order_query(
+ staff_api_client, permission_group_manage_orders, order, draft_order_list
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_QUERY)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- response = staff_api_client.post_graphql(query)
+ # then
edges = get_graphql_content(response)["data"]["draftOrders"]["edges"]
assert len(edges) == Order.objects.drafts().count()
+
+
+def test_query_draft_orders_by_user_with_access_to_all_channels(
+ staff_api_client,
+ permission_group_all_perms_all_channels,
+ draft_orders_in_different_channels,
+):
+ # given
+ permission_group_all_perms_all_channels.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_QUERY)
+
+ # then
+ edges = get_graphql_content(response)["data"]["draftOrders"]["edges"]
+
+ assert len(edges) == len(draft_orders_in_different_channels)
+
+
+def test_query_draft_orders_by_user_with_restricted_access_to_channels(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ draft_orders_in_different_channels,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_QUERY)
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["draftOrders"]["edges"]) == 1
+ assert content["data"]["draftOrders"]["edges"][0]["node"]["number"] == str(
+ draft_orders_in_different_channels[0].number
+ )
+
+
+def test_query_draft_orders_by_user_with_restricted_access_to_channels_no_acc_channels(
+ staff_api_client,
+ permission_group_all_perms_without_any_channel,
+ draft_orders_in_different_channels,
+):
+ # given
+ permission_group_all_perms_without_any_channel.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_QUERY)
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["draftOrders"]["edges"]) == 0
+
+
+def test_query_draft_orders_by_app(
+ app_api_client, permission_manage_orders, draft_orders_in_different_channels
+):
+ # when
+ response = app_api_client.post_graphql(
+ DRAFT_ORDER_QUERY, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ edges = get_graphql_content(response)["data"]["draftOrders"]["edges"]
+
+ assert len(edges) == len(draft_orders_in_different_channels)
+
+
+def test_query_draft_orders_by_customer(
+ user_api_client, draft_orders_in_different_channels
+):
+ # when
+ response = user_api_client.post_graphql(DRAFT_ORDER_QUERY)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py b/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py
index 32fd9d9602..747867a39d 100644
--- a/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py
+++ b/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py
@@ -37,11 +37,11 @@ def test_draft_orders_query_with_filter_search_by_number(
draft_orders_query_with_filter,
draft_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
update_order_search_vector(draft_order)
variables = {"filter": {"search": draft_order.number}}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(draft_orders_query_with_filter, variables)
content = get_graphql_content(response)
assert content["data"]["draftOrders"]["totalCount"] == 1
@@ -51,11 +51,11 @@ def test_draft_orders_query_with_filter_search_by_number_with_hash(
draft_orders_query_with_filter,
draft_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
update_order_search_vector(draft_order)
variables = {"filter": {"search": f"#{draft_order.number}"}}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(draft_orders_query_with_filter, variables)
content = get_graphql_content(response)
assert content["data"]["draftOrders"]["totalCount"] == 1
@@ -75,7 +75,7 @@ def test_draft_order_query_with_filter_customer_fields(
user_value,
draft_orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
channel_USD,
):
@@ -96,7 +96,7 @@ def test_draft_order_query_with_filter_customer_fields(
)
variables = {"filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(draft_orders_query_with_filter, variables)
content = get_graphql_content(response)
orders = content["data"]["draftOrders"]["edges"]
@@ -126,19 +126,19 @@ def test_draft_order_query_with_filter_customer_fields(
({"created": {"lte": None}}, 2),
],
)
-def test_draft_order_query_with_filter_created_(
+def test_draft_order_query_with_filter_created(
orders_filter,
count,
draft_orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
channel_USD,
):
Order.objects.create(status=OrderStatus.DRAFT, channel=channel_USD)
with freeze_time("2012-01-14"):
Order.objects.create(status=OrderStatus.DRAFT, channel=channel_USD)
variables = {"filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(draft_orders_query_with_filter, variables)
content = get_graphql_content(response)
orders = content["data"]["draftOrders"]["edges"]
@@ -164,7 +164,7 @@ def test_draft_orders_query_with_filter_search(
count,
draft_orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
channel_USD,
):
@@ -214,7 +214,7 @@ def test_draft_orders_query_with_filter_search(
variables = {"filter": draft_orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(draft_orders_query_with_filter, variables)
content = get_graphql_content(response)
assert content["data"]["draftOrders"]["totalCount"] == count
diff --git a/saleor/graphql/order/tests/queries/test_draft_order_with_sort.py b/saleor/graphql/order/tests/queries/test_draft_order_with_sort.py
index ddabf93fd4..d9fd232675 100644
--- a/saleor/graphql/order/tests/queries/test_draft_order_with_sort.py
+++ b/saleor/graphql/order/tests/queries/test_draft_order_with_sort.py
@@ -34,7 +34,7 @@ def test_query_draft_orders_with_sort(
draft_order_sort,
result_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
address,
channel_USD,
):
@@ -72,7 +72,7 @@ def test_query_draft_orders_with_sort(
)
)
variables = {"sort_by": draft_order_sort}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(QUERY_DRAFT_ORDER_WITH_SORT, variables)
content = get_graphql_content(response)
draft_orders = content["data"]["draftOrders"]["edges"]
diff --git a/saleor/graphql/order/tests/queries/test_order.py b/saleor/graphql/order/tests/queries/test_order.py
index 6002af94c9..bdc6b1279e 100644
--- a/saleor/graphql/order/tests/queries/test_order.py
+++ b/saleor/graphql/order/tests/queries/test_order.py
@@ -31,7 +31,7 @@ from ....tests.utils import (
get_graphql_content_from_response,
)
-ORDERS_QUERY = """
+ORDERS_FULL_QUERY = """
query OrdersQuery {
orders(first: 1) {
edges {
@@ -267,11 +267,11 @@ query OrdersQuery {
def test_order_query(
staff_api_client,
- permission_manage_orders,
- permission_manage_shipping,
fulfilled_order,
checkout,
shipping_zone,
+ permission_group_manage_orders,
+ permission_group_manage_shipping,
):
# given
order = fulfilled_order
@@ -289,11 +289,11 @@ def test_order_query(
order.shipping_method.save()
order.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ permission_group_manage_shipping.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(ORDERS_QUERY)
+ response = staff_api_client.post_graphql(ORDERS_FULL_QUERY)
content = get_graphql_content(response)
# then
@@ -380,20 +380,20 @@ def test_order_query(
def test_order_query_denormalized_shipping_tax_class_data(
staff_api_client,
- permission_manage_orders,
- permission_manage_shipping,
+ permission_group_manage_orders,
+ permission_group_manage_shipping,
fulfilled_order,
):
# given
order = fulfilled_order
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ permission_group_manage_shipping.user_set.add(staff_api_client.user)
shipping_tax_class = order.shipping_method.tax_class
assert shipping_tax_class
# when
shipping_tax_class.delete()
- response = staff_api_client.post_graphql(ORDERS_QUERY)
+ response = staff_api_client.post_graphql(ORDERS_FULL_QUERY)
content = get_graphql_content(response)
# then
@@ -420,8 +420,8 @@ def test_order_query_denormalized_shipping_tax_class_data(
def test_order_query_total_price_is_0(
staff_api_client,
- permission_manage_orders,
- permission_manage_shipping,
+ permission_group_manage_orders,
+ permission_group_manage_shipping,
fulfilled_order,
shipping_zone,
):
@@ -441,11 +441,11 @@ def test_order_query_total_price_is_0(
order.shipping_method.save()
order.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ permission_group_manage_shipping.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(ORDERS_QUERY)
+ response = staff_api_client.post_graphql(ORDERS_FULL_QUERY)
content = get_graphql_content(response)
# then
@@ -464,7 +464,7 @@ def test_order_query_total_price_is_0(
def test_order_query_shows_non_draft_orders(
- staff_api_client, permission_manage_orders, orders
+ staff_api_client, permission_group_manage_orders, orders
):
query = """
query OrdersQuery {
@@ -478,17 +478,14 @@ def test_order_query_shows_non_draft_orders(
}
"""
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(query)
edges = get_graphql_content(response)["data"]["orders"]["edges"]
assert len(edges) == Order.objects.non_draft().count()
-def test_orders_with_channel(
- staff_api_client, permission_manage_orders, orders, channel_USD
-):
- query = """
+QUERY_ORDERS_WITH_CHANNEL = """
query OrdersQuery($channel: String) {
orders(first: 10, channel: $channel) {
edges {
@@ -498,17 +495,46 @@ def test_orders_with_channel(
}
}
}
- """
+"""
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+def test_orders_with_channel(
+ staff_api_client, permission_group_manage_orders, orders, channel_USD
+):
+ # given
+ query = QUERY_ORDERS_WITH_CHANNEL
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"channel": channel_USD.slug}
+
+ # when
response = staff_api_client.post_graphql(query, variables)
+
+ # then
edges = get_graphql_content(response)["data"]["orders"]["edges"]
assert len(edges) == 3
-def test_orders_without_channel(staff_api_client, permission_manage_orders, orders):
+def test_orders_with_channel_no_access_to_channel(
+ staff_api_client, permission_group_all_perms_channel_USD_only, orders, channel_JPY
+):
+ # given
+ query = QUERY_ORDERS_WITH_CHANNEL
+
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ variables = {"channel": channel_JPY.slug}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_orders_without_channel(
+ staff_api_client, permission_group_manage_orders, orders
+):
query = """
query OrdersQuery {
orders(first: 10) {
@@ -521,7 +547,7 @@ def test_orders_without_channel(staff_api_client, permission_manage_orders, orde
}
"""
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(query)
edges = get_graphql_content(response)["data"]["orders"]["edges"]
@@ -562,8 +588,8 @@ def test_order_query_authorize_status(
total_charged,
expected_status,
staff_api_client,
- permission_manage_orders,
- permission_manage_shipping,
+ permission_group_manage_orders,
+ permission_group_manage_shipping,
fulfilled_order,
):
# given
@@ -573,11 +599,11 @@ def test_order_query_authorize_status(
update_order_authorize_status(fulfilled_order, Decimal(0))
fulfilled_order.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ permission_group_manage_shipping.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(ORDERS_QUERY)
+ response = staff_api_client.post_graphql(ORDERS_FULL_QUERY)
content = get_graphql_content(response)
# then
@@ -601,8 +627,8 @@ def test_order_query_charge_status(
total_charged,
expected_status,
staff_api_client,
- permission_manage_orders,
- permission_manage_shipping,
+ permission_group_manage_orders,
+ permission_group_manage_shipping,
fulfilled_order,
):
# given
@@ -612,11 +638,11 @@ def test_order_query_charge_status(
update_order_charge_status(fulfilled_order, Decimal(0))
fulfilled_order.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ permission_group_manage_shipping.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(ORDERS_QUERY)
+ response = staff_api_client.post_graphql(ORDERS_FULL_QUERY)
content = get_graphql_content(response)
# then
@@ -626,8 +652,8 @@ def test_order_query_charge_status(
def test_order_query_payment_status_with_total_fulfillment_refund_equal_to_order_total(
staff_api_client,
- permission_manage_orders,
- permission_manage_shipping,
+ permission_group_manage_orders,
+ permission_group_manage_shipping,
fulfilled_order,
):
# given
@@ -635,11 +661,11 @@ def test_order_query_payment_status_with_total_fulfillment_refund_equal_to_order
tracking_number="123", total_refund_amount=fulfilled_order.total.gross.amount
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ permission_group_manage_shipping.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(ORDERS_QUERY)
+ response = staff_api_client.post_graphql(ORDERS_FULL_QUERY)
content = get_graphql_content(response)
# then
@@ -649,8 +675,8 @@ def test_order_query_payment_status_with_total_fulfillment_refund_equal_to_order
def test_order_query_with_transactions_details(
staff_api_client,
- permission_manage_orders,
- permission_manage_shipping,
+ permission_group_manage_orders,
+ permission_group_manage_shipping,
fulfilled_order,
shipping_zone,
):
@@ -734,11 +760,11 @@ def test_order_query_with_transactions_details(
]
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ permission_group_manage_shipping.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(ORDERS_QUERY)
+ response = staff_api_client.post_graphql(ORDERS_FULL_QUERY)
content = get_graphql_content(response)
# then
@@ -771,8 +797,8 @@ def test_order_query_with_transactions_details(
def test_order_query_shipping_method_channel_listing_does_not_exist(
staff_api_client,
- permission_manage_orders,
- permission_manage_shipping,
+ permission_group_manage_orders,
+ permission_group_manage_shipping,
order_with_lines,
):
# given
@@ -785,11 +811,11 @@ def test_order_query_shipping_method_channel_listing_does_not_exist(
shipping_method=shipping_method, channel=order.channel
).delete()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ permission_group_manage_shipping.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(ORDERS_QUERY)
+ response = staff_api_client.post_graphql(ORDERS_FULL_QUERY)
content = get_graphql_content(response)
# then
@@ -799,8 +825,8 @@ def test_order_query_shipping_method_channel_listing_does_not_exist(
def test_order_query_external_shipping_method(
staff_api_client,
- permission_manage_orders,
- permission_manage_shipping,
+ permission_group_manage_orders,
+ permission_group_manage_shipping,
order_with_lines,
):
external_shipping_method_id = graphene.Node.to_global_id("app", "1:external123")
@@ -811,11 +837,11 @@ def test_order_query_external_shipping_method(
order.private_metadata = {PRIVATE_META_APP_SHIPPING_ID: external_shipping_method_id}
order.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ permission_group_manage_shipping.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(ORDERS_QUERY)
+ response = staff_api_client.post_graphql(ORDERS_FULL_QUERY)
content = get_graphql_content(response)
# then
@@ -829,8 +855,8 @@ def test_order_query_external_shipping_method(
def test_order_discounts_query(
staff_api_client,
- permission_manage_orders,
- permission_manage_shipping,
+ permission_group_manage_orders,
+ permission_group_manage_shipping,
draft_order_with_fixed_discount_order,
):
# given
@@ -840,11 +866,11 @@ def test_order_discounts_query(
discount = order.discounts.get()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ permission_group_manage_shipping.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(ORDERS_QUERY)
+ response = staff_api_client.post_graphql(ORDERS_FULL_QUERY)
content = get_graphql_content(response)
# then
@@ -862,8 +888,8 @@ def test_order_discounts_query(
def test_order_line_discount_query(
staff_api_client,
- permission_manage_orders,
- permission_manage_shipping,
+ permission_group_manage_orders,
+ permission_group_manage_shipping,
draft_order_with_fixed_discount_order,
):
# given
@@ -879,11 +905,11 @@ def test_order_line_discount_query(
line_with_discount_id = graphene.Node.to_global_id("OrderLine", line.pk)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ permission_group_manage_shipping.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(ORDERS_QUERY)
+ response = staff_api_client.post_graphql(ORDERS_FULL_QUERY)
content = get_graphql_content(response)
# then
@@ -922,8 +948,8 @@ def test_order_line_discount_query(
def test_order_query_in_pln_channel(
staff_api_client,
- permission_manage_orders,
- permission_manage_shipping,
+ permission_group_manage_orders,
+ permission_group_manage_shipping,
order_with_lines_channel_PLN,
shipping_zone,
channel_PLN,
@@ -931,11 +957,11 @@ def test_order_query_in_pln_channel(
# given
shipping_zone.channels.add(channel_PLN)
order = order_with_lines_channel_PLN
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ permission_group_manage_shipping.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(ORDERS_QUERY)
+ response = staff_api_client.post_graphql(ORDERS_FULL_QUERY)
content = get_graphql_content(response)
# then
@@ -983,8 +1009,9 @@ def test_order_query_in_pln_channel(
QUERY_ORDER_BY_ID = """
query OrderQuery($id: ID) {
order(id: $id) {
- number
id
+ number
+ status
}
}
"""
@@ -1019,7 +1046,7 @@ def test_query_order_as_app(app_api_client, order):
assert order_data["id"] == graphene.Node.to_global_id("Order", order.id)
-def test_staff_query_order_by_old_id(staff_api_client, order, permission_manage_orders):
+def test_staff_query_order_by_old_id(staff_api_client, order):
# given
order.use_old_id = True
order.save(update_fields=["use_old_id"])
@@ -1352,7 +1379,7 @@ def test_query_order_fields_by_old_id_app_no_perm(order, app_api_client):
def test_order_query_gift_cards(
- staff_api_client, permission_manage_orders, order_with_lines, gift_card
+ staff_api_client, permission_group_manage_orders, order_with_lines, gift_card
):
query = """
query OrderQuery($id: ID!) {
@@ -1371,7 +1398,7 @@ def test_order_query_gift_cards(
order_id = graphene.Node.to_global_id("Order", order_with_lines.id)
variables = {"id": order_id}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
gift_card_data = content["data"]["order"]["giftCards"][0]
@@ -1425,3 +1452,144 @@ def test_order_display_gross_prices_use_country_exception(
# then
assert data["displayGrossPrices"] == tax_country_config.display_gross_prices
+
+
+QUERY_ORDERS = """
+ query OrdersQuery {
+ orders(first: 10) {
+ edges {
+ node {
+ number
+ }
+ }
+ }
+ }
+"""
+
+
+def test_query_orders_by_user_with_access_to_all_channels(
+ order_list,
+ staff_api_client,
+ permission_group_all_perms_all_channels,
+ channel_PLN,
+ channel_JPY,
+ channel_USD,
+):
+ # given
+ user = staff_api_client.user
+ permission_group_all_perms_all_channels.user_set.add(user)
+
+ order_list[0].channel = channel_PLN
+ order_list[1].channel = channel_JPY
+ order_list[2].channel = channel_USD
+
+ Order.objects.bulk_update(order_list, ["channel"])
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_ORDERS)
+ content = get_graphql_content(response)
+
+ # then
+ assert len(content["data"]["orders"]["edges"]) == len(order_list)
+
+
+def test_query_orders_by_user_with_restricted_access_to_channels(
+ order_list,
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+ channel_JPY,
+ channel_USD,
+):
+ # given
+ user = staff_api_client.user
+ permission_group_all_perms_channel_USD_only.user_set.add(user)
+
+ order_list[0].channel = channel_PLN
+ order_list[1].channel = channel_JPY
+ order_list[2].channel = channel_USD
+
+ Order.objects.bulk_update(order_list, ["channel"])
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_ORDERS)
+ content = get_graphql_content(response)
+
+ # then
+ assert len(content["data"]["orders"]["edges"]) == 1
+ assert content["data"]["orders"]["edges"][0]["node"]["number"] == str(
+ order_list[2].number
+ )
+
+
+def test_query_orders_by_user_with_restricted_access_to_channels_no_acc_channels(
+ order_list,
+ staff_api_client,
+ permission_group_all_perms_without_any_channel,
+ channel_PLN,
+ channel_JPY,
+ channel_USD,
+):
+ """Ensure that query returns no orders when user has no accessible channels."""
+ # given
+ user = staff_api_client.user
+ permission_group_all_perms_without_any_channel.user_set.add(user)
+
+ order_list[0].channel = channel_PLN
+ order_list[1].channel = channel_JPY
+ order_list[2].channel = channel_USD
+
+ Order.objects.bulk_update(order_list, ["channel"])
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_ORDERS)
+ content = get_graphql_content(response)
+
+ # then
+ assert len(content["data"]["orders"]["edges"]) == 0
+
+
+def test_query_orders_by_app(
+ order_list,
+ app_api_client,
+ permission_manage_orders,
+ channel_PLN,
+ channel_JPY,
+ channel_USD,
+):
+ # given
+ order_list[0].channel = channel_PLN
+ order_list[1].channel = channel_JPY
+ order_list[2].channel = channel_USD
+
+ Order.objects.bulk_update(order_list, ["channel"])
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_ORDERS, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["orders"]["edges"]) == len(order_list)
+
+
+def test_query_orders_by_customer(
+ order_list,
+ user_api_client,
+ channel_PLN,
+ channel_JPY,
+ channel_USD,
+):
+ # given
+ order_list[0].channel = channel_PLN
+ order_list[1].channel = channel_JPY
+ order_list[2].channel = channel_USD
+
+ Order.objects.bulk_update(order_list, ["channel"])
+
+ # when
+ response = user_api_client.post_graphql(QUERY_ORDERS)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/order/tests/queries/test_order_amounts.py b/saleor/graphql/order/tests/queries/test_order_amounts.py
index 53b0c06959..b57d92ec06 100644
--- a/saleor/graphql/order/tests/queries/test_order_amounts.py
+++ b/saleor/graphql/order/tests/queries/test_order_amounts.py
@@ -111,7 +111,7 @@ query OrdersQuery {
def test_order_total_refunded_query_with_transactions_by_staff_user(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
):
# given
@@ -127,7 +127,7 @@ def test_order_total_refunded_query_with_transactions_by_staff_user(
currency=order.currency,
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
@@ -209,7 +209,10 @@ def test_order_total_refunded_query_with_transactions_by_app(
def test_order_total_refunded_query_with_payment_by_staff_user(
- staff_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines,
+ payment_txn_refunded,
):
# given
payment = payment_txn_refunded
@@ -224,7 +227,7 @@ def test_order_total_refunded_query_with_payment_by_staff_user(
refund_transaction.amount = second_refund_amount
refund_transaction.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
@@ -266,7 +269,7 @@ def test_order_total_refunded_query_with_payment_by_app(
def test_order_total_refund_pending_query_with_transactions_by_staff_user(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
):
# given
@@ -281,7 +284,7 @@ def test_order_total_refund_pending_query_with_transactions_by_staff_user(
refund_pending_value=second_pending_refund_amount, currency="USD"
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
@@ -353,14 +356,17 @@ def test_order_total_refund_pending_query_with_transactions_by_app(
def test_order_total_refund_pending_query_with_payment_by_staff_user(
- staff_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines,
+ payment_txn_refunded,
):
# given
payment = payment_txn_refunded
payment.is_active = True
payment.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
@@ -394,7 +400,7 @@ def test_order_total_refund_pending_query_with_payment_by_app(
def test_order_total_authorize_pending_query_with_transactions_by_staff_user(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
):
# given
@@ -409,7 +415,7 @@ def test_order_total_authorize_pending_query_with_transactions_by_staff_user(
authorize_pending_value=second_pending_authorize_amount, currency="USD"
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
@@ -481,14 +487,17 @@ def test_order_total_authorize_pending_query_with_transactions_by_app(
def test_order_total_authorize_pending_query_with_payment_by_staff_user(
- staff_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines,
+ payment_txn_refunded,
):
# given
payment = payment_txn_refunded
payment.is_active = True
payment.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
@@ -522,7 +531,7 @@ def test_order_total_authorize_pending_query_with_payment_by_app(
def test_order_total_charge_pending_query_with_transactions_by_staff_user(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
):
# given
@@ -537,7 +546,7 @@ def test_order_total_charge_pending_query_with_transactions_by_staff_user(
charge_pending_value=second_pending_charge_amount, currency="USD"
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
@@ -609,14 +618,17 @@ def test_order_total_charge_pending_query_with_transactions_by_app(
def test_order_total_charge_pending_query_with_payment_by_staff_user(
- staff_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines,
+ payment_txn_refunded,
):
# given
payment = payment_txn_refunded
payment.is_active = True
payment.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
@@ -650,7 +662,7 @@ def test_order_total_charge_pending_query_with_payment_by_app(
def test_order_total_cancel_pending_query_with_transactions_by_staff_user(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
):
# given
@@ -665,7 +677,7 @@ def test_order_total_cancel_pending_query_with_transactions_by_staff_user(
cancel_pending_value=second_pending_cancel_amount, currency="USD"
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
@@ -737,14 +749,17 @@ def test_order_total_cancel_pending_query_with_transactions_by_app(
def test_order_total_cancel_pending_query_with_payment_by_staff_user(
- staff_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines,
+ payment_txn_refunded,
):
# given
payment = payment_txn_refunded
payment.is_active = True
payment.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
@@ -777,7 +792,7 @@ def test_order_total_cancel_pending_query_with_payment_by_app(
def test_order_total_remaining_grant_query_with_transactions_by_staff_user(
- staff_api_client, permission_manage_orders, fulfilled_order, staff_user
+ staff_api_client, permission_group_manage_orders, fulfilled_order, staff_user
):
# given
order = fulfilled_order
@@ -796,7 +811,7 @@ def test_order_total_remaining_grant_query_with_transactions_by_staff_user(
)
order.payment_transactions.create(refunded_value=refund_amount, currency="USD")
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
@@ -870,7 +885,7 @@ def test_order_total_remaining_grant_query_with_transactions_by_app(
def test_order_total_remaining_grant_query_with_payment_by_staff_user(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
payment_txn_refunded,
staff_user,
@@ -895,7 +910,7 @@ def test_order_total_remaining_grant_query_with_payment_by_staff_user(
refund_transaction.amount = second_refund_amount
refund_transaction.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
diff --git a/saleor/graphql/order/tests/queries/test_order_entity.py b/saleor/graphql/order/tests/queries/test_order_entity.py
index d569fbd1f7..f3beb363b5 100644
--- a/saleor/graphql/order/tests/queries/test_order_entity.py
+++ b/saleor/graphql/order/tests/queries/test_order_entity.py
@@ -18,8 +18,10 @@ ORDER_FEDERATION_QUERY = """
def test_staff_query_order_by_id_for_federation(
- staff_api_client, fulfilled_order, permission_manage_orders
+ staff_api_client, fulfilled_order, permission_group_manage_orders
):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order_id = graphene.Node.to_global_id("Order", fulfilled_order.id)
variables = {
"representations": [
@@ -30,12 +32,14 @@ def test_staff_query_order_by_id_for_federation(
],
}
+ # when
response = staff_api_client.post_graphql(
ORDER_FEDERATION_QUERY,
variables,
- permissions=[permission_manage_orders],
check_no_permissions=False,
)
+
+ # then
content = get_graphql_content(response)
assert content["data"]["_entities"] == [
{
diff --git a/saleor/graphql/order/tests/queries/test_order_events.py b/saleor/graphql/order/tests/queries/test_order_events.py
index d6ee17e528..20e5f79a6f 100644
--- a/saleor/graphql/order/tests/queries/test_order_events.py
+++ b/saleor/graphql/order/tests/queries/test_order_events.py
@@ -51,7 +51,7 @@ ORDERS_FULFILLED_EVENTS = """
def test_nested_order_events_query(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
permission_manage_apps,
fulfilled_order,
fulfillment,
@@ -78,9 +78,8 @@ def test_nested_order_events_query(
)
event.save()
- staff_api_client.user.user_permissions.add(
- permission_manage_orders, permission_manage_apps
- )
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ staff_api_client.user.user_permissions.add(permission_manage_apps)
response = staff_api_client.post_graphql(query)
content = get_graphql_content(response)
data = content["data"]["orders"]["edges"][0]["node"]["events"][0]
@@ -110,7 +109,7 @@ def test_nested_order_events_query(
def test_nested_order_events_query_for_app(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
permission_manage_apps,
fulfilled_order,
fulfillment,
@@ -137,9 +136,8 @@ def test_nested_order_events_query_for_app(
)
event.save()
- staff_api_client.user.user_permissions.add(
- permission_manage_orders, permission_manage_apps
- )
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ staff_api_client.user.user_permissions.add(permission_manage_apps)
response = staff_api_client.post_graphql(query)
content = get_graphql_content(response)
data = content["data"]["orders"]["edges"][0]["node"]["events"][0]
@@ -190,7 +188,7 @@ ORDERS_WITH_EVENTS = """
def test_related_order_events_query(
- staff_api_client, permission_manage_orders, order, payment_dummy, staff_user
+ staff_api_client, permission_group_manage_orders, order, payment_dummy, staff_user
):
new_order = deepcopy(order)
new_order.id = None
@@ -203,7 +201,7 @@ def test_related_order_events_query(
original_order=order, replace_order=new_order, user=staff_user, app=None
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDERS_WITH_EVENTS)
content = get_graphql_content(response)
@@ -215,7 +213,7 @@ def test_related_order_events_query(
def test_related_order_events_query_for_app(
- staff_api_client, permission_manage_orders, order, payment_dummy, app
+ staff_api_client, permission_group_manage_orders, order, payment_dummy, app
):
new_order = deepcopy(order)
new_order.id = None
@@ -228,7 +226,7 @@ def test_related_order_events_query_for_app(
original_order=order, replace_order=new_order, user=None, app=app
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDERS_WITH_EVENTS)
content = get_graphql_content(response)
@@ -240,7 +238,7 @@ def test_related_order_events_query_for_app(
def test_related_order_eventes_old_order_id(
- staff_api_client, permission_manage_orders, order, payment_dummy, app
+ staff_api_client, permission_group_manage_orders, order, payment_dummy, app
):
# given
new_order = deepcopy(order)
@@ -259,7 +257,7 @@ def test_related_order_eventes_old_order_id(
parameters=parameters,
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_WITH_EVENTS)
@@ -276,7 +274,7 @@ def test_related_order_eventes_old_order_id(
def test_order_events_without_permission(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines_and_events,
customer_user,
):
@@ -284,7 +282,7 @@ def test_order_events_without_permission(
last_event.user = customer_user
last_event.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDERS_WITH_EVENTS)
content = get_graphql_content(response)
@@ -316,7 +314,7 @@ QUERY_GET_FIRST_EVENT = """
def test_retrieving_event_lines_with_deleted_line(
- staff_api_client, order_with_lines, staff_user, permission_manage_orders
+ staff_api_client, order_with_lines, staff_user, permission_group_manage_orders
):
order = order_with_lines
lines = order_with_lines.lines.all()
@@ -331,7 +329,7 @@ def test_retrieving_event_lines_with_deleted_line(
deleted_line.delete()
# Prepare the query
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Send the query and retrieve the data
content = get_graphql_content(staff_api_client.post_graphql(QUERY_GET_FIRST_EVENT))
@@ -355,7 +353,7 @@ def test_retrieving_event_lines_with_deleted_line(
def test_retrieving_event_lines_with_missing_line_pk_in_data(
- staff_api_client, order_with_lines, staff_user, permission_manage_orders
+ staff_api_client, order_with_lines, staff_user, permission_group_manage_orders
):
order = order_with_lines
line = order_with_lines.lines.first()
@@ -368,7 +366,7 @@ def test_retrieving_event_lines_with_missing_line_pk_in_data(
event.save(update_fields=["parameters"])
# Prepare the query
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# Send the query and retrieve the data
content = get_graphql_content(staff_api_client.post_graphql(QUERY_GET_FIRST_EVENT))
diff --git a/saleor/graphql/order/tests/queries/test_order_granted_refunds.py b/saleor/graphql/order/tests/queries/test_order_granted_refunds.py
index 3d15bdf1b2..70714b8c92 100644
--- a/saleor/graphql/order/tests/queries/test_order_granted_refunds.py
+++ b/saleor/graphql/order/tests/queries/test_order_granted_refunds.py
@@ -42,7 +42,7 @@ def test_order_granted_refunds_query_by_user(
staff_user,
app,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
permission_manage_shipping,
fulfilled_order,
shipping_zone,
@@ -66,7 +66,7 @@ def test_order_granted_refunds_query_by_user(
amount_value=Decimal("12.5"), currency="USD", reason="Test reason", app=app
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
staff_api_client.user.user_permissions.add(permission_manage_shipping)
# when
@@ -205,7 +205,7 @@ def test_order_total_granted_refund_query_by_staff_user(
staff_user,
app,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
shipping_zone,
):
@@ -226,7 +226,7 @@ def test_order_total_granted_refund_query_by_staff_user(
app=app,
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY)
diff --git a/saleor/graphql/order/tests/queries/test_order_invoices.py b/saleor/graphql/order/tests/queries/test_order_invoices.py
index 83b7285de7..1fd3cc3004 100644
--- a/saleor/graphql/order/tests/queries/test_order_invoices.py
+++ b/saleor/graphql/order/tests/queries/test_order_invoices.py
@@ -19,9 +19,9 @@ ORDERS_WITH_INVOICES_QUERY = """
def test_order_query_invoices(
- user_api_client, permission_manage_orders, fulfilled_order
+ user_api_client, permission_group_manage_orders, fulfilled_order
):
- user_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(user_api_client.user)
response = user_api_client.post_graphql(ORDERS_WITH_INVOICES_QUERY)
content = get_graphql_content(response)
edges = content["data"]["orders"]["edges"]
diff --git a/saleor/graphql/order/tests/queries/test_order_line.py b/saleor/graphql/order/tests/queries/test_order_line.py
index 8d9ec863ce..9f6fcc5b4e 100644
--- a/saleor/graphql/order/tests/queries/test_order_line.py
+++ b/saleor/graphql/order/tests/queries/test_order_line.py
@@ -10,7 +10,9 @@ from ....core.enums import ThumbnailFormatEnum
from ....tests.utils import get_graphql_content
-def test_order_line_query(staff_api_client, permission_manage_orders, fulfilled_order):
+def test_order_line_query(
+ staff_api_client, permission_group_manage_orders, fulfilled_order
+):
order = fulfilled_order
query = """
query OrdersQuery {
@@ -80,7 +82,7 @@ def test_order_line_query(staff_api_client, permission_manage_orders, fulfilled_
line.store_value_in_metadata({metadata_key: metadata_value})
line.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(query)
content = get_graphql_content(response)
order_data = content["data"]["orders"]["edges"][0]["node"]
@@ -145,7 +147,7 @@ def test_order_line_query(staff_api_client, permission_manage_orders, fulfilled_
def test_denormalized_tax_class_in_orderline_query(
- staff_api_client, permission_manage_orders, fulfilled_order
+ staff_api_client, permission_group_manage_orders, fulfilled_order
):
# given
order = fulfilled_order
@@ -209,7 +211,7 @@ def test_denormalized_tax_class_in_orderline_query(
}
"""
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
line_tax_class = order.lines.first().tax_class
assert line_tax_class
@@ -242,7 +244,7 @@ def test_denormalized_tax_class_in_orderline_query(
def test_order_line_with_allocations(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
):
# given
@@ -267,7 +269,7 @@ def test_order_line_with_allocations(
}
}
"""
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(query)
@@ -315,7 +317,7 @@ query OrderQuery($id: ID!) {
def test_query_order_line_stocks(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines_for_cc,
warehouse,
warehouse_for_cc,
@@ -325,14 +327,13 @@ def test_query_order_line_stocks(
order = order_with_lines_for_cc
variant = order.lines.first().variant
variables = {"id": graphene.Node.to_global_id("Order", order.id)}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# create the variant stock for not click and collect warehouse
Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=10)
# when
- response = staff_api_client.post_graphql(
- QUERY_ORDER_LINE_STOCKS, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(QUERY_ORDER_LINE_STOCKS, variables)
# then
content = get_graphql_content(response)
@@ -365,11 +366,11 @@ ORDERS_QUERY_LINE_THUMBNAIL = """
def test_order_query_no_thumbnail(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_line,
):
# given
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_LINE_THUMBNAIL)
@@ -383,7 +384,7 @@ def test_order_query_no_thumbnail(
def test_order_query_product_image_size_and_format_given_proxy_url_returned(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_line,
product_with_image,
site_settings,
@@ -397,7 +398,7 @@ def test_order_query_product_image_size_and_format_given_proxy_url_returned(
"format": format,
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_LINE_THUMBNAIL, variables)
@@ -416,7 +417,7 @@ def test_order_query_product_image_size_and_format_given_proxy_url_returned(
def test_order_query_product_image_size_given_proxy_url_returned(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_line,
product_with_image,
site_settings,
@@ -428,7 +429,7 @@ def test_order_query_product_image_size_given_proxy_url_returned(
"size": 120,
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_LINE_THUMBNAIL, variables)
@@ -446,7 +447,7 @@ def test_order_query_product_image_size_given_proxy_url_returned(
def test_order_query_product_image_size_given_thumbnail_url_returned(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_line,
product_with_image,
site_settings,
@@ -463,7 +464,7 @@ def test_order_query_product_image_size_given_thumbnail_url_returned(
"size": 120,
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_LINE_THUMBNAIL, variables)
@@ -480,7 +481,7 @@ def test_order_query_product_image_size_given_thumbnail_url_returned(
def test_order_query_variant_image_size_and_format_given_proxy_url_returned(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_line,
variant_with_image,
site_settings,
@@ -494,7 +495,7 @@ def test_order_query_variant_image_size_and_format_given_proxy_url_returned(
"format": format,
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_LINE_THUMBNAIL, variables)
@@ -513,7 +514,7 @@ def test_order_query_variant_image_size_and_format_given_proxy_url_returned(
def test_order_query_variant_image_size_given_proxy_url_returned(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_line,
variant_with_image,
site_settings,
@@ -525,7 +526,7 @@ def test_order_query_variant_image_size_given_proxy_url_returned(
"size": 120,
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_LINE_THUMBNAIL, variables)
@@ -543,7 +544,7 @@ def test_order_query_variant_image_size_given_proxy_url_returned(
def test_order_query_variant_image_size_given_thumbnail_url_returned(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_line,
variant_with_image,
site_settings,
@@ -560,7 +561,7 @@ def test_order_query_variant_image_size_given_thumbnail_url_returned(
"size": 120,
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDERS_QUERY_LINE_THUMBNAIL, variables)
@@ -595,11 +596,11 @@ QUERY_LINE_TAX_CLASS_QUERY = """
def test_order_line_tax_class_query_by_staff(
staff_api_client,
- permission_manage_orders,
+ permission_group_all_perms_all_channels,
order_line,
):
# given
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_all_perms_all_channels.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(QUERY_LINE_TAX_CLASS_QUERY)
diff --git a/saleor/graphql/order/tests/queries/test_order_payment_event.py b/saleor/graphql/order/tests/queries/test_order_payment_event.py
index 768eefeaf1..0318df94b7 100644
--- a/saleor/graphql/order/tests/queries/test_order_payment_event.py
+++ b/saleor/graphql/order/tests/queries/test_order_payment_event.py
@@ -38,7 +38,7 @@ ORDERS_PAYMENTS_EVENTS_QUERY = """
def test_payment_information_order_events_query(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
permission_manage_apps,
order,
payment_dummy,
@@ -52,9 +52,8 @@ def test_payment_information_order_events_query(
order=order, user=staff_user, app=None, amount=amount, payment=payment_dummy
)
- staff_api_client.user.user_permissions.add(
- permission_manage_orders, permission_manage_apps
- )
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ staff_api_client.user.user_permissions.add(permission_manage_apps)
response = staff_api_client.post_graphql(query)
content = get_graphql_content(response)
data = content["data"]["orders"]["edges"][0]["node"]["events"][0]
@@ -75,7 +74,7 @@ def test_payment_information_order_events_query(
def test_payment_information_order_events_query_for_app(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
permission_manage_apps,
order,
payment_dummy,
@@ -89,9 +88,8 @@ def test_payment_information_order_events_query_for_app(
order=order, user=None, app=app, amount=amount, payment=payment_dummy
)
- staff_api_client.user.user_permissions.add(
- permission_manage_orders, permission_manage_apps
- )
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ staff_api_client.user.user_permissions.add(permission_manage_apps)
response = staff_api_client.post_graphql(query)
content = get_graphql_content(response)
data = content["data"]["orders"]["edges"][0]["node"]["events"][0]
diff --git a/saleor/graphql/order/tests/queries/test_order_shipping_method.py b/saleor/graphql/order/tests/queries/test_order_shipping_method.py
index c9c9ee621a..813b222526 100644
--- a/saleor/graphql/order/tests/queries/test_order_shipping_method.py
+++ b/saleor/graphql/order/tests/queries/test_order_shipping_method.py
@@ -23,7 +23,7 @@ ORDERS_QUERY_SHIPPING_METHODS = """
def test_order_query_without_available_shipping_methods(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order,
shipping_method_channel_PLN,
channel_USD,
@@ -32,7 +32,7 @@ def test_order_query_without_available_shipping_methods(
order.shipping_method = shipping_method_channel_PLN
order.save()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDERS_QUERY_SHIPPING_METHODS)
content = get_graphql_content(response)
order_data = content["data"]["orders"]["edges"][0]["node"]
@@ -44,7 +44,7 @@ def test_order_available_shipping_methods_with_weight_based_shipping_method(
staff_api_client,
order_line,
shipping_method_weight_based,
- permission_manage_orders,
+ permission_group_manage_orders,
minimum_order_weight_value,
):
shipping_method = shipping_method_weight_based
@@ -59,7 +59,7 @@ def test_order_available_shipping_methods_with_weight_based_shipping_method(
shipping_method.save(update_fields=["minimum_order_weight"])
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDERS_QUERY_SHIPPING_METHODS)
content = get_graphql_content(response)
order_data = content["data"]["orders"]["edges"][0]["node"]
@@ -71,7 +71,10 @@ def test_order_available_shipping_methods_with_weight_based_shipping_method(
def test_order_available_shipping_methods_weight_method_with_higher_minimal_weigh(
- staff_api_client, order_line, shipping_method_weight_based, permission_manage_orders
+ staff_api_client,
+ order_line,
+ shipping_method_weight_based,
+ permission_group_manage_orders,
):
order = order_line.order
@@ -83,7 +86,7 @@ def test_order_available_shipping_methods_weight_method_with_higher_minimal_weig
order.weight = Weight(kg=1)
order.save(update_fields=["weight"])
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDERS_QUERY_SHIPPING_METHODS)
content = get_graphql_content(response)
order_data = content["data"]["orders"]["edges"][0]["node"]
@@ -96,11 +99,11 @@ def test_order_available_shipping_methods_weight_method_with_higher_minimal_weig
def test_order_query_shipping_zones_with_available_shipping_methods(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
shipping_zone,
):
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDERS_QUERY_SHIPPING_METHODS)
content = get_graphql_content(response)
order_data = content["data"]["orders"]["edges"][0]["node"]
@@ -109,13 +112,13 @@ def test_order_query_shipping_zones_with_available_shipping_methods(
def test_order_query_shipping_zones_without_channel(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
shipping_zone,
channel_USD,
):
channel_USD.shipping_zones.clear()
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDERS_QUERY_SHIPPING_METHODS)
content = get_graphql_content(response)
order_data = content["data"]["orders"]["edges"][0]["node"]
@@ -125,7 +128,7 @@ def test_order_query_shipping_zones_without_channel(
def test_order_query_shipping_methods_excluded_postal_codes(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines_channel_PLN,
channel_PLN,
):
@@ -134,7 +137,7 @@ def test_order_query_shipping_methods_excluded_postal_codes(
order.shipping_address.postal_code = "HB5"
order.shipping_address.save(update_fields=["postal_code"])
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDERS_QUERY_SHIPPING_METHODS)
content = get_graphql_content(response)
order_data = content["data"]["orders"]["edges"][0]["node"]
@@ -143,7 +146,7 @@ def test_order_query_shipping_methods_excluded_postal_codes(
def test_order_available_shipping_methods_query(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
fulfilled_order,
shipping_zone,
):
@@ -152,7 +155,7 @@ def test_order_available_shipping_methods_query(
channel_id=fulfilled_order.channel_id
).price
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(ORDERS_QUERY_SHIPPING_METHODS)
content = get_graphql_content(response)
order_data = content["data"]["orders"]["edges"][0]["node"]
diff --git a/saleor/graphql/order/tests/queries/test_order_total_balance.py b/saleor/graphql/order/tests/queries/test_order_total_balance.py
index e9a76846d2..6dbe0c48b2 100644
--- a/saleor/graphql/order/tests/queries/test_order_total_balance.py
+++ b/saleor/graphql/order/tests/queries/test_order_total_balance.py
@@ -23,7 +23,7 @@ query OrdersQuery {
def test_total_balance_only_charged(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
permission_manage_shipping,
fulfilled_order,
):
@@ -49,7 +49,7 @@ def test_total_balance_only_charged(
]
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
staff_api_client.user.user_permissions.add(permission_manage_shipping)
# when
@@ -70,7 +70,7 @@ def test_total_balance_only_charged(
def test_total_balance_charged_and_pending_charged(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
permission_manage_shipping,
fulfilled_order,
):
@@ -96,7 +96,7 @@ def test_total_balance_charged_and_pending_charged(
]
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
staff_api_client.user.user_permissions.add(permission_manage_shipping)
# when
@@ -118,7 +118,7 @@ def test_total_balance_charged_and_pending_charged(
def test_total_balance_only_refunded(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
permission_manage_shipping,
fulfilled_order,
):
@@ -144,7 +144,7 @@ def test_total_balance_only_refunded(
]
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
staff_api_client.user.user_permissions.add(permission_manage_shipping)
# when
@@ -162,7 +162,7 @@ def test_total_balance_only_refunded(
def test_total_balance_refunded_and_pending_refund(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
permission_manage_shipping,
fulfilled_order,
):
@@ -188,7 +188,7 @@ def test_total_balance_refunded_and_pending_refund(
]
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
staff_api_client.user.user_permissions.add(permission_manage_shipping)
# when
@@ -206,7 +206,7 @@ def test_total_balance_refunded_and_pending_refund(
def test_total_balance_refunded_and_charged(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
permission_manage_shipping,
fulfilled_order,
):
@@ -232,7 +232,7 @@ def test_total_balance_refunded_and_charged(
]
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
staff_api_client.user.user_permissions.add(permission_manage_shipping)
# when
@@ -253,7 +253,7 @@ def test_total_balance_refunded_and_charged(
def test_total_balance_with_granted_refund(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
permission_manage_shipping,
fulfilled_order,
):
@@ -263,7 +263,7 @@ def test_total_balance_with_granted_refund(
amount_value=Decimal("10.15"), currency=order.currency, order_id=order.pk
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
staff_api_client.user.user_permissions.add(permission_manage_shipping)
# when
@@ -283,7 +283,7 @@ def test_total_balance_with_granted_refund(
def test_total_balance_with_granted_refund_and_transactions(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
permission_manage_shipping,
fulfilled_order,
):
@@ -328,7 +328,7 @@ def test_total_balance_with_granted_refund_and_transactions(
]
)
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
staff_api_client.user.user_permissions.add(permission_manage_shipping)
# when
diff --git a/saleor/graphql/order/tests/queries/test_order_with_filter.py b/saleor/graphql/order/tests/queries/test_order_with_filter.py
index d6d66632e2..a7ffc15774 100644
--- a/saleor/graphql/order/tests/queries/test_order_with_filter.py
+++ b/saleor/graphql/order/tests/queries/test_order_with_filter.py
@@ -62,18 +62,17 @@ def order_list_with_cc_orders(orders, warehouse_for_cc):
def test_order_query_with_filter_channels_with_one_channel(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
orders,
channel_USD,
):
# given
channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
variables = {"filter": {"channels": [channel_id]}}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -84,16 +83,16 @@ def test_order_query_with_filter_channels_with_one_channel(
def test_order_query_with_filter_channels_without_channel(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
orders,
):
# given
variables = {"filter": {"channels": []}}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -104,7 +103,7 @@ def test_order_query_with_filter_channels_without_channel(
def test_order_query_with_filter_channels_with_many_channel(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
orders,
channel_USD,
channel_PLN,
@@ -116,10 +115,10 @@ def test_order_query_with_filter_channels_with_many_channel(
channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)
variables = {"filter": {"channels": [channel_pln_id, channel_usd_id]}}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -131,18 +130,17 @@ def test_order_query_with_filter_channels_with_many_channel(
def test_order_query_with_filter_channels_with_empty_channel(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
orders,
other_channel_USD,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
channel_id = graphene.Node.to_global_id("Channel", other_channel_USD.pk)
variables = {"filter": {"channels": [channel_id]}}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -153,11 +151,12 @@ def test_order_query_with_filter_channels_with_empty_channel(
def test_order_query_with_filter_gift_card_used_true(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
gift_card,
orders,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
gift_card_order = orders[0]
gift_cards_used_in_order_event(
[(gift_card, 20.0)], gift_card_order, staff_api_client.user, None
@@ -165,9 +164,7 @@ def test_order_query_with_filter_gift_card_used_true(
variables = {"filter": {"giftCardUsed": True}}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -181,11 +178,12 @@ def test_order_query_with_filter_gift_card_used_true(
def test_order_query_with_filter_gift_card_used_false(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
gift_card,
orders,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
gift_card_order = orders[0]
gift_card_order_id = graphene.Node.to_global_id("Order", gift_card_order.id)
gift_cards_used_in_order_event(
@@ -194,9 +192,7 @@ def test_order_query_with_filter_gift_card_used_false(
variables = {"filter": {"giftCardUsed": False}}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -209,19 +205,18 @@ def test_order_query_with_filter_gift_card_used_false(
def test_order_query_with_filter_gift_card_bough_true(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
gift_card,
orders,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
gift_card_order = orders[-1]
gift_cards_bought_event([gift_card], gift_card_order, staff_api_client.user, None)
variables = {"filter": {"giftCardBought": True}}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -235,20 +230,19 @@ def test_order_query_with_filter_gift_card_bough_true(
def test_order_query_with_filter_gift_card_bought_false(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
gift_card,
orders,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
gift_card_order = orders[-1]
gift_card_order_id = graphene.Node.to_global_id("Order", gift_card_order.id)
gift_cards_bought_event([gift_card], gift_card_order, staff_api_client.user, None)
variables = {"filter": {"giftCardBought": False}}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -281,14 +275,14 @@ def test_order_query_with_filter_created(
count,
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
channel_USD,
):
Order.objects.create(channel=channel_USD)
with freeze_time("2012-01-14"):
Order.objects.create(channel=channel_USD)
variables = {"filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content(response)
orders = content["data"]["orders"]["edges"]
@@ -321,7 +315,7 @@ def test_order_query_with_filter_updated_at(
count,
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
channel_USD,
):
with freeze_time("2012-01-14 11:00:00"):
@@ -331,7 +325,7 @@ def test_order_query_with_filter_updated_at(
Order.objects.create(channel=channel_USD)
variables = {"filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content(response)
orders = content["data"]["orders"]["edges"]
@@ -358,7 +352,7 @@ def test_order_query_with_filter_payment_status(
orders_query_with_filter,
staff_api_client,
payment_dummy,
- permission_manage_orders,
+ permission_group_manage_orders,
channel_PLN,
):
payment_dummy.charge_status = payment_status
@@ -370,7 +364,7 @@ def test_order_query_with_filter_payment_status(
payment_dummy.save()
variables = {"filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content(response)
orders = content["data"]["orders"]["edges"]
@@ -382,7 +376,7 @@ def test_order_query_with_filter_payment_fully_refunded_not_active(
orders_query_with_filter,
staff_api_client,
payment_dummy,
- permission_manage_orders,
+ permission_group_manage_orders,
channel_PLN,
):
# given
@@ -391,7 +385,7 @@ def test_order_query_with_filter_payment_fully_refunded_not_active(
payment_dummy.order = Order.objects.create(channel=channel_PLN)
payment_dummy.save()
variables = {"filter": {"paymentStatus": "FULLY_REFUNDED"}}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
@@ -419,7 +413,7 @@ def test_order_query_with_filter_status(
orders_query_with_filter,
staff_api_client,
payment_dummy,
- permission_manage_orders,
+ permission_group_manage_orders,
order,
channel_USD,
):
@@ -429,7 +423,7 @@ def test_order_query_with_filter_status(
Order.objects.create(channel=channel_USD)
variables = {"filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content(response)
orders = content["data"]["orders"]["edges"]
@@ -454,7 +448,7 @@ def test_order_query_with_filter_customer_fields(
user_value,
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
channel_USD,
):
@@ -466,7 +460,7 @@ def test_order_query_with_filter_customer_fields(
Order.objects.bulk_create([order, Order(channel=channel_USD)])
variables = {"filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content(response)
orders = content["data"]["orders"]["edges"]
@@ -479,17 +473,16 @@ def test_order_query_with_filter_customer_fields(
def test_order_query_with_filter_is_click_and_collect_true(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_list_with_cc_orders,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
orders = order_list_with_cc_orders
variables = {"filter": {"isClickAndCollect": True}}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -508,17 +501,16 @@ def test_order_query_with_filter_is_click_and_collect_true(
def test_order_query_with_filter_is_click_and_collect_false(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_list_with_cc_orders,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
orders = order_list_with_cc_orders
variables = {"filter": {"isClickAndCollect": False}}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -584,16 +576,15 @@ def preorders(orders, product):
def test_order_query_with_filter_is_preorder_true(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
preorders,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"filter": {"isPreorder": True}}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -608,16 +599,15 @@ def test_order_query_with_filter_is_preorder_true(
def test_order_query_with_filter_is_preorder_false(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
preorders,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"filter": {"isPreorder": False}}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -649,7 +639,7 @@ def test_orders_query_with_filter_search(
count,
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
channel_USD,
product,
@@ -726,7 +716,7 @@ def test_orders_query_with_filter_search(
Order.objects.bulk_update(orders, ["search_vector"])
variables = {"filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content(response)
assert content["data"]["orders"]["totalCount"] == count
@@ -735,7 +725,7 @@ def test_orders_query_with_filter_search(
def test_orders_query_with_filter_search_by_global_payment_id(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
channel_USD,
):
@@ -770,7 +760,7 @@ def test_orders_query_with_filter_search_by_global_payment_id(
Order.objects.bulk_update(orders, ["search_vector"])
variables = {"filter": {"search": global_id}}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content(response)
assert content["data"]["orders"]["totalCount"] == 1
@@ -780,11 +770,11 @@ def test_orders_query_with_filter_search_by_number(
orders_query_with_filter,
order_with_search_vector_value,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
order = order_with_search_vector_value
variables = {"filter": {"search": order.number}}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content(response)
assert content["data"]["orders"]["totalCount"] == 1
@@ -794,29 +784,34 @@ def test_orders_query_with_filter_search_by_number_with_hash(
orders_query_with_filter,
order_with_search_vector_value,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
order = order_with_search_vector_value
variables = {"filter": {"search": f"#{order.number}"}}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content(response)
assert content["data"]["orders"]["totalCount"] == 1
def test_orders_query_with_filter_search_by_product_sku_with_multiple_identic_sku(
- orders_query_with_filter, staff_api_client, permission_manage_orders, allocations
+ orders_query_with_filter,
+ staff_api_client,
+ permission_group_manage_orders,
+ allocations,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"filter": {"search": allocations[0].order_line.product_sku}}
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content(response)
assert content["data"]["orders"]["totalCount"] == 3
def test_order_query_with_filter_search_by_product_sku_order_line(
- orders_query_with_filter, staff_api_client, permission_manage_orders, order_line
+ orders_query_with_filter,
+ staff_api_client,
+ permission_group_manage_orders,
+ order_line,
):
query = """
query ($filter: OrderFilterInput!, ) {
@@ -833,14 +828,13 @@ def test_order_query_with_filter_search_by_product_sku_order_line(
}
}
"""
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_line.order
order.refresh_from_db()
update_order_search_vector(order)
variables = {"filter": {"search": order_line.product_sku}}
- response = staff_api_client.post_graphql(
- query, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
orders = content["data"]["orders"]["edges"][0]
lines = orders["node"]["lines"][0]["productSku"]
@@ -852,10 +846,11 @@ def test_orders_query_with_filter_by_orders_id(
orders_query_with_filter,
staff_api_client,
order,
- permission_manage_orders,
+ permission_group_manage_orders,
channel_USD,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
orders = Order.objects.bulk_create(
[
Order(
@@ -874,9 +869,7 @@ def test_orders_query_with_filter_by_orders_id(
variables = {"filter": {"ids": orders_ids}}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content(response)
edges = content["data"]["orders"]["edges"]
response_ids = [edge["node"]["id"] for edge in edges]
@@ -890,10 +883,11 @@ def test_orders_query_with_filter_by_old_orders_id(
orders_query_with_filter,
staff_api_client,
order,
- permission_manage_orders,
+ permission_group_manage_orders,
channel_USD,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
orders = Order.objects.bulk_create(
[
Order(
@@ -914,9 +908,7 @@ def test_orders_query_with_filter_by_old_orders_id(
variables = {"filter": {"ids": orders_ids}}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content(response)
edges = content["data"]["orders"]["edges"]
response_ids = [edge["node"]["id"] for edge in edges]
@@ -930,10 +922,11 @@ def test_orders_query_with_filter_by_old_and_new_orders_id(
orders_query_with_filter,
staff_api_client,
order,
- permission_manage_orders,
+ permission_group_manage_orders,
channel_USD,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
orders = Order.objects.bulk_create(
[
Order(
@@ -956,9 +949,7 @@ def test_orders_query_with_filter_by_old_and_new_orders_id(
variables = {"filter": {"ids": orders_ids}}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content(response)
edges = content["data"]["orders"]["edges"]
response_ids = [edge["node"]["id"] for edge in edges]
@@ -973,7 +964,7 @@ def test_orders_query_with_filter_by_old_and_new_orders_id(
def test_order_query_with_filter_search_by_product_sku_multi_order_lines(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
product,
channel_USD,
order,
@@ -1049,11 +1040,10 @@ def test_order_query_with_filter_search_by_product_sku_multi_order_lines(
)
order.refresh_from_db()
update_order_search_vector(order)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"filter": {"search": lines[0].product_sku}}
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content(response)
assert content["data"]["orders"]["totalCount"] == 1
@@ -1101,7 +1091,7 @@ def test_orders_query_with_filter_authorize_status(
order_with_lines,
order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
channel_USD,
):
@@ -1129,7 +1119,7 @@ def test_orders_query_with_filter_authorize_status(
update_order_authorize_data(order_with_lines)
variables = {"filter": {"authorizeStatus": statuses}}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
@@ -1182,7 +1172,7 @@ def test_orders_query_with_filter_charge_status(
order_with_lines,
order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
channel_USD,
):
@@ -1208,7 +1198,7 @@ def test_orders_query_with_filter_charge_status(
update_order_charge_data(order_with_lines)
variables = {"filter": {"chargeStatus": statuses}}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
@@ -1221,7 +1211,7 @@ def test_orders_query_with_filter_charge_status(
def test_order_query_with_filter_numbers(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
orders,
channel_USD,
):
@@ -1231,11 +1221,10 @@ def test_order_query_with_filter_numbers(
"numbers": [str(orders[0].number), str(orders[2].number)],
},
}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -1251,7 +1240,7 @@ def test_order_query_with_filter_numbers(
def test_order_query_with_filter_not_allow_numbers_and_ids_together(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
orders,
channel_USD,
):
@@ -1263,11 +1252,10 @@ def test_order_query_with_filter_not_allow_numbers_and_ids_together(
},
}
error_message = "'ids' and 'numbers` are not allowed to use together in filter."
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
content = get_graphql_content_from_response(response)
# then
@@ -1278,12 +1266,13 @@ def test_order_query_with_filter_not_allow_numbers_and_ids_together(
def test_order_query_with_filter_by_checkout_token(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
orders_from_checkout,
orders,
checkout,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"filter": {
"checkoutIds": [
@@ -1293,9 +1282,7 @@ def test_order_query_with_filter_by_checkout_token(
}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -1314,7 +1301,7 @@ def test_order_query_with_filter_by_checkout_token(
def test_order_query_with_filter_by_multiple_checkout_tokens(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
orders_from_checkout,
order_from_checkout_JPY,
orders,
@@ -1322,6 +1309,7 @@ def test_order_query_with_filter_by_multiple_checkout_tokens(
checkout_JPY,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"filter": {
"checkoutIds": [
@@ -1332,9 +1320,7 @@ def test_order_query_with_filter_by_multiple_checkout_tokens(
}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
@@ -1353,10 +1339,11 @@ def test_order_query_with_filter_by_multiple_checkout_tokens(
def test_order_query_with_filter_by_empty_list(
orders_query_with_filter,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
orders_from_checkout,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"filter": {
"checkoutIds": [],
@@ -1364,9 +1351,7 @@ def test_order_query_with_filter_by_empty_list(
}
# when
- response = staff_api_client.post_graphql(
- orders_query_with_filter, variables, permissions=(permission_manage_orders,)
- )
+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)
# then
content = get_graphql_content(response)
diff --git a/saleor/graphql/order/tests/queries/test_order_with_sort.py b/saleor/graphql/order/tests/queries/test_order_with_sort.py
index 1cdf3d4220..b45f2669ab 100644
--- a/saleor/graphql/order/tests/queries/test_order_with_sort.py
+++ b/saleor/graphql/order/tests/queries/test_order_with_sort.py
@@ -36,7 +36,7 @@ def test_query_orders_with_sort(
order_sort,
result_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
address,
channel_USD,
):
@@ -82,7 +82,7 @@ def test_query_orders_with_sort(
)
)
variables = {"sort_by": order_sort}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(QUERY_ORDER_WITH_SORT, variables)
content = get_graphql_content(response)
orders = content["data"]["orders"]["edges"]
@@ -116,8 +116,10 @@ SEARCH_ORDERS_QUERY = """
"""
-def test_sort_order_by_rank_without_search(staff_api_client, permission_manage_orders):
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+def test_sort_order_by_rank_without_search(
+ staff_api_client, permission_group_manage_orders
+):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"sortBy": {"field": "RANK", "direction": "DESC"},
diff --git a/saleor/graphql/order/tests/queries/test_pagination.py b/saleor/graphql/order/tests/queries/test_pagination.py
index 86480f0b4f..2d3b1fe1ed 100644
--- a/saleor/graphql/order/tests/queries/test_pagination.py
+++ b/saleor/graphql/order/tests/queries/test_pagination.py
@@ -160,7 +160,7 @@ def test_order_query_pagination_with_filter_created(
orders_order,
expected_total_count,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
orders_for_pagination,
channel_USD,
):
@@ -168,7 +168,7 @@ def test_order_query_pagination_with_filter_created(
Order.objects.create(channel=channel_USD)
page_size = 2
variables = {"first": page_size, "after": None, "filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
response = staff_api_client.post_graphql(QUERY_ORDERS_WITH_PAGINATION, variables)
content = get_graphql_content(response)
@@ -210,9 +210,10 @@ def test_order_query_pagination_with_filter_payment_status(
orders_order,
staff_api_client,
payment_dummy,
- permission_manage_orders,
+ permission_group_manage_orders,
orders_for_pagination,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
payment_dummy.charge_status = payment_status
payment_dummy.save()
@@ -224,7 +225,6 @@ def test_order_query_pagination_with_filter_payment_status(
page_size = 2
variables = {"first": page_size, "after": None, "filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(QUERY_ORDERS_WITH_PAGINATION, variables)
content = get_graphql_content(response)
@@ -251,7 +251,7 @@ def test_order_query_pagination_with_filter_status(
status,
orders_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order,
orders_for_pagination,
):
@@ -260,7 +260,8 @@ def test_order_query_pagination_with_filter_status(
page_size = 2
variables = {"first": page_size, "after": None, "filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
response = staff_api_client.post_graphql(QUERY_ORDERS_WITH_PAGINATION, variables)
content = get_graphql_content(response)
@@ -285,7 +286,7 @@ def test_order_query_pagination_with_filter_customer_fields(
user_field,
user_value,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
orders_for_pagination,
channel_USD,
@@ -298,7 +299,8 @@ def test_order_query_pagination_with_filter_customer_fields(
page_size = 2
variables = {"first": page_size, "after": None, "filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
response = staff_api_client.post_graphql(QUERY_ORDERS_WITH_PAGINATION, variables)
content = get_graphql_content(response)
orders = content["data"]["orders"]["edges"]
@@ -321,7 +323,7 @@ def test_draft_order_query_pagination_with_filter_customer_fields(
user_field,
user_value,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
draft_orders_for_pagination,
channel_USD,
@@ -338,7 +340,8 @@ def test_draft_order_query_pagination_with_filter_customer_fields(
page_size = 2
variables = {"first": page_size, "after": None, "filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
response = staff_api_client.post_graphql(
QUERY_DRAFT_ORDERS_WITH_PAGINATION, variables
)
@@ -374,7 +377,7 @@ def test_draft_order_query_pagination_with_filter_created(
expected_total_count,
orders_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
draft_orders_for_pagination,
channel_USD,
):
@@ -386,7 +389,8 @@ def test_draft_order_query_pagination_with_filter_created(
)
page_size = 2
variables = {"first": page_size, "after": None, "filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
response = staff_api_client.post_graphql(
QUERY_DRAFT_ORDERS_WITH_PAGINATION, variables
)
@@ -416,7 +420,7 @@ def test_orders_query_pagination_with_filter_search(
orders_filter,
expected_total_count,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
orders_for_pagination,
channel_USD,
@@ -467,7 +471,8 @@ def test_orders_query_pagination_with_filter_search(
orders_seen = 0
while True:
variables = {"first": 1, "after": after, "filter": orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
response = staff_api_client.post_graphql(
QUERY_ORDERS_WITH_PAGINATION, variables
)
@@ -497,7 +502,7 @@ def test_draft_orders_query_pagination_with_filter_search(
draft_orders_filter,
expected_total_count,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
customer_user,
draft_orders_for_pagination,
channel_USD,
@@ -552,7 +557,8 @@ def test_draft_orders_query_pagination_with_filter_search(
page_size = 2
variables = {"first": page_size, "after": None, "filter": draft_orders_filter}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
response = staff_api_client.post_graphql(
QUERY_DRAFT_ORDERS_WITH_PAGINATION, variables
)
@@ -564,12 +570,13 @@ def test_draft_orders_query_pagination_with_filter_search(
def test_orders_query_pagination_with_filter_search_by_number(
- order_with_search_vector_value, staff_api_client, permission_manage_orders
+ order_with_search_vector_value, staff_api_client, permission_group_manage_orders
):
order = order_with_search_vector_value
page_size = 2
variables = {"first": page_size, "after": None, "filter": {"search": order.number}}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
response = staff_api_client.post_graphql(QUERY_ORDERS_WITH_PAGINATION, variables)
content = get_graphql_content(response)
assert content["data"]["orders"]["totalCount"] == 1
@@ -578,7 +585,7 @@ def test_orders_query_pagination_with_filter_search_by_number(
def test_draft_orders_query_pagination_with_filter_search_by_number(
draft_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
):
update_order_search_vector(draft_order)
page_size = 2
@@ -587,7 +594,8 @@ def test_draft_orders_query_pagination_with_filter_search_by_number(
"after": None,
"filter": {"search": draft_order.number},
}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
response = staff_api_client.post_graphql(
QUERY_DRAFT_ORDERS_WITH_PAGINATION, variables
)
@@ -616,7 +624,7 @@ def test_query_orders_pagination_with_sort(
order_sort,
result_order,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
address,
channel_USD,
):
@@ -660,7 +668,8 @@ def test_query_orders_pagination_with_sort(
page_size = 2
variables = {"first": page_size, "after": None, "sortBy": order_sort}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
response = staff_api_client.post_graphql(QUERY_ORDERS_WITH_PAGINATION, variables)
content = get_graphql_content(response)
orders = content["data"]["orders"]["edges"]
diff --git a/saleor/graphql/order/tests/test_homepage.py b/saleor/graphql/order/tests/test_homepage.py
index 8f4b828a91..48972ea4c2 100644
--- a/saleor/graphql/order/tests/test_homepage.py
+++ b/saleor/graphql/order/tests/test_homepage.py
@@ -1,31 +1,73 @@
from datetime import date, timedelta
+import pytest
from prices import Money
from ....order import OrderEvents
-from ....order.models import OrderEvent
+from ....order.models import Order, OrderEvent
from ...core.enums import ReportingPeriod
from ...tests.utils import assert_no_permission, get_graphql_content
-
-def test_homepage_events(order_events, staff_api_client, permission_manage_orders):
- query = """
- {
- homepageEvents(first: 20) {
- edges {
- node {
- date
- type
- orderNumber
- }
+QUERY_HOMEPAGE_EVENTS = """
+{
+ homepageEvents(first: 20) {
+ edges {
+ node {
+ date
+ type
+ orderNumber
}
}
}
- """
- response = staff_api_client.post_graphql(
- query, permissions=[permission_manage_orders]
+}
+"""
+
+
+def order_events_from_different_channels(
+ order_events,
+ order_list,
+ channel_PLN,
+ channel_JPY,
+ channel_USD,
+):
+ order_list[0].channel = channel_PLN
+ order_list[1].channel = channel_JPY
+ order_list[2].channel = channel_USD
+ Order.objects.bulk_update(order_list, ["channel"])
+
+ events = list(
+ OrderEvent.objects.filter(
+ type__in=[
+ OrderEvents.PLACED,
+ OrderEvents.PLACED_FROM_DRAFT,
+ OrderEvents.ORDER_FULLY_PAID,
+ ]
+ )
)
+
+ events[0].order = order_list[0]
+ events[1].order = order_list[1]
+ events[2].order = order_list[2]
+ OrderEvent.objects.bulk_update(events, ["order"])
+
+ return order_events
+
+
+def test_homepage_events(
+ order_events_from_different_channels,
+ staff_api_client,
+ permission_group_manage_orders,
+):
+ # given
+ query = QUERY_HOMEPAGE_EVENTS
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ response = staff_api_client.post_graphql(query)
+
+ # when
content = get_graphql_content(response)
+
+ # then
edges = content["data"]["homepageEvents"]["edges"]
only_types = {"PLACED", "PLACED_FROM_DRAFT", "ORDER_FULLY_PAID"}
assert {edge["node"]["type"] for edge in edges} == only_types
@@ -41,6 +83,87 @@ def test_homepage_events(order_events, staff_api_client, permission_manage_order
assert {int(edge["node"]["orderNumber"]) for edge in edges} == expected_numbers
+def test_query_homepage_events_by_user_with_restricted_access_to_channels(
+ order_events_from_different_channels,
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ channel_USD,
+):
+ # given
+ user = staff_api_client.user
+ permission_group_all_perms_channel_USD_only.user_set.add(user)
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_HOMEPAGE_EVENTS)
+ content = get_graphql_content(response)
+
+ # then
+ assert len(content["data"]["homepageEvents"]["edges"]) == 1
+ event = OrderEvent.objects.filter(
+ type__in=[
+ OrderEvents.PLACED,
+ OrderEvents.PLACED_FROM_DRAFT,
+ OrderEvents.ORDER_FULLY_PAID,
+ ],
+ order__channel=channel_USD,
+ ).first()
+ assert content["data"]["homepageEvents"]["edges"][0]["node"]["orderNumber"] == str(
+ event.order.number
+ )
+
+
+def test_query_homepage_by_user_with_restricted_access_to_channels_no_acc_channels(
+ order_events_from_different_channels,
+ staff_api_client,
+ permission_group_all_perms_without_any_channel,
+):
+ """Ensure that query returns no orders when user has no accessible channels."""
+ # given
+ user = staff_api_client.user
+ permission_group_all_perms_without_any_channel.user_set.add(user)
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_HOMEPAGE_EVENTS)
+ content = get_graphql_content(response)
+
+ # then
+ assert len(content["data"]["homepageEvents"]["edges"]) == 0
+
+
+def test_query_homepage_by_app(
+ order_events_from_different_channels,
+ app_api_client,
+ permission_manage_orders,
+):
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_HOMEPAGE_EVENTS, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ events = OrderEvent.objects.filter(
+ type__in=[
+ OrderEvents.PLACED,
+ OrderEvents.PLACED_FROM_DRAFT,
+ OrderEvents.ORDER_FULLY_PAID,
+ ]
+ )
+ assert len(content["data"]["homepageEvents"]["edges"]) == events.count()
+
+
+def test_query_homepage_by_customer(
+ order_events_from_different_channels,
+ order_list,
+ user_api_client,
+):
+ # when
+ response = user_api_client.post_graphql(QUERY_HOMEPAGE_EVENTS)
+
+ # then
+ assert_no_permission(response)
+
+
QUERY_ORDER_TOTAL = """
query Orders($period: ReportingPeriod, $channel: String) {
ordersTotal(period: $period, channel: $channel ) {
@@ -59,19 +182,18 @@ query Orders($period: ReportingPeriod, $channel: String) {
def test_orders_total(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
order_with_lines_channel_PLN,
channel_USD,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
variables = {"period": ReportingPeriod.TODAY.name, "channel": channel_USD.slug}
# when
- response = staff_api_client.post_graphql(
- QUERY_ORDER_TOTAL, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(QUERY_ORDER_TOTAL, variables)
# then
content = get_graphql_content(response)
@@ -81,19 +203,18 @@ def test_orders_total(
def test_orders_total_channel_pln(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
order_with_lines_channel_PLN,
channel_PLN,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines_channel_PLN
variables = {"period": ReportingPeriod.TODAY.name, "channel": channel_PLN.slug}
# when
- response = staff_api_client.post_graphql(
- QUERY_ORDER_TOTAL, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(QUERY_ORDER_TOTAL, variables)
# then
content = get_graphql_content(response)
@@ -103,17 +224,16 @@ def test_orders_total_channel_pln(
def test_orders_total_not_existing_channel(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
order_with_lines_channel_PLN,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"period": ReportingPeriod.TODAY.name, "channel": "not-existing"}
# when
- response = staff_api_client.post_graphql(
- QUERY_ORDER_TOTAL, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(QUERY_ORDER_TOTAL, variables)
# then
content = get_graphql_content(response)
@@ -122,19 +242,18 @@ def test_orders_total_not_existing_channel(
def test_orders_total_as_staff(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
order_with_lines_channel_PLN,
channel_USD,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines
variables = {"period": ReportingPeriod.TODAY.name, "channel": channel_USD.slug}
# when
- response = staff_api_client.post_graphql(
- QUERY_ORDER_TOTAL, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(QUERY_ORDER_TOTAL, variables)
# then
content = get_graphql_content(response)
@@ -142,6 +261,22 @@ def test_orders_total_as_staff(
assert Money(amount, "USD") == order.total.gross
+def test_orders_total_no_access_to_channel(
+ staff_api_client, permission_group_all_perms_channel_USD_only, orders, channel_JPY
+):
+ # given
+ query = QUERY_ORDER_TOTAL
+
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ variables = {"period": ReportingPeriod.TODAY.name, "channel": channel_JPY.slug}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
def test_orders_total_as_app(
app_api_client,
permission_manage_orders,
@@ -207,12 +342,13 @@ QUERY_ORDER_TODAY_COUNT = """
def test_orders_total_count_without_channel(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
order_with_lines_channel_PLN,
channel_USD,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"created": {
"gte": str(date.today() - timedelta(days=3)),
@@ -221,9 +357,7 @@ def test_orders_total_count_without_channel(
}
# when
- response = staff_api_client.post_graphql(
- QUERY_ORDER_TODAY_COUNT, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(QUERY_ORDER_TODAY_COUNT, variables)
# then
content = get_graphql_content(response)
@@ -232,12 +366,13 @@ def test_orders_total_count_without_channel(
def test_orders_total_count_channel_USD(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
order_with_lines_channel_PLN,
channel_USD,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"created": {
"gte": str(date.today() - timedelta(days=3)),
@@ -247,9 +382,7 @@ def test_orders_total_count_channel_USD(
}
# when
- response = staff_api_client.post_graphql(
- QUERY_ORDER_TODAY_COUNT, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(QUERY_ORDER_TODAY_COUNT, variables)
# then
content = get_graphql_content(response)
@@ -258,12 +391,13 @@ def test_orders_total_count_channel_USD(
def test_orders_total_count_channel_PLN(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
order_with_lines_channel_PLN,
channel_PLN,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"created": {
"gte": str(date.today() - timedelta(days=3)),
@@ -273,9 +407,7 @@ def test_orders_total_count_channel_PLN(
}
# when
- response = staff_api_client.post_graphql(
- QUERY_ORDER_TODAY_COUNT, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(QUERY_ORDER_TODAY_COUNT, variables)
# then
content = get_graphql_content(response)
@@ -284,12 +416,13 @@ def test_orders_total_count_channel_PLN(
def test_orders_total_count_as_staff(
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
order_with_lines,
order_with_lines_channel_PLN,
channel_USD,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"created": {
"gte": str(date.today() - timedelta(days=3)),
@@ -299,9 +432,7 @@ def test_orders_total_count_as_staff(
}
# when
- response = staff_api_client.post_graphql(
- QUERY_ORDER_TODAY_COUNT, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(QUERY_ORDER_TODAY_COUNT, variables)
# then
content = get_graphql_content(response)
diff --git a/saleor/graphql/order/tests/test_order_payment.py b/saleor/graphql/order/tests/test_order_payment.py
index 5644fc2973..67debef4ca 100644
--- a/saleor/graphql/order/tests/test_order_payment.py
+++ b/saleor/graphql/order/tests/test_order_payment.py
@@ -14,8 +14,13 @@ from ..mutations.utils import try_payment_action
((True, "orderRefund"), (False, "orderVoid"), (True, "orderCapture")),
)
def test_clean_payment_without_payment_associated_to_order(
- staff_api_client, permission_manage_orders, order, requires_amount, mutation_name
+ staff_api_client,
+ permission_group_manage_orders,
+ order,
+ requires_amount,
+ mutation_name,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
assert not OrderEvent.objects.exists()
additional_arguments = ", amount: 2" if requires_amount else ""
@@ -35,9 +40,7 @@ def test_clean_payment_without_payment_associated_to_order(
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(query, variables)
errors = get_graphql_content(response)["data"][mutation_name].get("errors")
message = "There's no payment associated with the order."
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index c2b2f27ffa..a1c3cbcf38 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -428,11 +428,9 @@ class PaymentCapture(BaseMutation):
payment = cls.get_node_or_error(
info, payment_id, field="payment_id", only_type=Payment
)
- channel_slug = (
- payment.order.channel.slug
- if payment.order
- else payment.checkout.channel.slug
- )
+ channel = payment.order.channel if payment.order else payment.checkout.channel
+ cls.check_channel_permissions(info, [channel.id])
+ channel_slug = channel.slug
manager = get_plugin_manager_promise(info.context).get()
try:
gateway.capture(
@@ -466,11 +464,9 @@ class PaymentRefund(PaymentCapture):
payment = cls.get_node_or_error(
info, payment_id, field="payment_id", only_type=Payment
)
- channel_slug = (
- payment.order.channel.slug
- if payment.order
- else payment.checkout.channel.slug
- )
+ channel = payment.order.channel if payment.order else payment.checkout.channel
+ cls.check_channel_permissions(info, [channel.id])
+ channel_slug = channel.slug
manager = get_plugin_manager_promise(info.context).get()
payment_transaction = None
try:
@@ -520,11 +516,9 @@ class PaymentVoid(BaseMutation):
payment = cls.get_node_or_error(
info, payment_id, field="payment_id", only_type=Payment
)
- channel_slug = (
- payment.order.channel.slug
- if payment.order
- else payment.checkout.channel.slug
- )
+ channel = payment.order.channel if payment.order else payment.checkout.channel
+ cls.check_channel_permissions(info, [channel.id])
+ channel_slug = channel.slug
manager = get_plugin_manager_promise(info.context).get()
try:
gateway.void(payment, manager, channel_slug=channel_slug)
@@ -1438,10 +1432,12 @@ class TransactionRequestAction(BaseMutation):
transaction = get_transaction_item(id)
if transaction.order_id:
order = cast(Order, transaction.order)
- channel_slug = order.channel.slug
+ channel = order.channel
else:
checkout = cast(Checkout, transaction.checkout)
- channel_slug = checkout.channel.slug
+ channel = checkout.channel
+ cls.check_channel_permissions(info, [channel.id])
+ channel_slug = channel.slug
app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
action_kwargs = {
diff --git a/saleor/graphql/payment/resolvers.py b/saleor/graphql/payment/resolvers.py
index fe9a29cc97..557a1afce4 100644
--- a/saleor/graphql/payment/resolvers.py
+++ b/saleor/graphql/payment/resolvers.py
@@ -1,4 +1,8 @@
+from ...app import models as app_models
+from ...order import models as order_models
from ...payment import models
+from ..account.utils import get_user_accessible_channels
+from ..utils import get_user_or_app_from_context
def resolve_payment_by_id(id):
@@ -6,7 +10,14 @@ def resolve_payment_by_id(id):
def resolve_payments(info):
- return models.Payment.objects.all()
+ requestor = get_user_or_app_from_context(info.context)
+ payments = models.Payment.objects.all()
+ if isinstance(requestor, app_models.App):
+ return payments
+ accessible_channels = get_user_accessible_channels(info, requestor)
+ channel_ids = [channel.id for channel in accessible_channels]
+ orders = order_models.Order.objects.filter(channel_id__in=channel_ids)
+ return payments.filter(order_id__in=orders.values("id"))
def resolve_transaction(id):
diff --git a/saleor/graphql/payment/tests/benchmark/test_payment_transactions.py b/saleor/graphql/payment/tests/benchmark/test_payment_transactions.py
index a8e714da3f..f819447c13 100644
--- a/saleor/graphql/payment/tests/benchmark/test_payment_transactions.py
+++ b/saleor/graphql/payment/tests/benchmark/test_payment_transactions.py
@@ -52,13 +52,16 @@ query {
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_payment_transactions(
- staff_api_client, orders_for_benchmarks, permission_manage_orders, count_queries
+ staff_api_client,
+ orders_for_benchmarks,
+ permission_group_manage_orders,
+ count_queries,
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
transactions_count = 0
content = get_graphql_content(
staff_api_client.post_graphql(
PAYMENT_TRANSACTIONS_QUERY,
- permissions=[permission_manage_orders],
check_no_permissions=False,
)
)
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_capture.py b/saleor/graphql/payment/tests/mutations/test_payment_capture.py
index 362fc78ccc..118f819c74 100644
--- a/saleor/graphql/payment/tests/mutations/test_payment_capture.py
+++ b/saleor/graphql/payment/tests/mutations/test_payment_capture.py
@@ -8,7 +8,7 @@ from .....payment.gateways.dummy_credit_card import (
TOKEN_VALIDATION_MAPPING,
)
from .....payment.models import ChargeStatus
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
CAPTURE_QUERY = """
mutation PaymentCapture($paymentId: ID!, $amount: PositiveDecimal) {
@@ -28,16 +28,67 @@ CAPTURE_QUERY = """
def test_payment_capture_success(
- staff_api_client, permission_manage_orders, payment_txn_preauth
+ staff_api_client, permission_group_manage_orders, payment_txn_preauth
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
payment = payment_txn_preauth
assert payment.charge_status == ChargeStatus.NOT_CHARGED
payment_id = graphene.Node.to_global_id("Payment", payment.pk)
variables = {"paymentId": payment_id, "amount": str(payment_txn_preauth.total)}
- response = staff_api_client.post_graphql(
- CAPTURE_QUERY, variables, permissions=[permission_manage_orders]
+ response = staff_api_client.post_graphql(CAPTURE_QUERY, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["paymentCapture"]
+ assert not data["errors"]
+ payment_txn_preauth.refresh_from_db()
+ assert payment.charge_status == ChargeStatus.FULLY_CHARGED
+ assert payment.transactions.count() == 2
+ txn = payment.transactions.last()
+ assert txn.kind == TransactionKind.CAPTURE
+
+
+def test_payment_capture_success_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ payment_txn_preauth,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ order = payment_txn_preauth.order
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ payment = payment_txn_preauth
+ assert payment.charge_status == ChargeStatus.NOT_CHARGED
+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)
+
+ variables = {"paymentId": payment_id, "amount": str(payment_txn_preauth.total)}
+
+ # when
+ response = staff_api_client.post_graphql(CAPTURE_QUERY, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_payment_capture_success_by_app(
+ app_api_client, permission_manage_orders, payment_txn_preauth
+):
+ # given
+ payment = payment_txn_preauth
+ assert payment.charge_status == ChargeStatus.NOT_CHARGED
+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)
+
+ variables = {"paymentId": payment_id, "amount": str(payment_txn_preauth.total)}
+
+ # when
+ response = app_api_client.post_graphql(
+ CAPTURE_QUERY, variables, permissions=(permission_manage_orders,)
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["paymentCapture"]
assert not data["errors"]
@@ -49,16 +100,15 @@ def test_payment_capture_success(
def test_payment_capture_with_invalid_argument(
- staff_api_client, permission_manage_orders, payment_txn_preauth
+ staff_api_client, permission_group_manage_orders, payment_txn_preauth
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
payment = payment_txn_preauth
assert payment.charge_status == ChargeStatus.NOT_CHARGED
payment_id = graphene.Node.to_global_id("Payment", payment.pk)
variables = {"paymentId": payment_id, "amount": 0}
- response = staff_api_client.post_graphql(
- CAPTURE_QUERY, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(CAPTURE_QUERY, variables)
content = get_graphql_content(response)
data = content["data"]["paymentCapture"]
assert len(data["errors"]) == 1
@@ -66,19 +116,18 @@ def test_payment_capture_with_invalid_argument(
def test_payment_capture_with_payment_non_authorized_yet(
- staff_api_client, permission_manage_orders, payment_dummy
+ staff_api_client, permission_group_manage_orders, payment_dummy
):
"""Ensure capture a payment that is set as authorized is failing with
the proper error message.
"""
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
payment = payment_dummy
assert payment.charge_status == ChargeStatus.NOT_CHARGED
payment_id = graphene.Node.to_global_id("Payment", payment.pk)
variables = {"paymentId": payment_id, "amount": 1}
- response = staff_api_client.post_graphql(
- CAPTURE_QUERY, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(CAPTURE_QUERY, variables)
content = get_graphql_content(response)
data = content["data"]["paymentCapture"]
assert data["errors"] == [
@@ -91,9 +140,10 @@ def test_payment_capture_with_payment_non_authorized_yet(
def test_payment_capture_gateway_error(
- staff_api_client, permission_manage_orders, payment_txn_preauth, monkeypatch
+ staff_api_client, permission_group_manage_orders, payment_txn_preauth, monkeypatch
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
payment = payment_txn_preauth
assert payment.charge_status == ChargeStatus.NOT_CHARGED
@@ -102,9 +152,7 @@ def test_payment_capture_gateway_error(
monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)
# when
- response = staff_api_client.post_graphql(
- CAPTURE_QUERY, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(CAPTURE_QUERY, variables)
# then
content = get_graphql_content(response)
@@ -127,9 +175,10 @@ def test_payment_capture_gateway_error(
True,
)
def test_payment_capture_gateway_dummy_credit_card_error(
- staff_api_client, permission_manage_orders, payment_txn_preauth, monkeypatch
+ staff_api_client, permission_group_manage_orders, payment_txn_preauth, monkeypatch
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
token = TOKEN_EXPIRED
error = TOKEN_VALIDATION_MAPPING[token]
@@ -149,9 +198,7 @@ def test_payment_capture_gateway_dummy_credit_card_error(
)
# when
- response = staff_api_client.post_graphql(
- CAPTURE_QUERY, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(CAPTURE_QUERY, variables)
# then
content = get_graphql_content(response)
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_refund.py b/saleor/graphql/payment/tests/mutations/test_payment_refund.py
index 584efde448..c34df2008c 100644
--- a/saleor/graphql/payment/tests/mutations/test_payment_refund.py
+++ b/saleor/graphql/payment/tests/mutations/test_payment_refund.py
@@ -5,7 +5,7 @@ from .....payment import TransactionKind
from .....payment.models import ChargeStatus
from .....tests.utils import flush_post_commit_hooks
from ....core.enums import PaymentErrorCode
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
REFUND_QUERY = """
mutation PaymentRefund($paymentId: ID!, $amount: PositiveDecimal) {
@@ -32,11 +32,12 @@ def test_payment_refund_success(
mock_order_refunded,
mock_order_updated,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
payment_txn_captured,
order_with_lines,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
payment = payment_txn_captured
payment.total = order_with_lines.total.gross.amount
payment.charge_status = ChargeStatus.FULLY_CHARGED
@@ -47,8 +48,75 @@ def test_payment_refund_success(
variables = {"paymentId": payment_id, "amount": str(payment.total)}
# when
- response = staff_api_client.post_graphql(
- REFUND_QUERY, variables, permissions=[permission_manage_orders]
+ response = staff_api_client.post_graphql(REFUND_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["paymentRefund"]
+ assert not data["errors"]
+ payment.refresh_from_db()
+ assert payment.charge_status == ChargeStatus.FULLY_REFUNDED
+ assert payment.transactions.count() == 2
+ txn = payment.transactions.last()
+ assert txn.kind == TransactionKind.REFUND
+
+ flush_post_commit_hooks()
+ mock_order_updated.assert_called_once_with(payment.order)
+ mock_order_refunded.assert_called_once_with(payment.order)
+ mock_order_fully_refunded.assert_called_once_with(payment.order)
+
+
+def test_payment_refund_success_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ payment_txn_captured,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ payment = payment_txn_captured
+
+ order = payment.order
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount = payment.total
+ payment.save()
+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)
+
+ variables = {"paymentId": payment_id, "amount": str(payment.total)}
+
+ # when
+ response = staff_api_client.post_graphql(REFUND_QUERY, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+def test_payment_refund_success_by_app(
+ mock_order_fully_refunded,
+ mock_order_refunded,
+ mock_order_updated,
+ app_api_client,
+ permission_manage_orders,
+ payment_txn_captured,
+):
+ # given
+ payment = payment_txn_captured
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount = payment.total
+ payment.save()
+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)
+
+ variables = {"paymentId": payment_id, "amount": str(payment.total)}
+
+ # when
+ response = app_api_client.post_graphql(
+ REFUND_QUERY, variables, permissions=(permission_manage_orders,)
)
# then
@@ -75,10 +143,11 @@ def test_payment_refund_with_invalid_argument(
mock_order_refunded,
mock_order_updated,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
payment_txn_captured,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
payment = payment_txn_captured
payment.charge_status = ChargeStatus.FULLY_CHARGED
payment.captured_amount = payment.total
@@ -88,9 +157,7 @@ def test_payment_refund_with_invalid_argument(
variables = {"paymentId": payment_id, "amount": 0}
# when
- response = staff_api_client.post_graphql(
- REFUND_QUERY, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(REFUND_QUERY, variables)
# then
content = get_graphql_content(response)
@@ -111,11 +178,12 @@ def test_payment_refund_error(
mock_order_refunded,
mock_order_updated,
staff_api_client,
- permission_manage_orders,
+ permission_group_manage_orders,
payment_txn_captured,
monkeypatch,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
payment = payment_txn_captured
payment.charge_status = ChargeStatus.FULLY_CHARGED
payment.captured_amount = payment.total
@@ -125,9 +193,7 @@ def test_payment_refund_error(
monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)
# when
- response = staff_api_client.post_graphql(
- REFUND_QUERY, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(REFUND_QUERY, variables)
# then
content = get_graphql_content(response)
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_void.py b/saleor/graphql/payment/tests/mutations/test_payment_void.py
index f8ff2389d8..841e6a7429 100644
--- a/saleor/graphql/payment/tests/mutations/test_payment_void.py
+++ b/saleor/graphql/payment/tests/mutations/test_payment_void.py
@@ -1,7 +1,7 @@
import graphene
from .....payment import ChargeStatus, TransactionKind
-from ....tests.utils import get_graphql_content
+from ....tests.utils import assert_no_permission, get_graphql_content
VOID_QUERY = """
mutation PaymentVoid($paymentId: ID!) {
@@ -21,14 +21,61 @@ VOID_QUERY = """
def test_payment_void_success(
- staff_api_client, permission_manage_orders, payment_txn_preauth
+ staff_api_client, permission_group_manage_orders, payment_txn_preauth
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
assert payment_txn_preauth.charge_status == ChargeStatus.NOT_CHARGED
payment_id = graphene.Node.to_global_id("Payment", payment_txn_preauth.pk)
variables = {"paymentId": payment_id}
- response = staff_api_client.post_graphql(
- VOID_QUERY, variables, permissions=[permission_manage_orders]
+ response = staff_api_client.post_graphql(VOID_QUERY, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["paymentVoid"]
+ assert not data["errors"]
+ payment_txn_preauth.refresh_from_db()
+ assert payment_txn_preauth.is_active is False
+ assert payment_txn_preauth.transactions.count() == 2
+ txn = payment_txn_preauth.transactions.last()
+ assert txn.kind == TransactionKind.VOID
+
+
+def test_payment_void_success_by_user_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ payment_txn_preauth,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ order = payment_txn_preauth.order
+ order.channel = channel_PLN
+ order.save(update_fields=["channel"])
+
+ assert payment_txn_preauth.charge_status == ChargeStatus.NOT_CHARGED
+ payment_id = graphene.Node.to_global_id("Payment", payment_txn_preauth.pk)
+ variables = {"paymentId": payment_id}
+
+ # when
+ response = staff_api_client.post_graphql(VOID_QUERY, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_payment_void_success_by_app(
+ app_api_client, permission_manage_orders, payment_txn_preauth
+):
+ # given
+ assert payment_txn_preauth.charge_status == ChargeStatus.NOT_CHARGED
+ payment_id = graphene.Node.to_global_id("Payment", payment_txn_preauth.pk)
+ variables = {"paymentId": payment_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ VOID_QUERY, variables, permissions=(permission_manage_orders,)
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["paymentVoid"]
assert not data["errors"]
@@ -40,15 +87,14 @@ def test_payment_void_success(
def test_payment_void_gateway_error(
- staff_api_client, permission_manage_orders, payment_txn_preauth, monkeypatch
+ staff_api_client, permission_group_manage_orders, payment_txn_preauth, monkeypatch
):
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
assert payment_txn_preauth.charge_status == ChargeStatus.NOT_CHARGED
payment_id = graphene.Node.to_global_id("Payment", payment_txn_preauth.pk)
variables = {"paymentId": payment_id}
monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)
- response = staff_api_client.post_graphql(
- VOID_QUERY, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(VOID_QUERY, variables)
content = get_graphql_content(response)
data = content["data"]["paymentVoid"]
assert data["errors"]
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
index e88bd819f6..e118e3a511 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
@@ -278,6 +278,46 @@ def test_transaction_request_void_action_for_order(
)
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_transaction_request_void_action_for_order_by_user_no_channel_access(
+ mocked_payment_action_request,
+ mocked_is_active,
+ order_with_lines,
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ mocked_is_active.return_value = True
+
+ order_with_lines.channel = channel_PLN
+ order_with_lines.save(update_fields=["channel"])
+
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ psp_reference="PSP ref",
+ available_actions=["charge", "void"],
+ currency="USD",
+ order_id=order_with_lines.pk,
+ authorized_value=Decimal("10"),
+ )
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.VOID.name,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # then
+ assert_no_permission(response)
+
+
@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
def test_transaction_request_void_action_for_checkout(
@@ -568,9 +608,15 @@ def test_transaction_request_action_missing_permission(
@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
def test_transaction_request_action_missing_event(
- mocked_is_active, staff_api_client, permission_manage_payments, order
+ mocked_is_active,
+ staff_api_client,
+ permission_group_manage_orders,
+ permission_manage_payments,
+ permission_group_no_perms_all_channels,
+ order,
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
authorization_value = Decimal("10")
transaction = TransactionItem.objects.create(
status="Authorized",
@@ -587,14 +633,13 @@ def test_transaction_request_action_missing_event(
"id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.VOID.name,
}
+ permission_group_no_perms_all_channels.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(
MUTATION_TRANSACTION_REQUEST_ACTION,
variables,
- permissions=[
- permission_manage_payments,
- ],
+ permissions=(permission_manage_payments,),
)
# then
@@ -1261,6 +1306,7 @@ def test_transaction_request_missing_event(
mocked_get_webhooks,
staff_api_client,
permission_manage_payments,
+ permission_group_no_perms_all_channels,
order,
app,
):
@@ -1285,6 +1331,7 @@ def test_transaction_request_missing_event(
"id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.VOID.name,
}
+ permission_group_no_perms_all_channels.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(
diff --git a/saleor/graphql/payment/tests/queries/test_payments_filter.py b/saleor/graphql/payment/tests/queries/test_payments_filter.py
index 4d1d1233f9..f242270e9f 100644
--- a/saleor/graphql/payment/tests/queries/test_payments_filter.py
+++ b/saleor/graphql/payment/tests/queries/test_payments_filter.py
@@ -35,9 +35,10 @@ PAYMENT_QUERY = """ query Payments($filter: PaymentFilterInput){
def test_query_payments_filter_by_checkout(
- payment_dummy, checkouts_list, permission_manage_orders, staff_api_client
+ payment_dummy, checkouts_list, permission_group_manage_orders, staff_api_client
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
payment1 = payment_dummy
payment1.checkout = checkouts_list[0]
payment1.save()
@@ -62,9 +63,7 @@ def test_query_payments_filter_by_checkout(
}
# when
- response = staff_api_client.post_graphql(
- PAYMENT_QUERY, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(PAYMENT_QUERY, variables)
# then
content = get_graphql_content(response)
@@ -77,9 +76,10 @@ def test_query_payments_filter_by_checkout(
def test_query_payments_filter_by_one_id(
- payments_dummy, permission_manage_orders, staff_api_client
+ payments_dummy, permission_group_manage_orders, staff_api_client
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
search_payment = payments_dummy[0]
variables = {
@@ -89,9 +89,7 @@ def test_query_payments_filter_by_one_id(
}
# when
- response = staff_api_client.post_graphql(
- PAYMENT_QUERY, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(PAYMENT_QUERY, variables)
# then
content = get_graphql_content(response)
@@ -103,9 +101,10 @@ def test_query_payments_filter_by_one_id(
def test_query_payments_filter_by_multiple_ids(
- payments_dummy, permission_manage_orders, staff_api_client
+ payments_dummy, permission_group_manage_orders, staff_api_client
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
search_payments = payments_dummy[:2]
search_payments_ids = [
graphene.Node.to_global_id("Payment", payment.pk) for payment in search_payments
@@ -114,9 +113,7 @@ def test_query_payments_filter_by_multiple_ids(
variables = {"filter": {"ids": search_payments_ids}}
# when
- response = staff_api_client.post_graphql(
- PAYMENT_QUERY, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(PAYMENT_QUERY, variables)
# then
content = get_graphql_content(response)
@@ -131,15 +128,14 @@ def test_query_payments_filter_by_multiple_ids(
def test_query_payments_filter_by_empty_id_list(
- payments_dummy, permission_manage_orders, staff_api_client
+ payments_dummy, permission_group_manage_orders, staff_api_client
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {"filter": {"ids": []}}
# when
- response = staff_api_client.post_graphql(
- PAYMENT_QUERY, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(PAYMENT_QUERY, variables)
# then
content = get_graphql_content(response)
@@ -154,17 +150,16 @@ def test_query_payments_filter_by_empty_id_list(
def test_query_payments_filter_by_not_existing_id(
- payments_dummy, permission_manage_orders, staff_api_client
+ payments_dummy, permission_group_manage_orders, staff_api_client
):
# given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
search_pk = max([payment.pk for payment in payments_dummy]) + 1
search_id = graphene.Node.to_global_id("Payment", search_pk)
variables = {"filter": {"ids": [search_id]}}
# when
- response = staff_api_client.post_graphql(
- PAYMENT_QUERY, variables, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(PAYMENT_QUERY, variables)
# then
content = get_graphql_content(response)
diff --git a/saleor/graphql/payment/tests/queries/test_payments_query.py b/saleor/graphql/payment/tests/queries/test_payments_query.py
index ea28cdef2f..e595b80075 100644
--- a/saleor/graphql/payment/tests/queries/test_payments_query.py
+++ b/saleor/graphql/payment/tests/queries/test_payments_query.py
@@ -2,10 +2,35 @@ import json
from decimal import Decimal
import graphene
+import pytest
-from ....tests.utils import get_graphql_content, get_graphql_content_from_response
+from .....order.models import Order
+from .....payment.models import Payment
+from ....tests.utils import (
+ assert_no_permission,
+ get_graphql_content,
+ get_graphql_content_from_response,
+)
from ...enums import PaymentChargeStatusEnum, TransactionActionEnum
+
+def payments_in_different_channels(
+ order_list, payments_dummy, channel_USD, channel_JPY, channel_PLN
+):
+ order_list[0].channel = channel_PLN
+ order_list[1].channel = channel_JPY
+ order_list[2].channel = channel_USD
+ Order.objects.bulk_update(order_list, ["channel"])
+
+ payments_dummy[0].order = order_list[0]
+ payments_dummy[1].order = order_list[1]
+ payments_dummy[2].order = order_list[2]
+ Payment.objects.bulk_update(payments_dummy, ["order"])
+
+ return payments_dummy
+
+
PAYMENT_QUERY = """ query Payments($filter: PaymentFilterInput){
payments(first: 20, filter: $filter) {
edges {
@@ -38,11 +63,10 @@ PAYMENT_QUERY = """ query Payments($filter: PaymentFilterInput){
def test_payments_query(
- payment_txn_captured, permission_manage_orders, staff_api_client
+ payment_txn_captured, permission_group_manage_orders, staff_api_client
):
- response = staff_api_client.post_graphql(
- PAYMENT_QUERY, permissions=[permission_manage_orders]
- )
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ response = staff_api_client.post_graphql(PAYMENT_QUERY)
content = get_graphql_content(response)
data = content["data"]["payments"]["edges"][0]["node"]
pay = payment_txn_captured
@@ -65,12 +89,13 @@ def test_payments_query(
]
-def test_query_payments(payment_dummy, permission_manage_orders, staff_api_client):
+def test_query_payments(
+ payment_dummy, permission_group_manage_orders, staff_api_client
+):
payment = payment_dummy
payment_id = graphene.Node.to_global_id("Payment", payment.pk)
- response = staff_api_client.post_graphql(
- PAYMENT_QUERY, {}, permissions=[permission_manage_orders]
- )
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ response = staff_api_client.post_graphql(PAYMENT_QUERY, {})
content = get_graphql_content(response)
edges = content["data"]["payments"]["edges"]
payment_ids = [edge["node"]["id"] for edge in edges]
@@ -78,15 +103,14 @@ def test_query_payments(payment_dummy, permission_manage_orders, staff_api_clien
def test_query_payments_failed_payment(
- payment_txn_capture_failed, permission_manage_orders, staff_api_client
+ payment_txn_capture_failed, permission_group_manage_orders, staff_api_client
):
# given
payment = payment_txn_capture_failed
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
- response = staff_api_client.post_graphql(
- PAYMENT_QUERY, permissions=[permission_manage_orders]
- )
+ response = staff_api_client.post_graphql(PAYMENT_QUERY)
# then
content = get_graphql_content(response)
@@ -111,6 +135,83 @@ def test_query_payments_failed_payment(
]
+def test_query_payments_by_user_with_access_to_all_channels(
+ payments_in_different_channels,
+ permission_group_all_perms_all_channels,
+ staff_api_client,
+):
+ # given
+ permission_group_all_perms_all_channels.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(PAYMENT_QUERY)
+
+ # then
+ content = get_graphql_content(response)
+ edges = content["data"]["payments"]["edges"]
+ assert len(edges) == len(payments_in_different_channels)
+
+
+def test_query_payments_by_user_with_restricted_access_to_channels(
+ payments_in_different_channels,
+ permission_group_all_perms_channel_USD_only,
+ staff_api_client,
+ channel_USD,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(PAYMENT_QUERY)
+
+ # then
+ content = get_graphql_content(response)
+ edges = content["data"]["payments"]["edges"]
+ assert len(edges) == 1
+ assert edges[0]["node"]["id"] == graphene.Node.to_global_id(
+ "Payment", Payment.objects.get(order__channel=channel_USD).pk
+ )
+
+
+def test_query_payments_by_user_with_restricted_access_to_channels_no_acc_channels(
+ payments_in_different_channels,
+ permission_group_all_perms_without_any_channel,
+ staff_api_client,
+):
+ # given
+ permission_group_all_perms_without_any_channel.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(PAYMENT_QUERY)
+
+ # then
+ content = get_graphql_content(response)
+ edges = content["data"]["payments"]["edges"]
+ assert len(edges) == 0
+
+
+def test_query_payments_by_app(
+ payments_in_different_channels, app_api_client, permission_manage_orders
+):
+ # when
+ response = app_api_client.post_graphql(
+ PAYMENT_QUERY, permissions=(permission_manage_orders,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ edges = content["data"]["payments"]["edges"]
+ assert len(edges) == len(payments_in_different_channels)
+
+
+def test_query_payments_by_customer(payments_in_different_channels, user_api_client):
+ # when
+ response = user_api_client.post_graphql(PAYMENT_QUERY)
+
+ # then
+ assert_no_permission(response)
+
+
QUERY_PAYMENT_BY_ID = """
query payment($id: ID!) {
payment(id: $id) {
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 97eb560ffd..a1dec30cd3 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -9204,6 +9204,24 @@ type User implements Node & ObjectWithMetadata @doc(category: "Users") {
"""List of user's permission groups which user can manage."""
editableGroups: [Group!]
+
+ """
+ List of channels the user has access to. The sum of channels from all user groups. If at least one group has `restrictedAccessToChannels` set to False - all channels are returned.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ accessibleChannels: [Channel!]
+
+ """
+ Determine if user have restricted access to channels. False if at least one user group has `restrictedAccessToChannels` set to False.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ restrictedAccessToChannels: Boolean!
avatar(
"""
Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).
@@ -11516,6 +11534,24 @@ type Group implements Node @doc(category: "Users") {
True, if the currently authenticated user has rights to manage a group.
"""
userCanManage: Boolean!
+
+ """
+ List of channels the group has access to.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ accessibleChannels: [Channel!]
+
+ """
+ Determine if the group have restricted access to channels.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ restrictedAccessToChannels: Boolean!
}
"""History log of the customer."""
@@ -25835,18 +25871,22 @@ type PermissionGroupError @doc(category: "Users") {
"""List of user IDs which causes the error."""
users: [ID!]
+
+ """List of chnnels IDs which causes the error."""
+ channels: [ID!]
}
"""An enumeration."""
enum PermissionGroupErrorCode @doc(category: "Users") {
+ REQUIRED
+ UNIQUE
ASSIGN_NON_STAFF_MEMBER
DUPLICATED_INPUT_ITEM
CANNOT_REMOVE_FROM_LAST_GROUP
LEFT_NOT_MANAGEABLE_PERMISSION
OUT_OF_SCOPE_PERMISSION
OUT_OF_SCOPE_USER
- REQUIRED
- UNIQUE
+ OUT_OF_SCOPE_CHANNEL
}
input PermissionGroupCreateInput @doc(category: "Users") {
@@ -25856,8 +25896,26 @@ input PermissionGroupCreateInput @doc(category: "Users") {
"""List of users to assign to this group."""
addUsers: [ID!]
+ """
+ List of channels to assign to this group.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ addChannels: [ID!]
+
"""Group name."""
name: String!
+
+ """
+ Determine if the group has restricted access to channels. DEFAULT: False
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ restrictedAccessToChannels: Boolean = false
}
"""
@@ -25878,6 +25936,15 @@ input PermissionGroupUpdateInput @doc(category: "Users") {
"""List of users to assign to this group."""
addUsers: [ID!]
+ """
+ List of channels to assign to this group.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ addChannels: [ID!]
+
"""Group name."""
name: String
@@ -25886,6 +25953,24 @@ input PermissionGroupUpdateInput @doc(category: "Users") {
"""List of users to unassign from this group."""
removeUsers: [ID!]
+
+ """
+ List of channels to unassign from this group.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ removeChannels: [ID!]
+
+ """
+ Determine if the group has restricted access to channels.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ restrictedAccessToChannels: Boolean
}
"""
diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.py
index e1b75e41da..f1d28811bc 100644
--- a/saleor/graphql/shop/mutations.py
+++ b/saleor/graphql/shop/mutations.py
@@ -434,6 +434,8 @@ class OrderSettingsUpdate(BaseMutation):
code=OrderSettingsErrorCode.INVALID.value,
)
+ cls.check_channel_permissions(info, [channel.id])
+
update_fields = {}
for field in FIELDS:
if field in data["input"]:
diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.py
index a2c78248b3..c1af8adc3f 100644
--- a/saleor/graphql/shop/tests/test_shop.py
+++ b/saleor/graphql/shop/tests/test_shop.py
@@ -1342,10 +1342,10 @@ ORDER_SETTINGS_UPDATE_MUTATION = """
def test_order_settings_update_by_staff(
- staff_api_client, permission_manage_orders, channel_USD, channel_PLN
+ staff_api_client, permission_group_manage_orders, channel_USD, channel_PLN
):
# given
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(
@@ -1371,11 +1371,32 @@ def test_order_settings_update_by_staff(
assert channel_USD.automatically_fulfill_non_shippable_gift_card is False
+def test_order_settings_update_by_staff_no_channel_access(
+ staff_api_client,
+ permission_group_all_perms_channel_USD_only,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ permission_group_all_perms_channel_USD_only.user_set.add(staff_api_client.user)
+ channel_USD.is_active = False
+ channel_USD.save(update_fields=["is_active"])
+
+ # when
+ response = staff_api_client.post_graphql(
+ ORDER_SETTINGS_UPDATE_MUTATION,
+ {"confirmOrders": False, "fulfillGiftCards": False},
+ )
+
+ # then
+ assert_no_permission(response)
+
+
def test_order_settings_update_by_staff_nothing_changed(
- staff_api_client, permission_manage_orders, channel_USD, channel_PLN
+ staff_api_client, permission_group_manage_orders, channel_USD, channel_PLN
):
# given
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
QUERY = """
mutation {
orderSettingsUpdate(
diff --git a/saleor/graphql/tests/fixtures.py b/saleor/graphql/tests/fixtures.py
index 0d4c478ce4..d8f8e050dc 100644
--- a/saleor/graphql/tests/fixtures.py
+++ b/saleor/graphql/tests/fixtures.py
@@ -192,7 +192,7 @@ def graphql_log_handler():
@pytest.fixture
-def superuser():
+def superuser(db):
superuser = User.objects.create_user(
"pass",
diff --git a/saleor/plugins/openid_connect/dataclasses.py b/saleor/plugins/openid_connect/dataclasses.py
index df281787ea..f454d09307 100644
--- a/saleor/plugins/openid_connect/dataclasses.py
+++ b/saleor/plugins/openid_connect/dataclasses.py
@@ -13,3 +13,5 @@ class OpenIDConnectConfig:
user_info_url: str
audience: str
use_scope_permissions: bool
+ staff_user_domains: str
+ default_group_name: str
diff --git a/saleor/plugins/openid_connect/plugin.py b/saleor/plugins/openid_connect/plugin.py
index 9eb528f9db..dbb60a53c5 100644
--- a/saleor/plugins/openid_connect/plugin.py
+++ b/saleor/plugins/openid_connect/plugin.py
@@ -10,6 +10,7 @@ from jwt import ExpiredSignatureError, InvalidTokenError
from requests import HTTPError, PreparedRequest
from ...account.models import User
+from ...account.utils import get_user_groups_permissions
from ...core.auth import get_token_from_request
from ...core.jwt import (
JWT_REFRESH_TOKEN_COOKIE_NAME,
@@ -28,12 +29,15 @@ from .dataclasses import OpenIDConnectConfig
from .exceptions import AuthenticationError
from .utils import (
OAUTH_TOKEN_REFRESH_FIELD,
+ assign_staff_to_default_group_and_update_permissions,
create_tokens_from_oauth_payload,
+ get_domain_from_email,
get_incorrect_fields,
get_or_create_user_from_payload,
get_parsed_id_token,
get_saleor_permission_names,
get_saleor_permissions_qs_from_scope,
+ get_staff_user_domains,
get_user_from_oauth_access_token,
get_user_from_token,
is_owner_of_token_valid,
@@ -56,6 +60,8 @@ class OpenIDConnectPlugin(BasePlugin):
{"name": "user_info_url", "value": None},
{"name": "audience", "value": None},
{"name": "use_oauth_scope_permissions", "value": False},
+ {"name": "staff_user_domains", "value": None},
+ {"name": "default_group_name_for_new_staff_users", "value": None},
]
PLUGIN_NAME = "OpenID Connect"
CONFIGURATION_PER_CHANNEL = False
@@ -140,6 +146,24 @@ class OpenIDConnectPlugin(BasePlugin):
),
"label": "Use OAuth scope permissions",
},
+ "staff_user_domains": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": (
+ "Provide the domains of the user emails, separated by commas, "
+ "that should be treated as staff users (e.g. example.com)."
+ ),
+ "label": "Staff user domains",
+ },
+ "default_group_name_for_new_staff_users": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": (
+ "Provide the name of the default permission group to which the new "
+ "staff user should be assigned to. When the provided group doesn't "
+ "exist, the new group without any permissions and any channels "
+ "will be created."
+ ),
+ "label": "Default permission group name for new staff users",
+ },
}
def __init__(self, *args, **kwargs):
@@ -157,6 +181,8 @@ class OpenIDConnectPlugin(BasePlugin):
audience=configuration["audience"],
use_scope_permissions=configuration["use_oauth_scope_permissions"],
user_info_url=configuration["user_info_url"],
+ staff_user_domains=configuration["staff_user_domains"],
+ default_group_name=configuration["default_group_name_for_new_staff_users"],
)
# Determine, if we have defined all fields required to use OAuth access token
@@ -261,21 +287,26 @@ class OpenIDConnectPlugin(BasePlugin):
)
user = get_or_create_user_from_payload(
- parsed_id_token, self.config.authorization_url
+ parsed_id_token,
+ self.config.authorization_url,
)
user_permissions = []
- if self.config.use_scope_permissions:
+ is_staff_user_email = self.is_staff_user_email(user)
+ if self.config.use_scope_permissions or is_staff_user_email:
scope = token_data.get("scope")
user_permissions = self._use_scope_permissions(user, scope)
- if not user.is_staff and bool(
- SALEOR_STAFF_PERMISSION in scope or user_permissions
- ):
- user.is_staff = True
- user.save(update_fields=["is_staff"])
- elif user.is_staff and not bool(
- SALEOR_STAFF_PERMISSION in scope or user_permissions
- ):
+
+ is_staff_in_scope = SALEOR_STAFF_PERMISSION in scope
+ is_staff_user = is_staff_in_scope or user_permissions or is_staff_user_email
+ if is_staff_user:
+ assign_staff_to_default_group_and_update_permissions(
+ user, self.config.default_group_name
+ )
+ if not user.is_staff:
+ user.is_staff = True
+ user.save(update_fields=["is_staff"])
+ elif user.is_staff and not is_staff_user:
user.is_staff = False
user.save(update_fields=["is_staff"])
@@ -284,6 +315,12 @@ class OpenIDConnectPlugin(BasePlugin):
)
return ExternalAccessTokens(user=user, **tokens)
+ def is_staff_user_email(self, user: "User"):
+ """Return True if the user email is from staff user domains."""
+ staff_user_domains = get_staff_user_domains(self.config)
+ email_domain = get_domain_from_email(user.email)
+ return email_domain in staff_user_domains
+
def external_authentication_url(
self, data: dict, request: WSGIRequest, previous_value
) -> dict:
@@ -358,11 +395,9 @@ class OpenIDConnectPlugin(BasePlugin):
)
user = get_user_from_token(parsed_id_token)
- user_permissions = []
- if self.config.use_scope_permissions:
- user_permissions = self._use_scope_permissions(
- user, token_data.get("scope")
- )
+ user_permissions = self.get_and_update_user_permissions(
+ user, self.config.use_scope_permissions, token_data.get("scope")
+ )
tokens = create_tokens_from_oauth_payload(
token_data,
@@ -377,6 +412,19 @@ class OpenIDConnectPlugin(BasePlugin):
{"refreshToken": ValidationError(str(e), code=error_code)}
)
+ def get_and_update_user_permissions(
+ self, user: User, use_scope_permissions: bool, scope: str
+ ):
+ """Update user permissions based on scope and user groups' permissions."""
+ permissions = get_user_groups_permissions(user)
+ if use_scope_permissions and scope:
+ permissions |= get_saleor_permissions_qs_from_scope(scope)
+ user.effective_permissions = permissions
+ user_permissions = (
+ get_saleor_permission_names(permissions) if permissions else []
+ )
+ return user_permissions
+
def external_logout(self, data: dict, request: WSGIRequest, previous_value):
if not self.active:
return previous_value
@@ -416,9 +464,12 @@ class OpenIDConnectPlugin(BasePlugin):
except (ExpiredSignatureError, InvalidTokenError) as e:
raise ValidationError({"token": e})
permissions = payload.get(PERMISSIONS_FIELD)
- if permissions is not None:
- user.effective_permissions = get_permissions_from_names(permissions)
+ if permissions:
user.is_staff = True
+ user.effective_permissions = get_permissions_from_names(permissions)
+ assign_staff_to_default_group_and_update_permissions(
+ user, self.config.default_group_name
+ )
return user, payload
def authenticate_user(self, request: WSGIRequest, previous_value) -> Optional[User]:
@@ -434,8 +485,14 @@ class OpenIDConnectPlugin(BasePlugin):
# Check if the token is created by this plugin
payload = jwt_decode(token)
user = get_user_from_access_payload(payload, request)
+ if user.is_staff:
+ assign_staff_to_default_group_and_update_permissions(
+ user, self.config.default_group_name
+ )
return user
+ staff_user_domains = get_staff_user_domains(self.config)
+
if self.use_oauth_access_token:
user = get_user_from_oauth_access_token(
token,
@@ -443,5 +500,7 @@ class OpenIDConnectPlugin(BasePlugin):
self.config.user_info_url,
self.config.use_scope_permissions,
self.config.audience,
+ staff_user_domains,
+ self.config.default_group_name,
)
return user or previous_value
diff --git a/saleor/plugins/openid_connect/tests/conftest.py b/saleor/plugins/openid_connect/tests/conftest.py
index e40b28ae85..42ab4ba3d8 100644
--- a/saleor/plugins/openid_connect/tests/conftest.py
+++ b/saleor/plugins/openid_connect/tests/conftest.py
@@ -18,6 +18,8 @@ def plugin_configuration():
user_info_url=None,
use_oauth_scope_permissions=False,
audience=None,
+ staff_user_domains=None,
+ default_group_name_for_new_staff_users=None,
):
return [
{"name": "client_id", "value": client_id},
@@ -33,6 +35,11 @@ def plugin_configuration():
"value": use_oauth_scope_permissions,
},
{"name": "audience", "value": audience},
+ {"name": "staff_user_domains", "value": staff_user_domains},
+ {
+ "name": "default_group_name_for_new_staff_users",
+ "value": default_group_name_for_new_staff_users,
+ },
]
return fun
@@ -52,6 +59,8 @@ def openid_plugin(settings, plugin_configuration):
use_oauth_scope_permissions=False,
user_info_url="https://saleor.io/userinfo",
audience="perms",
+ staff_user_domains="",
+ default_group_name_for_new_staff_users="OpenID test group",
):
settings.PLUGINS = ["saleor.plugins.openid_connect.plugin.OpenIDConnectPlugin"]
manager = get_plugins_manager()
@@ -71,6 +80,8 @@ def openid_plugin(settings, plugin_configuration):
use_oauth_scope_permissions=use_oauth_scope_permissions,
user_info_url=user_info_url,
audience=audience,
+ staff_user_domains=staff_user_domains,
+ default_group_name_for_new_staff_users=default_group_name_for_new_staff_users,
),
},
)
diff --git a/saleor/plugins/openid_connect/tests/test_plugin.py b/saleor/plugins/openid_connect/tests/test_plugin.py
index 54b7896be7..88ea489a8e 100644
--- a/saleor/plugins/openid_connect/tests/test_plugin.py
+++ b/saleor/plugins/openid_connect/tests/test_plugin.py
@@ -7,6 +7,7 @@ from django.core import signing
from django.core.exceptions import ValidationError
from freezegun import freeze_time
+from ....account.models import Group
from ....core.jwt import (
JWT_ACCESS_TYPE,
JWT_REFRESH_TOKEN_COOKIE_NAME,
@@ -193,8 +194,15 @@ def test_external_refresh_from_input(
@freeze_time("2019-03-18 12:00:00")
def test_external_refresh_with_scope_permissions(
- openid_plugin, admin_user, monkeypatch, rf, id_token, id_payload
+ openid_plugin,
+ admin_user,
+ monkeypatch,
+ rf,
+ id_token,
+ id_payload,
+ permission_manage_users,
):
+ # given
mocked_jwt_validator = MagicMock()
mocked_jwt_validator.__getitem__.side_effect = id_payload.__getitem__
mocked_jwt_validator.get.side_effect = id_payload.get
@@ -226,15 +234,21 @@ def test_external_refresh_with_scope_permissions(
saleor_refresh_token = create_jwt_refresh_token(
admin_user, oauth_refresh_token, csrf_token, plugin.PLUGIN_ID
)
+ group = Group.objects.create(name=plugin.config.default_group_name)
+ group.permissions.add(permission_manage_users)
+ admin_user.groups.add(group)
request = rf.request()
data = {"refreshToken": saleor_refresh_token}
+
+ # when
response = plugin.external_refresh(data, request, None)
+ # then
decoded_token = jwt_decode(response.token)
assert decoded_token["exp"] == id_payload["exp"]
assert decoded_token["oauth_access_key"] == oauth_payload["access_token"]
- assert decoded_token["permissions"] == ["MANAGE_ORDERS"]
+ assert set(decoded_token["permissions"]) == {"MANAGE_ORDERS", "MANAGE_USERS"}
decoded_refresh_token = jwt_decode(response.refresh_token)
assert decoded_refresh_token["oauth_refresh_token"] == "new_refresh"
@@ -244,6 +258,10 @@ def test_external_refresh_with_scope_permissions(
refresh_token=oauth_refresh_token,
)
+ user = response.user
+ assert user.is_staff
+ assert permission_manage_users in user.effective_permissions
+
@freeze_time("2019-03-18 12:00:00")
@pytest.mark.vcr
@@ -387,7 +405,10 @@ def test_external_obtain_access_tokens(
oauth_payload,
plugin.config.json_web_key_set_url,
)
- user = get_or_create_user_from_payload(claims, oauth_url="https://saleor.io/oauth")
+ user = get_or_create_user_from_payload(
+ claims,
+ oauth_url="https://saleor.io/oauth",
+ )
expected_tokens = create_tokens_from_oauth_payload(
oauth_payload, user, claims, permissions=[], owner=plugin.PLUGIN_ID
)
@@ -514,7 +535,10 @@ def test_external_obtain_access_tokens_with_saleor_staff(
oauth_payload,
plugin.config.json_web_key_set_url,
)
- user = get_or_create_user_from_payload(claims, "https://saleor.io/oauth")
+ user = get_or_create_user_from_payload(
+ claims,
+ "https://saleor.io/oauth",
+ )
user.refresh_from_db()
assert user.is_staff is True
@@ -774,6 +798,9 @@ def test_external_verify(id_payload, customer_user, openid_plugin, rf):
user, data = response
assert user == customer_user
assert list(user.effective_permissions) == []
+ assert user.is_staff is False
+ assert Group.objects.count() == 0
+ assert user.groups.count() == 0
@freeze_time("2019-03-18 12:00:00")
@@ -794,6 +821,12 @@ def test_external_verify_user_with_effective_permissions(
user, data = response
assert user == customer_user
assert list(user.effective_permissions) == [permission_manage_orders]
+ assert user.is_staff is True
+ assert Group.objects.count() == 1
+ group = Group.objects.get()
+ assert group.name == plugin.config.default_group_name
+ assert user.groups.count() == 1
+ assert user.groups.first() == group
@freeze_time("2019-03-18 12:00:00")
@@ -828,6 +861,7 @@ def test_authenticate_user_with_access_token(
json_web_key_set_url="https://saleor.io/.well-known/jwks.json",
user_info_url="https://saleor.io/userinfo",
use_oauth_scope_permissions=True,
+ staff_user_domains="",
)
decoded_access_token["scope"] = ""
@@ -997,6 +1031,7 @@ def test_authenticate_staff_user_with_jwt_access_token_and_staff_scope(
monkeypatch,
rf,
):
+ # given
plugin = openid_plugin(
oauth_authorization_url=None,
oauth_token_url=None,
@@ -1008,6 +1043,7 @@ def test_authenticate_staff_user_with_jwt_access_token_and_staff_scope(
decoded_token = MagicMock()
decoded_token.__getitem__.side_effect = decoded_access_token.__getitem__
decoded_token.get.side_effect = decoded_access_token.get
+ assert Group.objects.count() == 0
# mock get token from request
monkeypatch.setattr(
@@ -1027,12 +1063,19 @@ def test_authenticate_staff_user_with_jwt_access_token_and_staff_scope(
# mock cache used for caching user info details
monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+ # when
user = plugin.authenticate_user(rf.request(), None)
+ # then
user.refresh_from_db()
assert user == customer_user
assert user.is_staff is True
assert list(user.effective_permissions) == []
+ assert Group.objects.count() == 1
+ group = Group.objects.get()
+ assert group.name == plugin.config.default_group_name
+ assert user.groups.count() == 1
+ assert user.groups.first() == group
@freeze_time("2021-03-08 12:00:00")
@@ -1044,6 +1087,7 @@ def test_authenticate_staff_user_with_jwt_access_token_and_staff_in_permissions_
monkeypatch,
rf,
):
+ # given
plugin = openid_plugin(
oauth_authorization_url=None,
oauth_token_url=None,
@@ -1056,6 +1100,7 @@ def test_authenticate_staff_user_with_jwt_access_token_and_staff_in_permissions_
decoded_token = MagicMock()
decoded_token.__getitem__.side_effect = decoded_access_token.__getitem__
decoded_token.get.side_effect = decoded_access_token.get
+ assert Group.objects.count() == 0
# mock get token from request
monkeypatch.setattr(
@@ -1075,12 +1120,19 @@ def test_authenticate_staff_user_with_jwt_access_token_and_staff_in_permissions_
# mock cache used for caching user info details
monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+ # when
user = plugin.authenticate_user(rf.request(), None)
+ # then
user.refresh_from_db()
assert user == customer_user
assert user.is_staff is True
assert list(user.effective_permissions) == []
+ assert Group.objects.count() == 1
+ group = Group.objects.get()
+ assert group.name == plugin.config.default_group_name
+ assert user.groups.count() == 1
+ assert user.groups.first() == group
@freeze_time("2021-03-08 12:00:00")
@@ -1094,6 +1146,7 @@ def test_authenticate_staff_user_with_jwt_access_token_with_permissions_field(
monkeypatch,
rf,
):
+ # given
plugin = openid_plugin(
oauth_authorization_url=None,
oauth_token_url=None,
@@ -1125,8 +1178,10 @@ def test_authenticate_staff_user_with_jwt_access_token_with_permissions_field(
# mock cache used for caching user info details
monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+ # when
user = plugin.authenticate_user(rf.request(), None)
+ # then
user.refresh_from_db()
assert user == customer_user
assert user.is_staff is True
@@ -1134,6 +1189,11 @@ def test_authenticate_staff_user_with_jwt_access_token_with_permissions_field(
permission_manage_apps,
permission_manage_orders,
}
+ assert Group.objects.count() == 1
+ group = Group.objects.get()
+ assert group.name == plugin.config.default_group_name
+ assert user.groups.count() == 1
+ assert user.groups.first() == group
@freeze_time("2021-03-08 12:00:00")
@@ -1233,6 +1293,7 @@ def test_authenticate_staff_user_with_jwt_access_token(
permission_manage_apps,
permission_manage_products,
):
+ # given
staff_user.is_staff = False
staff_user.save()
@@ -1248,6 +1309,7 @@ def test_authenticate_staff_user_with_jwt_access_token(
decoded_token = MagicMock()
decoded_token.__getitem__.side_effect = decoded_access_token.__getitem__
decoded_token.get.side_effect = decoded_access_token.get
+ assert Group.objects.count() == 0
user_info_response["email"] = staff_user.email
@@ -1269,8 +1331,10 @@ def test_authenticate_staff_user_with_jwt_access_token(
# mock cache used for caching user info details
monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+ # when
user = plugin.authenticate_user(rf.request(), None)
+ # then
user.refresh_from_db()
assert user == staff_user
assert user.is_staff is True
@@ -1279,12 +1343,18 @@ def test_authenticate_staff_user_with_jwt_access_token(
permission_manage_apps,
permission_manage_products,
}
+ assert Group.objects.count() == 1
+ group = Group.objects.get()
+ assert group.name == plugin.config.default_group_name
+ assert user.groups.count() == 1
+ assert user.groups.first() == group
@freeze_time("2021-03-08 12:00:00")
def test_authenticate_staff_user_with_jwt_access_token_and_disabled_scope_permission(
openid_plugin, decoded_access_token, user_info_response, staff_user, monkeypatch, rf
):
+ # given
plugin = openid_plugin(
oauth_authorization_url=None,
oauth_token_url=None,
@@ -1296,6 +1366,7 @@ def test_authenticate_staff_user_with_jwt_access_token_and_disabled_scope_permis
decoded_token = MagicMock()
decoded_token.__getitem__.side_effect = decoded_access_token.__getitem__
decoded_token.get.side_effect = decoded_access_token.get
+ assert Group.objects.count() == 0
user_info_response["email"] = staff_user.email
@@ -1320,11 +1391,74 @@ def test_authenticate_staff_user_with_jwt_access_token_and_disabled_scope_permis
# mock cache used for caching user info details
monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+ # when
user = plugin.authenticate_user(rf.request(), None)
+ # then
assert user == staff_user
assert user.is_staff is False
assert list(user.effective_permissions) == []
+ assert Group.objects.count() == 0
+ assert user.groups.count() == 0
+
+
+@freeze_time("2021-03-08 12:00:00")
+def test_authenticate_user_with_jwt_access_token_user_email_in_staff_domains_group(
+ openid_plugin,
+ decoded_access_token,
+ user_info_response,
+ customer_user,
+ monkeypatch,
+ rf,
+ permission_manage_users,
+):
+ # given
+ plugin = openid_plugin(
+ oauth_authorization_url=None,
+ oauth_token_url=None,
+ json_web_key_set_url="https://saleor.io/.well-known/jwks.json",
+ user_info_url="https://saleor.io/userinfo",
+ use_oauth_scope_permissions=True,
+ staff_user_domains=user_info_response["email"].split("@")[1],
+ )
+ decoded_access_token["scope"] = ""
+ decoded_token = MagicMock()
+ decoded_token.__getitem__.side_effect = decoded_access_token.__getitem__
+ decoded_token.get.side_effect = decoded_access_token.get
+
+ group = Group.objects.create(name=plugin.config.default_group_name)
+ group.permissions.add(permission_manage_users)
+ group_count = Group.objects.count()
+
+ # mock get token from request
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request",
+ lambda _: "OAuth_access_token",
+ )
+ # decode access token returns payload when access token is in JWT format
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.decode_access_token",
+ lambda x, y: decoded_token,
+ )
+ # mock request to api to fetch user info details
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info",
+ lambda x, z: user_info_response,
+ )
+ # mock cache used for caching user info details
+ monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+
+ # when
+ user = plugin.authenticate_user(rf.request(), None)
+
+ # then
+ assert user == customer_user
+ assert user.is_staff is True
+ assert Group.objects.count() == group_count
+ assert group in user.groups.all()
+ assert {perm.name for perm in user.effective_permissions} == set(
+ group.permissions.values_list("name", flat=True)
+ )
@freeze_time("2019-03-18 12:00:00")
@@ -1419,7 +1553,9 @@ def test_authenticate_user_staff_user_with_effective_permissions(
monkeypatch,
rf,
):
+ # given
plugin = openid_plugin()
+ assert Group.objects.count() == 0
staff_user.user_permissions.add(
permission_manage_gift_card, permission_manage_checkouts
)
@@ -1434,12 +1570,21 @@ def test_authenticate_user_staff_user_with_effective_permissions(
monkeypatch.setattr(
"saleor.plugins.openid_connect.plugin.get_token_from_request", lambda _: token
)
+
+ # when
user = plugin.authenticate_user(rf.request(), None)
+
+ # then
assert user == staff_user
assert set(user.effective_permissions) == {
permission_manage_orders,
permission_manage_users,
}
+ assert Group.objects.count() == 1
+ group = Group.objects.get()
+ assert group.name == plugin.config.default_group_name
+ assert user.groups.count() == 1
+ assert user.groups.first() == group
@freeze_time("2019-03-18 12:00:00")
@@ -1450,6 +1595,7 @@ def test_authenticate_user_staff_user_without_permissions(
monkeypatch,
rf,
):
+ # given
plugin = openid_plugin()
token = create_jwt_token(
id_payload,
@@ -1461,5 +1607,10 @@ def test_authenticate_user_staff_user_without_permissions(
monkeypatch.setattr(
"saleor.plugins.openid_connect.plugin.get_token_from_request", lambda _: token
)
+
+ # when
user = plugin.authenticate_user(rf.request(), None)
+
+ # then
assert user == staff_user
+ assert user.groups.count() == 1
diff --git a/saleor/plugins/openid_connect/tests/test_utils.py b/saleor/plugins/openid_connect/tests/test_utils.py
index ca194ecdb3..4692bbe477 100644
--- a/saleor/plugins/openid_connect/tests/test_utils.py
+++ b/saleor/plugins/openid_connect/tests/test_utils.py
@@ -14,7 +14,7 @@ from django.utils.timezone import make_aware
from freezegun import freeze_time
from requests import Response
-from ....account.models import User
+from ....account.models import Group, User
from ....core.jwt import (
JWT_REFRESH_TYPE,
PERMISSIONS_FIELD,
@@ -22,14 +22,17 @@ from ....core.jwt import (
jwt_encode,
jwt_user_payload,
)
+from ....permission.models import Permission
from ..exceptions import AuthenticationError
from ..utils import (
JWKS_CACHE_TIME,
JWKS_KEY,
+ assign_staff_to_default_group_and_update_permissions,
create_jwt_refresh_token,
create_jwt_token,
create_tokens_from_oauth_payload,
fetch_jwks,
+ get_domain_from_email,
get_or_create_user_from_payload,
get_saleor_permission_names,
get_saleor_permissions_qs_from_scope,
@@ -243,34 +246,42 @@ def test_get_or_create_user_from_payload_updates_sub(customer_user):
def test_get_or_create_user_from_payload_assigns_sub(customer_user):
+ # given
oauth_url = "https://saleor.io/oauth"
sub_id = "oauth|1234"
+ # when
user_from_payload = get_or_create_user_from_payload(
payload={"sub": sub_id, "email": customer_user.email},
oauth_url=oauth_url,
)
+ # then
assert user_from_payload.id == customer_user.id
assert user_from_payload.private_metadata[f"oidc-{oauth_url}"] == sub_id
+ assert customer_user.is_staff is False
def test_get_or_create_user_from_payload_creates_user_with_sub():
+ # given
oauth_url = "https://saleor.io/oauth"
sub_id = "oauth|1234"
customer_email = "[email protected]"
+ # when
user_from_payload = get_or_create_user_from_payload(
payload={"sub": sub_id, "email": customer_email},
oauth_url=oauth_url,
)
+ # then
assert user_from_payload.email == customer_email
assert user_from_payload.private_metadata[f"oidc-{oauth_url}"] == sub_id
assert not user_from_payload.has_usable_password()
def test_get_or_create_user_from_payload_multiple_subs(customer_user, admin_user):
+ # given
oauth_url = "https://saleor.io/oauth"
sub_id = "oauth|1234"
@@ -280,17 +291,20 @@ def test_get_or_create_user_from_payload_multiple_subs(customer_user, admin_user
admin_user.private_metadata = {f"oidc-{oauth_url}": sub_id}
admin_user.save()
+ # when
with warnings.catch_warnings(record=True):
user_from_payload = get_or_create_user_from_payload(
payload={"sub": sub_id, "email": customer_user.email},
oauth_url=oauth_url,
)
+ # then
assert user_from_payload.email == customer_user.email
assert user_from_payload.private_metadata[f"oidc-{oauth_url}"] == sub_id
def test_get_or_create_user_from_payload_different_email(customer_user):
+ # given
oauth_url = "https://saleor.io/oauth"
sub_id = "oauth|1234"
new_customer_email = "[email protected]"
@@ -298,11 +312,13 @@ def test_get_or_create_user_from_payload_different_email(customer_user):
customer_user.private_metadata = {f"oidc-{oauth_url}": sub_id}
customer_user.save()
+ # when
user_from_payload = get_or_create_user_from_payload(
payload={"sub": sub_id, "email": new_customer_email},
oauth_url=oauth_url,
)
+ # then
customer_user.refresh_from_db()
assert user_from_payload.id == customer_user.id
assert customer_user.email == new_customer_email
@@ -356,5 +372,271 @@ def test_jwt_token_without_expiration_claim(monkeypatch, decoded_access_token):
access_token="fake-token",
use_scope_permissions=False,
audience="",
+ staff_user_domains=[],
+ staff_default_group_name="",
)
assert user.email == "[email protected]"
+
+
+def test_jwt_token_without_expiration_claim_mixed_permissions_from_group(
+ customer_user, monkeypatch, decoded_access_token, permission_group_manage_shipping
+):
+ # given
+ customer_user.groups.add(permission_group_manage_shipping)
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info_from_cache_or_fetch",
+ lambda *args, **kwargs: {
+ "email": customer_user.email,
+ "sub": token_payload["sub"],
+ "scope": token_payload["scope"],
+ },
+ )
+ decoded_access_token.pop("exp")
+ token_payload = JWTClaims(
+ decoded_access_token,
+ {},
+ )
+
+ # when
+ user = get_user_from_oauth_access_token_in_jwt_format(
+ token_payload,
+ "https://example.com",
+ access_token="fake-token",
+ use_scope_permissions=True,
+ audience="",
+ staff_user_domains=[customer_user.email.split("@")[1]],
+ staff_default_group_name="",
+ )
+
+ # then
+ manage_shipping = permission_group_manage_shipping.permissions.first()
+ assert user.id == customer_user.id
+ assert manage_shipping in user.effective_permissions
+ assert len(user.effective_permissions) > 1
+ # ensure that manage_shipping is not from openID scope permissions
+ assert "saleor:manage_shipping" not in token_payload["scope"]
+
+
+def test_jwt_token_without_expiration_claim_email_not_match_staff_user_domains(
+ customer_user, monkeypatch, decoded_access_token
+):
+ # given
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info_from_cache_or_fetch",
+ lambda *args, **kwargs: {
+ "email": customer_user.email,
+ "sub": token_payload["sub"],
+ "scope": "",
+ },
+ )
+ decoded_access_token.pop("exp")
+ token_payload = JWTClaims(
+ decoded_access_token,
+ {},
+ )
+ default_group_name = "test group"
+ assert Group.objects.count() == 0
+
+ # when
+ user = get_user_from_oauth_access_token_in_jwt_format(
+ token_payload,
+ "https://example.com",
+ access_token="fake-token",
+ use_scope_permissions=False,
+ audience="",
+ staff_user_domains=["test.pl"],
+ staff_default_group_name=default_group_name,
+ )
+
+ # then
+ assert user.id == customer_user.id
+ assert user.is_staff is False
+ assert list(user.effective_permissions) == []
+ assert Group.objects.count() == 0
+ assert user.groups.count() == 0
+
+
+def test_jwt_token_without_expiration_claim_default_channel_group(
+ customer_user, monkeypatch, decoded_access_token
+):
+ # given
+ decoded_access_token["scope"] = ""
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info_from_cache_or_fetch",
+ lambda *args, **kwargs: {
+ "email": customer_user.email,
+ "sub": token_payload["sub"],
+ "scope": token_payload["scope"],
+ },
+ )
+ decoded_access_token.pop("exp")
+ token_payload = JWTClaims(
+ decoded_access_token,
+ {},
+ )
+ default_group_name = "test group"
+ assert Group.objects.count() == 0
+
+ # when
+ user = get_user_from_oauth_access_token_in_jwt_format(
+ token_payload,
+ "https://example.com",
+ access_token="fake-token",
+ use_scope_permissions=False,
+ audience="",
+ staff_user_domains=[customer_user.email.split("@")[1]],
+ staff_default_group_name=default_group_name,
+ )
+
+ # then
+ assert user.id == customer_user.id
+ assert user.is_staff is True
+ assert list(user.effective_permissions) == []
+ assert Group.objects.count() == 1
+ group = Group.objects.get()
+ assert group.name == default_group_name
+ assert user.groups.count() == 1
+ assert user.groups.first() == group
+
+
+def test_jwt_token_without_expiration_claim_with_existing_default_channel_group(
+ customer_user, monkeypatch, decoded_access_token, permission_manage_users
+):
+ # given
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info_from_cache_or_fetch",
+ lambda *args, **kwargs: {
+ "email": customer_user.email,
+ "sub": token_payload["sub"],
+ "scope": token_payload["scope"],
+ },
+ )
+ decoded_access_token.pop("exp")
+ token_payload = JWTClaims(
+ decoded_access_token,
+ {},
+ )
+ default_group_name = "test group"
+ group = Group.objects.create(name=default_group_name)
+ group.permissions.add(permission_manage_users)
+ group_count = Group.objects.count()
+
+ # when
+ user = get_user_from_oauth_access_token_in_jwt_format(
+ token_payload,
+ "https://example.com",
+ access_token="fake-token",
+ use_scope_permissions=False,
+ audience="",
+ staff_user_domains=[customer_user.email.split("@")[1]],
+ staff_default_group_name=default_group_name,
+ )
+
+ # then
+ assert user.id == customer_user.id
+ assert user.is_staff is True
+ assert Group.objects.count() == group_count
+ assert group in user.groups.all()
+ assert len(user.effective_permissions) > 1
+ assert permission_manage_users in user.effective_permissions
+ # ensure that manage_users is not from openID scope permissions
+ assert "saleor:manage_users" not in token_payload["scope"]
+
+
[email protected]("staff_default_group_name", [" ", ""])
+def test_jwt_token_without_expiration_claim_empty_default_channel_group(
+ staff_default_group_name, customer_user, monkeypatch, decoded_access_token
+):
+ # given
+ decoded_access_token["scope"] = ""
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info_from_cache_or_fetch",
+ lambda *args, **kwargs: {
+ "email": customer_user.email,
+ "sub": token_payload["sub"],
+ "scope": token_payload["scope"],
+ },
+ )
+ decoded_access_token.pop("exp")
+ token_payload = JWTClaims(
+ decoded_access_token,
+ {},
+ )
+ assert Group.objects.count() == 0
+
+ # when
+ user = get_user_from_oauth_access_token_in_jwt_format(
+ token_payload,
+ "https://example.com",
+ access_token="fake-token",
+ use_scope_permissions=False,
+ audience="",
+ staff_user_domains=[customer_user.email.split("@")[1]],
+ staff_default_group_name=staff_default_group_name,
+ )
+
+ # then
+ assert user.id == customer_user.id
+ assert user.is_staff is True
+ assert list(user.effective_permissions) == []
+ assert Group.objects.count() == 0
+ assert user.groups.count() == 0
+
+
+ "email, expected_domain",
+ [
+ ("[email protected]", "example.com"),
+ ("ABCd", None),
+ ("", None),
+ ("test.test", None),
+ ],
+)
+def test_get_domain_from_email(email, expected_domain):
+ # when
+ domain = get_domain_from_email(email)
+
+ # then
+ assert domain == expected_domain
+
+
+def test_assign_staff_to_default_group_and_update_permissions_new_group_created(
+ staff_user,
+):
+ # given
+ assert Group.objects.count() == 0
+ default_group_name = "test default group"
+
+ # when
+ assign_staff_to_default_group_and_update_permissions(staff_user, default_group_name)
+
+ # then
+ assert Group.objects.count() == 1
+ group = Group.objects.get()
+ assert group.name == default_group_name
+ assert group in staff_user.groups.all()
+
+
+def test_assign_staff_to_default_group_and_update_permissions_update_user_permissions(
+ staff_user, permission_manage_orders, permission_manage_users
+):
+ # given
+ default_group_name = "test default group"
+ group = Group.objects.create(name=default_group_name)
+ group.permissions.add(permission_manage_users)
+
+ staff_user.effective_permissions = Permission.objects.filter(
+ id=permission_manage_orders.id
+ )
+
+ # when
+ assign_staff_to_default_group_and_update_permissions(
+ staff_user, "test default group"
+ )
+
+ # then
+ assert group in staff_user.groups.all()
+ assert {perm.name for perm in staff_user.effective_permissions} == {
+ permission_manage_users.name,
+ permission_manage_orders.name,
+ }
diff --git a/saleor/plugins/openid_connect/utils.py b/saleor/plugins/openid_connect/utils.py
index bf11de2684..eeb75c35dd 100644
--- a/saleor/plugins/openid_connect/utils.py
+++ b/saleor/plugins/openid_connect/utils.py
@@ -1,7 +1,7 @@
import json
import logging
from datetime import datetime
-from typing import List, Optional
+from typing import TYPE_CHECKING, List, Optional
import requests
from authlib.jose import JWTClaims, jwt
@@ -15,7 +15,8 @@ from django.db.models import QuerySet
from django.utils.timezone import make_aware
from jwt import PyJWTError
-from ...account.models import User
+from ...account.models import Group, User
+from ...account.utils import get_user_groups_permissions
from ...core.jwt import (
JWT_ACCESS_TYPE,
JWT_OWNER_FIELD,
@@ -37,6 +38,9 @@ from . import PLUGIN_ID
from .const import SALEOR_STAFF_PERMISSION
from .exceptions import AuthenticationError
+if TYPE_CHECKING:
+ from .dataclasses import OpenIDConnectConfig
+
JWKS_KEY = "oauth_jwks"
JWKS_CACHE_TIME = 60 * 60 # 1 hour
USER_INFO_DEFAULT_CACHE_TIME = 60 * 60 # 1 hour
@@ -155,6 +159,8 @@ def get_user_from_oauth_access_token_in_jwt_format(
access_token: str,
use_scope_permissions: bool,
audience: str,
+ staff_user_domains: List[str],
+ staff_default_group_name: str,
):
try:
token_payload.validate()
@@ -179,7 +185,9 @@ def get_user_from_oauth_access_token_in_jwt_format(
try:
user = get_or_create_user_from_payload(
- user_info, user_info_url, last_login=token_payload.get("iat")
+ user_info,
+ user_info_url,
+ last_login=token_payload.get("iat"),
)
except AuthenticationError as e:
logger.info("Unable to create a user object", extra={"error": e})
@@ -197,24 +205,37 @@ def get_user_from_oauth_access_token_in_jwt_format(
else:
audience_in_token = audience == aud
+ is_staff = None
+ email_domain = get_domain_from_email(user.email)
+ is_staff_email = email_domain in staff_user_domains
is_staff_id = SALEOR_STAFF_PERMISSION
-
- if use_scope_permissions and audience_in_token:
+ if (use_scope_permissions and audience_in_token) or is_staff_email:
permissions = get_saleor_permissions_qs_from_scope(scope)
if not permissions and token_permissions:
permissions = get_saleor_permissions_from_list(token_permissions)
user.effective_permissions = permissions
+
is_staff_in_scope = is_staff_id in scope
is_staff_in_token_permissions = is_staff_id in token_permissions
- if is_staff_in_scope or is_staff_in_token_permissions or permissions:
+ if (
+ is_staff_email
+ or is_staff_in_scope
+ or is_staff_in_token_permissions
+ or permissions
+ ):
+ assign_staff_to_default_group_and_update_permissions(
+ user, staff_default_group_name
+ )
if not user.is_staff:
- user.is_staff = True
- user.save(update_fields=["is_staff"])
+ is_staff = True
elif user.is_staff:
- user.is_staff = False
- user.save(update_fields=["is_staff"])
+ is_staff = False
else:
- user.is_staff = False
+ is_staff = False
+
+ if is_staff is not None:
+ user.is_staff = is_staff
+ user.save(update_fields=["is_staff"])
return user
@@ -225,6 +246,8 @@ def get_user_from_oauth_access_token(
user_info_url: str,
use_scope_permissions: bool,
audience: str,
+ staff_user_domains: List[str],
+ staff_default_group_name: str,
):
# we try to decode token to define if the structure is a jwt format.
access_token_jwt_payload = decode_access_token(access_token, jwks_url)
@@ -235,6 +258,8 @@ def get_user_from_oauth_access_token(
access_token=access_token,
use_scope_permissions=use_scope_permissions,
audience=audience,
+ staff_user_domains=staff_user_domains,
+ staff_default_group_name=staff_default_group_name,
)
user_info = get_user_info_from_cache_or_fetch(
@@ -245,12 +270,43 @@ def get_user_from_oauth_access_token(
"Failed to fetch OIDC user info", extra={"user_info_url": user_info_url}
)
return None
- user = get_or_create_user_from_payload(user_info, oauth_url=user_info_url)
- if not use_scope_permissions:
+ user = get_or_create_user_from_payload(
+ user_info,
+ oauth_url=user_info_url,
+ )
+
+ email_domain = get_domain_from_email(user.email)
+ is_staff_email = email_domain in staff_user_domains
+ if not use_scope_permissions and not is_staff_email:
user.is_staff = False
+ elif is_staff_email:
+ assign_staff_to_default_group_and_update_permissions(
+ user, staff_default_group_name
+ )
+
return user
+def assign_staff_to_default_group_and_update_permissions(
+ user: "User", default_group_name: str
+):
+ """Assign staff user to the default permission group. and update user permissions.
+
+ If the group doesn't exist, the new group without any assigned permissions and
+ channels will be created.
+ """
+ default_group_name = (
+ default_group_name.strip() if default_group_name else default_group_name
+ )
+ if default_group_name:
+ group, _ = Group.objects.get_or_create(
+ name=default_group_name, defaults={"restricted_access_to_channels": True}
+ )
+ user.groups.add(group)
+ group_permissions = get_user_groups_permissions(user)
+ user.effective_permissions |= group_permissions
+
+
def create_jwt_token(
id_payload: CodeIDToken,
user: User,
@@ -314,7 +370,9 @@ def get_parsed_id_token(token_data, jwks_url) -> CodeIDToken:
def get_or_create_user_from_payload(
- payload: dict, oauth_url: str, last_login: Optional[int] = None
+ payload: dict,
+ oauth_url: str,
+ last_login: Optional[int] = None,
) -> User:
oidc_metadata_key = f"oidc-{oauth_url}"
user_email = payload.get("email")
@@ -363,8 +421,18 @@ def get_or_create_user_from_payload(
return user
+def get_domain_from_email(email: str):
+ """Return domain from the email."""
+ _user, delim, domain = email.rpartition("@")
+ return domain if delim else None
+
+
def _update_user_details(
- user: User, oidc_key: str, user_email: str, sub: str, last_login: Optional[int]
+ user: User,
+ oidc_key: str,
+ user_email: str,
+ sub: str,
+ last_login: Optional[int],
):
user_sub = user.get_value_from_private_metadata(oidc_key)
fields_to_save = []
@@ -391,6 +459,18 @@ def _update_user_details(
user.save(update_fields=fields_to_save)
+def get_staff_user_domains(
+ config: "OpenIDConnectConfig",
+):
+ """Return staff user domains for given gateway configuration."""
+ staff_domains = config.staff_user_domains
+ return (
+ [domain.strip().lower() for domain in staff_domains.split(",")]
+ if staff_domains
+ else []
+ )
+
+
def get_user_from_token(claims: CodeIDToken) -> User:
user_email = claims.get("email")
if not user_email:
diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.py
index 3c420743a1..292c85c5c8 100644
--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py
+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py
@@ -364,7 +364,7 @@ def test_order_shipping_methods(
mocked_webhook,
staff_api_client,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
settings,
):
# given
@@ -374,7 +374,7 @@ def test_order_shipping_methods(
mocked_webhook.return_value = [
ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)
]
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDER_QUERY_SHIPPING_METHOD)
content = get_graphql_content(response)
@@ -398,7 +398,7 @@ def test_order_available_shipping_methods(
mocked_webhook,
staff_api_client,
order_with_lines,
- permission_manage_orders,
+ permission_group_manage_orders,
settings,
webhook_response,
expected_count,
@@ -410,7 +410,7 @@ def test_order_available_shipping_methods(
return webhook_response(order_with_lines.shipping_method)
mocked_webhook.side_effect = respond
- staff_api_client.user.user_permissions.add(permission_manage_orders)
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
# when
response = staff_api_client.post_graphql(ORDER_QUERY_SHIPPING_METHOD)
content = get_graphql_content(response)
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 11b237bc1b..b0ff4f05e4 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -94,6 +94,7 @@ from ..payment.interface import AddressData, GatewayConfig, GatewayResponse, Pay
from ..payment.models import Payment, TransactionEvent, TransactionItem
from ..payment.transaction_item_calculations import recalculate_transaction_amounts
from ..payment.utils import create_manual_adjustment_events
+from ..permission.enums import get_permissions
from ..permission.models import Permission
from ..plugins.manager import get_plugins_manager
from ..plugins.webhook.tasks import WebhookResponse
@@ -1348,6 +1349,7 @@ def shipping_method_excluded_by_postal_code(shipping_method):
@pytest.fixture
def shipping_method_channel_PLN(shipping_zone, channel_PLN):
+ shipping_zone.channels.add(channel_PLN)
method = ShippingMethod.objects.create(
name="DHL",
type=ShippingMethodType.PRICE_BASED,
@@ -3312,6 +3314,16 @@ def order_list(customer_user, channel_USD):
return [order, order1, order2]
+def draft_order_list(order_list):
+ for order in order_list:
+ order.status = OrderStatus.DRAFT
+ order.origin = OrderOrigin.DRAFT
+
+ Order.objects.bulk_update(order_list, ["status", "origin"])
+ return order_list
+
+
@pytest.fixture
def product_with_image(product, image, media_root):
ProductMedia.objects.create(product=product, image=image)
@@ -5008,9 +5020,33 @@ def permission_manage_payments():
return Permission.objects.get(codename="handle_payments")
+def permission_group_manage_orders(permission_manage_orders, staff_users):
+ group = Group.objects.create(
+ name="Manage orders group.", restricted_access_to_channels=False
+ )
+ group.permissions.add(permission_manage_orders)
+
+ group.user_set.add(staff_users[1])
+ return group
+
+
+def permission_group_manage_shipping(permission_manage_shipping, staff_users):
+ group = Group.objects.create(
+ name="Manage shipping group.", restricted_access_to_channels=False
+ )
+ group.permissions.add(permission_manage_shipping)
+
+ group.user_set.add(staff_users[1])
+ return group
+
+
@pytest.fixture
def permission_group_manage_users(permission_manage_users, staff_users):
- group = Group.objects.create(name="Manage user groups.")
+ group = Group.objects.create(
+ name="Manage user group.", restricted_access_to_channels=False
+ )
group.permissions.add(permission_manage_users)
group.user_set.add(staff_users[1])
@@ -5019,13 +5055,81 @@ def permission_group_manage_users(permission_manage_users, staff_users):
@pytest.fixture
def permission_group_manage_staff(permission_manage_staff, staff_users):
- group = Group.objects.create(name="Manage staff groups.")
+ group = Group.objects.create(
+ name="Manage staff group.", restricted_access_to_channels=False
+ )
group.permissions.add(permission_manage_staff)
group.user_set.add(staff_users[1])
return group
+def permission_group_manage_apps(permission_manage_apps, staff_users):
+ group = Group.objects.create(
+ name="Manage apps group.", restricted_access_to_channels=False
+ )
+ group.permissions.add(permission_manage_apps)
+
+ group.user_set.add(staff_users[1])
+ return group
+
+
+def permission_group_all_perms_all_channels(
+ permission_manage_users, staff_users, channel_USD, channel_PLN
+):
+ group = Group.objects.create(
+ name="All permissions for all channels.",
+ restricted_access_to_channels=False,
+ )
+ permissions = get_permissions()
+ group.permissions.add(*permissions)
+
+ group.user_set.add(staff_users[1])
+ return group
+
+
+def permission_group_no_perms_all_channels(staff_users, channel_USD, channel_PLN):
+ group = Group.objects.create(
+ name="All permissions for all channels.",
+ restricted_access_to_channels=False,
+ )
+ group.user_set.add(staff_users[1])
+ return group
+
+
+def permission_group_all_perms_channel_USD_only(
+ permission_manage_users, staff_users, channel_USD, channel_PLN
+):
+ group = Group.objects.create(
+ name="All permissions for USD channel only.",
+ restricted_access_to_channels=True,
+ )
+ permissions = get_permissions()
+ group.permissions.add(*permissions)
+
+ group.channels.add(channel_USD)
+
+ group.user_set.add(staff_users[1])
+ return group
+
+
+def permission_group_all_perms_without_any_channel(
+ permission_manage_users, staff_users, channel_USD, channel_PLN
+):
+ group = Group.objects.create(
+ name="All permissions without any channel access.",
+ restricted_access_to_channels=True,
+ )
+ permissions = get_permissions()
+ group.permissions.add(*permissions)
+ return group
+
+
@pytest.fixture
def collection(db):
collection = Collection.objects.create(
diff --git a/saleor/tests/utils.py b/saleor/tests/utils.py
index fd25e64ce3..bd18d48214 100644
--- a/saleor/tests/utils.py
+++ b/saleor/tests/utils.py
@@ -11,9 +11,11 @@ def flush_post_commit_hooks():
for alias in connections:
connection = transaction.get_connection(alias)
was_atomic = connection.in_atomic_block
+ was_commit_on_exit = connection.commit_on_exit
connection.in_atomic_block = False
connection.run_and_clear_commit_hooks()
connection.in_atomic_block = was_atomic
+ connection.commit_on_exit = was_commit_on_exit
def dummy_editorjs(text, json_format=False):