Skip to content

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

Split shop module (#13149)

Iga Karbowiakb1b673819007
diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.py
deleted file mode 100644
index aeec61114c..0000000000
--- a/saleor/graphql/shop/mutations.py
+++ /dev/null
@@ -1,534 +0,0 @@
-import graphene
-from django.core.exceptions import ValidationError
-
-from ...account import models as account_models
-from ...channel import models as channel_models
-from ...core.error_codes import ShopErrorCode
-from ...core.utils.url import validate_storefront_url
-from ...permission.enums import GiftcardPermissions, OrderPermissions, SitePermissions
-from ...site import GiftCardSettingsExpiryType
-from ...site.error_codes import GiftCardSettingsErrorCode, OrderSettingsErrorCode
-from ...site.models import DEFAULT_LIMIT_QUANTITY_PER_CHECKOUT
-from ..account.i18n import I18nMixin
-from ..account.types import AddressInput, StaffNotificationRecipient
-from ..channel.types import OrderSettings
-from ..core import ResolveInfo
-from ..core.descriptions import ADDED_IN_31, ADDED_IN_314, DEPRECATED_IN_3X_INPUT
-from ..core.doc_category import (
- DOC_CATEGORY_GIFT_CARDS,
- DOC_CATEGORY_ORDERS,
- DOC_CATEGORY_SHOP,
-)
-from ..core.enums import WeightUnitsEnum
-from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
-from ..core.types import (
- BaseInputObjectType,
- GiftCardSettingsError,
- OrderSettingsError,
- ShopError,
- TimePeriodInputType,
-)
-from ..site.dataloaders import get_site_promise
-from .enums import GiftCardSettingsExpiryTypeEnum
-from .types import GiftCardSettings, Shop
-
-
-class ShopSettingsInput(graphene.InputObjectType):
- header_text = graphene.String(description="Header text.")
- description = graphene.String(description="SEO description.")
- track_inventory_by_default = graphene.Boolean(
- description="Enable inventory tracking."
- )
- default_weight_unit = WeightUnitsEnum(description="Default weight unit.")
- automatic_fulfillment_digital_products = graphene.Boolean(
- description="Enable automatic fulfillment for all digital products."
- )
- fulfillment_auto_approve = graphene.Boolean(
- description="Enable automatic approval of all new fulfillments." + ADDED_IN_31
- )
- fulfillment_allow_unpaid = graphene.Boolean(
- description=(
- "Enable ability to approve fulfillments which are unpaid." + ADDED_IN_31
- )
- )
- default_digital_max_downloads = graphene.Int(
- description="Default number of max downloads per digital content URL."
- )
- default_digital_url_valid_days = graphene.Int(
- description="Default number of days which digital content URL will be valid."
- )
- default_mail_sender_name = graphene.String(
- description="Default email sender's name."
- )
- default_mail_sender_address = graphene.String(
- description="Default email sender's address."
- )
- customer_set_password_url = graphene.String(
- description="URL of a view where customers can set their password."
- )
- reserve_stock_duration_anonymous_user = graphene.Int(
- description=(
- "Default number of minutes stock will be reserved for "
- "anonymous checkout. Enter 0 or null to disable." + ADDED_IN_31
- )
- )
- reserve_stock_duration_authenticated_user = graphene.Int(
- description=(
- "Default number of minutes stock will be reserved for "
- "authenticated checkout. Enter 0 or null to disable." + ADDED_IN_31
- )
- )
- limit_quantity_per_checkout = graphene.Int(
- description=(
- "Default number of maximum line quantity "
- "in single checkout. Minimum possible value is 1, default "
- f"value is {DEFAULT_LIMIT_QUANTITY_PER_CHECKOUT}." + ADDED_IN_31
- )
- )
-
- enable_account_confirmation_by_email = graphene.Boolean(
- description="Enable automatic account confirmation by email." + ADDED_IN_314
- )
-
- # deprecated
- include_taxes_in_prices = graphene.Boolean(
- description=(
- f"Include taxes in prices. {DEPRECATED_IN_3X_INPUT} Use "
- "`taxConfigurationUpdate` mutation to configure this setting per channel "
- "or country."
- )
- )
- display_gross_prices = graphene.Boolean(
- description=(
- f"Display prices with tax in store. {DEPRECATED_IN_3X_INPUT} Use "
- "`taxConfigurationUpdate` mutation to configure this setting per channel "
- "or country."
- )
- )
- charge_taxes_on_shipping = graphene.Boolean(
- description=(
- f"Charge taxes on shipping. {DEPRECATED_IN_3X_INPUT} To enable taxes for "
- "a shipping method, assign a tax class to the shipping method with "
- "`shippingPriceCreate` or `shippingPriceUpdate` mutations."
- ),
- )
-
-
-class SiteDomainInput(graphene.InputObjectType):
- domain = graphene.String(description="Domain name for shop.")
- name = graphene.String(description="Shop site name.")
-
- class Meta:
- doc_category = DOC_CATEGORY_SHOP
-
-
-class ShopSettingsUpdate(BaseMutation):
- shop = graphene.Field(Shop, description="Updated shop.")
-
- class Arguments:
- input = ShopSettingsInput(
- description="Fields required to update shop settings.", required=True
- )
-
- class Meta:
- description = "Updates shop settings."
- doc_category = DOC_CATEGORY_SHOP
- permissions = (SitePermissions.MANAGE_SETTINGS,)
- error_type_class = ShopError
- error_type_field = "shop_errors"
-
- @classmethod
- def clean_input(cls, _info, _instance, data):
- if data.get("customer_set_password_url"):
- try:
- validate_storefront_url(data["customer_set_password_url"])
- except ValidationError as error:
- raise ValidationError(
- {"customer_set_password_url": error},
- code=ShopErrorCode.INVALID.value,
- )
-
- if "reserve_stock_duration_anonymous_user" in data:
- new_value = data["reserve_stock_duration_anonymous_user"]
- if not new_value or new_value < 1:
- data["reserve_stock_duration_anonymous_user"] = None
- if "reserve_stock_duration_authenticated_user" in data:
- new_value = data["reserve_stock_duration_authenticated_user"]
- if not new_value or new_value < 1:
- data["reserve_stock_duration_authenticated_user"] = None
- if "limit_quantity_per_checkout" in data:
- new_value = data["limit_quantity_per_checkout"]
- if new_value is not None and new_value < 1:
- raise ValidationError(
- {
- "limit_quantity_per_checkout": ValidationError(
- "Quantity limit cannot be lower than 1.",
- code=ShopErrorCode.INVALID.value,
- )
- }
- )
- if not new_value:
- data["limit_quantity_per_checkout"] = None
-
- return data
-
- @classmethod
- def construct_instance(cls, instance, cleaned_data):
- for field_name, desired_value in cleaned_data.items():
- current_value = getattr(instance, field_name)
- if current_value != desired_value:
- setattr(instance, field_name, desired_value)
- return instance
-
- @classmethod
- def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
- site = get_site_promise(info.context).get()
- instance = site.settings
- data = data.get("input")
- cleaned_input = cls.clean_input(info, instance, data)
- instance = cls.construct_instance(instance, cleaned_input)
- cls.clean_instance(info, instance)
- instance.save()
- return ShopSettingsUpdate(shop=Shop())
-
-
-class ShopAddressUpdate(BaseMutation, I18nMixin):
- shop = graphene.Field(Shop, description="Updated shop.")
-
- class Arguments:
- input = AddressInput(description="Fields required to update shop address.")
-
- class Meta:
- description = (
- "Update the shop's address. If the `null` value is passed, the currently "
- "selected address will be deleted."
- )
- doc_category = DOC_CATEGORY_SHOP
- permissions = (SitePermissions.MANAGE_SETTINGS,)
- error_type_class = ShopError
- error_type_field = "shop_errors"
-
- @classmethod
- def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
- site = get_site_promise(info.context).get()
- data = data.get("input")
-
- if data:
- if not site.settings.company_address:
- company_address = account_models.Address()
- else:
- company_address = site.settings.company_address
- company_address = cls.validate_address(
- data, instance=company_address, info=info
- )
- company_address.save()
- site.settings.company_address = company_address
- site.settings.save(update_fields=["company_address"])
- else:
- if site.settings.company_address:
- site.settings.company_address.delete()
- return ShopAddressUpdate(shop=Shop())
-
-
-class ShopDomainUpdate(BaseMutation):
- shop = graphene.Field(Shop, description="Updated shop.")
-
- class Arguments:
- input = SiteDomainInput(description="Fields required to update site.")
-
- class Meta:
- description = "Updates site domain of the shop."
- doc_category = DOC_CATEGORY_SHOP
- permissions = (SitePermissions.MANAGE_SETTINGS,)
- error_type_class = ShopError
- error_type_field = "shop_errors"
-
- @classmethod
- def perform_mutation( # type: ignore[override]
- cls, _root, info: ResolveInfo, /, *, input
- ):
- site = get_site_promise(info.context).get()
- domain = input.get("domain")
- name = input.get("name")
- if domain is not None:
- site.domain = domain
- if name is not None:
- site.name = name
- cls.clean_instance(info, site)
- site.save()
- return ShopDomainUpdate(shop=Shop())
-
-
-class ShopFetchTaxRates(BaseMutation):
- shop = graphene.Field(Shop, description="Updated shop.")
-
- class Meta:
- description = "Fetch tax rates."
- doc_category = DOC_CATEGORY_SHOP
- permissions = (SitePermissions.MANAGE_SETTINGS,)
- error_type_class = ShopError
- error_type_field = "shop_errors"
-
- @classmethod
- def perform_mutation(cls, _root, _info: ResolveInfo, /):
- # This mutation is deprecated and will be removed in Saleor 4.0.
- return ShopFetchTaxRates(shop=Shop())
-
-
-class StaffNotificationRecipientInput(graphene.InputObjectType):
- user = graphene.ID(
- required=False,
- description="The ID of the user subscribed to email notifications..",
- )
- email = graphene.String(
- required=False,
- description="Email address of a user subscribed to email notifications.",
- )
- active = graphene.Boolean(
- required=False, description="Determines if a notification active."
- )
-
-
-class StaffNotificationRecipientCreate(ModelMutation):
- class Arguments:
- input = StaffNotificationRecipientInput(
- required=True,
- description="Fields required to create a staff notification recipient.",
- )
-
- class Meta:
- description = "Creates a new staff notification recipient."
- model = account_models.StaffNotificationRecipient
- object_type = StaffNotificationRecipient
- permissions = (SitePermissions.MANAGE_SETTINGS,)
- error_type_class = ShopError
- error_type_field = "shop_errors"
-
- @classmethod
- def clean_input(cls, info, instance, data):
- cleaned_input = super().clean_input(info, instance, data)
- cls.validate_input(instance, cleaned_input)
- email = cleaned_input.pop("email", None)
- if email:
- staff_user = account_models.User.objects.filter(email=email).first()
- if staff_user:
- cleaned_input["user"] = staff_user
- else:
- cleaned_input["staff_email"] = email
- return cleaned_input
-
- @staticmethod
- def validate_input(instance, cleaned_input):
- email = cleaned_input.get("email")
- user = cleaned_input.get("user")
- if not email and not user:
- if instance.id and "user" in cleaned_input or "email" in cleaned_input:
- raise ValidationError(
- {
- "staff_notification": ValidationError(
- "User and email cannot be set empty",
- code=ShopErrorCode.INVALID.value,
- )
- }
- )
- if not instance.id:
- raise ValidationError(
- {
- "staff_notification": ValidationError(
- "User or email is required",
- code=ShopErrorCode.REQUIRED.value,
- )
- }
- )
- if user and not user.is_staff:
- raise ValidationError(
- {
- "user": ValidationError(
- "User has to be staff user", code=ShopErrorCode.INVALID.value
- )
- }
- )
-
-
-class StaffNotificationRecipientUpdate(StaffNotificationRecipientCreate):
- class Arguments:
- id = graphene.ID(
- required=True, description="ID of a staff notification recipient to update."
- )
- input = StaffNotificationRecipientInput(
- required=True,
- description="Fields required to update a staff notification recipient.",
- )
-
- class Meta:
- description = "Updates a staff notification recipient."
- model = account_models.StaffNotificationRecipient
- object_type = StaffNotificationRecipient
- permissions = (SitePermissions.MANAGE_SETTINGS,)
- error_type_class = ShopError
- error_type_field = "shop_errors"
-
-
-class StaffNotificationRecipientDelete(ModelDeleteMutation):
- class Arguments:
- id = graphene.ID(
- required=True, description="ID of a staff notification recipient to delete."
- )
-
- class Meta:
- description = "Delete staff notification recipient."
- model = account_models.StaffNotificationRecipient
- object_type = StaffNotificationRecipient
- permissions = (SitePermissions.MANAGE_SETTINGS,)
- error_type_class = ShopError
- error_type_field = "shop_errors"
-
-
-class OrderSettingsUpdateInput(BaseInputObjectType):
- automatically_confirm_all_new_orders = graphene.Boolean(
- required=False,
- description="When disabled, all new orders from checkout "
- "will be marked as unconfirmed. When enabled orders from checkout will "
- "become unfulfilled immediately. By default set to True",
- )
- automatically_fulfill_non_shippable_gift_card = graphene.Boolean(
- required=False,
- description="When enabled, all non-shippable gift card orders "
- "will be fulfilled automatically. By defualt set to True.",
- )
-
- class Meta:
- doc_category = DOC_CATEGORY_ORDERS
-
-
-class OrderSettingsUpdate(BaseMutation):
- order_settings = graphene.Field(OrderSettings, description="Order settings.")
-
- class Arguments:
- input = OrderSettingsUpdateInput(
- required=True, description="Fields required to update shop order settings."
- )
-
- class Meta:
- description = (
- "Update shop order settings across all channels. "
- "Returns `orderSettings` for the first `channel` in alphabetical order. "
- )
- doc_category = DOC_CATEGORY_ORDERS
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderSettingsError
- error_type_field = "order_settings_errors"
-
- @classmethod
- def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
- FIELDS = [
- "automatically_confirm_all_new_orders",
- "automatically_fulfill_non_shippable_gift_card",
- ]
-
- channel = (
- channel_models.Channel.objects.filter(is_active=True)
- .order_by("slug")
- .first()
- )
-
- if channel is None:
- raise ValidationError(
- "There is no active channel available",
- code=OrderSettingsErrorCode.INVALID.value,
- )
-
- cls.check_channel_permissions(info, [channel.id])
-
- update_fields = {}
- for field in FIELDS:
- if field in data["input"]:
- update_fields[field] = data["input"][field]
-
- if update_fields:
- channel_models.Channel.objects.update(**update_fields)
-
- channel.refresh_from_db()
-
- order_settings = OrderSettings(
- automatically_confirm_all_new_orders=(
- channel.automatically_confirm_all_new_orders
- ),
- automatically_fulfill_non_shippable_gift_card=(
- channel.automatically_fulfill_non_shippable_gift_card
- ),
- mark_as_paid_strategy=channel.order_mark_as_paid_strategy,
- default_transaction_flow_strategy=(
- channel.default_transaction_flow_strategy
- ),
- )
- return OrderSettingsUpdate(order_settings=order_settings)
-
-
-class GiftCardSettingsUpdateInput(BaseInputObjectType):
- expiry_type = GiftCardSettingsExpiryTypeEnum(
- description="Defines gift card default expiry settings."
- )
- expiry_period = TimePeriodInputType(description="Defines gift card expiry period.")
-
- class Meta:
- doc_category = DOC_CATEGORY_GIFT_CARDS
-
-
-class GiftCardSettingsUpdate(BaseMutation):
- gift_card_settings = graphene.Field(
- GiftCardSettings, description="Gift card settings."
- )
-
- class Arguments:
- input = GiftCardSettingsUpdateInput(
- required=True, description="Fields required to update gift card settings."
- )
-
- class Meta:
- description = "Update gift card settings."
- doc_category = DOC_CATEGORY_GIFT_CARDS
- permissions = (GiftcardPermissions.MANAGE_GIFT_CARD,)
- error_type_class = GiftCardSettingsError
-
- @classmethod
- def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
- site = get_site_promise(info.context).get()
- instance = site.settings
- input = data["input"]
- cls.clean_input(input, instance)
-
- expiry_period = input.get("expiry_period")
- instance.gift_card_expiry_period_type = (
- expiry_period["type"] if expiry_period else None
- )
- instance.gift_card_expiry_period = (
- expiry_period["amount"] if expiry_period else None
- )
- update_fields = ["gift_card_expiry_period", "gift_card_expiry_period_type"]
-
- if expiry_type := input.get("expiry_type"):
- instance.gift_card_expiry_type = expiry_type
- update_fields.append("gift_card_expiry_type")
-
- instance.save(update_fields=update_fields)
- return GiftCardSettingsUpdate(gift_card_settings=instance)
-
- @staticmethod
- def clean_input(input, instance):
- expiry_type = input.get("expiry_type") or instance.gift_card_expiry_type
- if (
- expiry_type == GiftCardSettingsExpiryType.EXPIRY_PERIOD
- and input.get("expiry_period") is None
- ):
- raise ValidationError(
- {
- "expiry_period": ValidationError(
- "Expiry period settings are required for expiry period "
- "gift card settings.",
- code=GiftCardSettingsErrorCode.REQUIRED.value,
- )
- }
- )
- elif expiry_type == GiftCardSettingsExpiryType.NEVER_EXPIRE:
- input["expiry_period"] = None
diff --git a/saleor/graphql/shop/mutations/__init__.py b/saleor/graphql/shop/mutations/__init__.py
new file mode 100644
index 0000000000..852ea71c2c
--- /dev/null
+++ b/saleor/graphql/shop/mutations/__init__.py
@@ -0,0 +1,21 @@
+from .gift_card_settings_update import GiftCardSettingsUpdate
+from .order_settings_update import OrderSettingsUpdate
+from .shop_address_update import ShopAddressUpdate
+from .shop_domain_update import ShopDomainUpdate
+from .shop_fetch_tax_rates import ShopFetchTaxRates
+from .shop_settings_update import ShopSettingsUpdate
+from .staff_notification_recipient_create import StaffNotificationRecipientCreate
+from .staff_notification_recipient_delete import StaffNotificationRecipientDelete
+from .staff_notification_recipient_update import StaffNotificationRecipientUpdate
+
+__all__ = [
+ "GiftCardSettingsUpdate",
+ "OrderSettingsUpdate",
+ "ShopAddressUpdate",
+ "ShopDomainUpdate",
+ "ShopFetchTaxRates",
+ "ShopSettingsUpdate",
+ "StaffNotificationRecipientCreate",
+ "StaffNotificationRecipientDelete",
+ "StaffNotificationRecipientUpdate",
+]
diff --git a/saleor/graphql/shop/mutations/gift_card_settings_update.py b/saleor/graphql/shop/mutations/gift_card_settings_update.py
new file mode 100644
index 0000000000..56a272ce09
--- /dev/null
+++ b/saleor/graphql/shop/mutations/gift_card_settings_update.py
@@ -0,0 +1,86 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....permission.enums import GiftcardPermissions
+from ....site import GiftCardSettingsExpiryType
+from ....site.error_codes import GiftCardSettingsErrorCode
+from ...core import ResolveInfo
+from ...core.doc_category import DOC_CATEGORY_GIFT_CARDS
+from ...core.mutations import BaseMutation
+from ...core.types import (
+ BaseInputObjectType,
+ GiftCardSettingsError,
+ TimePeriodInputType,
+)
+from ...site.dataloaders import get_site_promise
+from ..enums import GiftCardSettingsExpiryTypeEnum
+from ..types import GiftCardSettings
+
+
+class GiftCardSettingsUpdateInput(BaseInputObjectType):
+ expiry_type = GiftCardSettingsExpiryTypeEnum(
+ description="Defines gift card default expiry settings."
+ )
+ expiry_period = TimePeriodInputType(description="Defines gift card expiry period.")
+
+ class Meta:
+ doc_category = DOC_CATEGORY_GIFT_CARDS
+
+
+class GiftCardSettingsUpdate(BaseMutation):
+ gift_card_settings = graphene.Field(
+ GiftCardSettings, description="Gift card settings."
+ )
+
+ class Arguments:
+ input = GiftCardSettingsUpdateInput(
+ required=True, description="Fields required to update gift card settings."
+ )
+
+ class Meta:
+ description = "Update gift card settings."
+ doc_category = DOC_CATEGORY_GIFT_CARDS
+ permissions = (GiftcardPermissions.MANAGE_GIFT_CARD,)
+ error_type_class = GiftCardSettingsError
+
+ @classmethod
+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ site = get_site_promise(info.context).get()
+ instance = site.settings
+ input = data["input"]
+ cls.clean_input(input, instance)
+
+ expiry_period = input.get("expiry_period")
+ instance.gift_card_expiry_period_type = (
+ expiry_period["type"] if expiry_period else None
+ )
+ instance.gift_card_expiry_period = (
+ expiry_period["amount"] if expiry_period else None
+ )
+ update_fields = ["gift_card_expiry_period", "gift_card_expiry_period_type"]
+
+ if expiry_type := input.get("expiry_type"):
+ instance.gift_card_expiry_type = expiry_type
+ update_fields.append("gift_card_expiry_type")
+
+ instance.save(update_fields=update_fields)
+ return GiftCardSettingsUpdate(gift_card_settings=instance)
+
+ @staticmethod
+ def clean_input(input, instance):
+ expiry_type = input.get("expiry_type") or instance.gift_card_expiry_type
+ if (
+ expiry_type == GiftCardSettingsExpiryType.EXPIRY_PERIOD
+ and input.get("expiry_period") is None
+ ):
+ raise ValidationError(
+ {
+ "expiry_period": ValidationError(
+ "Expiry period settings are required for expiry period "
+ "gift card settings.",
+ code=GiftCardSettingsErrorCode.REQUIRED.value,
+ )
+ }
+ )
+ elif expiry_type == GiftCardSettingsExpiryType.NEVER_EXPIRE:
+ input["expiry_period"] = None
diff --git a/saleor/graphql/shop/mutations/order_settings_update.py b/saleor/graphql/shop/mutations/order_settings_update.py
new file mode 100644
index 0000000000..2523081ef0
--- /dev/null
+++ b/saleor/graphql/shop/mutations/order_settings_update.py
@@ -0,0 +1,92 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....channel import models as channel_models
+from ....permission.enums import OrderPermissions
+from ....site.error_codes import OrderSettingsErrorCode
+from ...channel.types import OrderSettings
+from ...core import ResolveInfo
+from ...core.doc_category import DOC_CATEGORY_ORDERS
+from ...core.mutations import BaseMutation
+from ...core.types import BaseInputObjectType, OrderSettingsError
+
+
+class OrderSettingsUpdateInput(BaseInputObjectType):
+ automatically_confirm_all_new_orders = graphene.Boolean(
+ required=False,
+ description="When disabled, all new orders from checkout "
+ "will be marked as unconfirmed. When enabled orders from checkout will "
+ "become unfulfilled immediately. By default set to True",
+ )
+ automatically_fulfill_non_shippable_gift_card = graphene.Boolean(
+ required=False,
+ description="When enabled, all non-shippable gift card orders "
+ "will be fulfilled automatically. By defualt set to True.",
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_ORDERS
+
+
+class OrderSettingsUpdate(BaseMutation):
+ order_settings = graphene.Field(OrderSettings, description="Order settings.")
+
+ class Arguments:
+ input = OrderSettingsUpdateInput(
+ required=True, description="Fields required to update shop order settings."
+ )
+
+ class Meta:
+ description = (
+ "Update shop order settings across all channels. "
+ "Returns `orderSettings` for the first `channel` in alphabetical order. "
+ )
+ doc_category = DOC_CATEGORY_ORDERS
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderSettingsError
+ error_type_field = "order_settings_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ FIELDS = [
+ "automatically_confirm_all_new_orders",
+ "automatically_fulfill_non_shippable_gift_card",
+ ]
+
+ channel = (
+ channel_models.Channel.objects.filter(is_active=True)
+ .order_by("slug")
+ .first()
+ )
+
+ if channel is None:
+ raise ValidationError(
+ "There is no active channel available",
+ code=OrderSettingsErrorCode.INVALID.value,
+ )
+
+ cls.check_channel_permissions(info, [channel.id])
+
+ update_fields = {}
+ for field in FIELDS:
+ if field in data["input"]:
+ update_fields[field] = data["input"][field]
+
+ if update_fields:
+ channel_models.Channel.objects.update(**update_fields)
+
+ channel.refresh_from_db()
+
+ order_settings = OrderSettings(
+ automatically_confirm_all_new_orders=(
+ channel.automatically_confirm_all_new_orders
+ ),
+ automatically_fulfill_non_shippable_gift_card=(
+ channel.automatically_fulfill_non_shippable_gift_card
+ ),
+ mark_as_paid_strategy=channel.order_mark_as_paid_strategy,
+ default_transaction_flow_strategy=(
+ channel.default_transaction_flow_strategy
+ ),
+ )
+ return OrderSettingsUpdate(order_settings=order_settings)
diff --git a/saleor/graphql/shop/mutations/shop_address_update.py b/saleor/graphql/shop/mutations/shop_address_update.py
new file mode 100644
index 0000000000..8344dd5d46
--- /dev/null
+++ b/saleor/graphql/shop/mutations/shop_address_update.py
@@ -0,0 +1,50 @@
+import graphene
+
+from ....account import models as account_models
+from ....permission.enums import SitePermissions
+from ...account.i18n import I18nMixin
+from ...account.types import AddressInput
+from ...core import ResolveInfo
+from ...core.doc_category import DOC_CATEGORY_SHOP
+from ...core.mutations import BaseMutation
+from ...core.types import ShopError
+from ...site.dataloaders import get_site_promise
+from ..types import Shop
+
+
+class ShopAddressUpdate(BaseMutation, I18nMixin):
+ shop = graphene.Field(Shop, description="Updated shop.")
+
+ class Arguments:
+ input = AddressInput(description="Fields required to update shop address.")
+
+ class Meta:
+ description = (
+ "Update the shop's address. If the `null` value is passed, the currently "
+ "selected address will be deleted."
+ )
+ doc_category = DOC_CATEGORY_SHOP
+ permissions = (SitePermissions.MANAGE_SETTINGS,)
+ error_type_class = ShopError
+ error_type_field = "shop_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ site = get_site_promise(info.context).get()
+ data = data.get("input")
+
+ if data:
+ if not site.settings.company_address:
+ company_address = account_models.Address()
+ else:
+ company_address = site.settings.company_address
+ company_address = cls.validate_address(
+ data, instance=company_address, info=info
+ )
+ company_address.save()
+ site.settings.company_address = company_address
+ site.settings.save(update_fields=["company_address"])
+ else:
+ if site.settings.company_address:
+ site.settings.company_address.delete()
+ return ShopAddressUpdate(shop=Shop())
diff --git a/saleor/graphql/shop/mutations/shop_domain_update.py b/saleor/graphql/shop/mutations/shop_domain_update.py
new file mode 100644
index 0000000000..dfd314d2b3
--- /dev/null
+++ b/saleor/graphql/shop/mutations/shop_domain_update.py
@@ -0,0 +1,46 @@
+import graphene
+
+from ....permission.enums import SitePermissions
+from ...core import ResolveInfo
+from ...core.doc_category import DOC_CATEGORY_SHOP
+from ...core.mutations import BaseMutation
+from ...core.types import ShopError
+from ...site.dataloaders import get_site_promise
+from ..types import Shop
+
+
+class SiteDomainInput(graphene.InputObjectType):
+ domain = graphene.String(description="Domain name for shop.")
+ name = graphene.String(description="Shop site name.")
+
+ class Meta:
+ doc_category = DOC_CATEGORY_SHOP
+
+
+class ShopDomainUpdate(BaseMutation):
+ shop = graphene.Field(Shop, description="Updated shop.")
+
+ class Arguments:
+ input = SiteDomainInput(description="Fields required to update site.")
+
+ class Meta:
+ description = "Updates site domain of the shop."
+ doc_category = DOC_CATEGORY_SHOP
+ permissions = (SitePermissions.MANAGE_SETTINGS,)
+ error_type_class = ShopError
+ error_type_field = "shop_errors"
+
+ @classmethod
+ def perform_mutation( # type: ignore[override]
+ cls, _root, info: ResolveInfo, /, *, input
+ ):
+ site = get_site_promise(info.context).get()
+ domain = input.get("domain")
+ name = input.get("name")
+ if domain is not None:
+ site.domain = domain
+ if name is not None:
+ site.name = name
+ cls.clean_instance(info, site)
+ site.save()
+ return ShopDomainUpdate(shop=Shop())
diff --git a/saleor/graphql/shop/mutations/shop_fetch_tax_rates.py b/saleor/graphql/shop/mutations/shop_fetch_tax_rates.py
new file mode 100644
index 0000000000..019a159f51
--- /dev/null
+++ b/saleor/graphql/shop/mutations/shop_fetch_tax_rates.py
@@ -0,0 +1,24 @@
+import graphene
+
+from ....permission.enums import SitePermissions
+from ...core import ResolveInfo
+from ...core.doc_category import DOC_CATEGORY_SHOP
+from ...core.mutations import BaseMutation
+from ...core.types import ShopError
+from ..types import Shop
+
+
+class ShopFetchTaxRates(BaseMutation):
+ shop = graphene.Field(Shop, description="Updated shop.")
+
+ class Meta:
+ description = "Fetch tax rates."
+ doc_category = DOC_CATEGORY_SHOP
+ permissions = (SitePermissions.MANAGE_SETTINGS,)
+ error_type_class = ShopError
+ error_type_field = "shop_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, _info: ResolveInfo, /):
+ # This mutation is deprecated and will be removed in Saleor 4.0.
+ return ShopFetchTaxRates(shop=Shop())
diff --git a/saleor/graphql/shop/mutations/shop_settings_update.py b/saleor/graphql/shop/mutations/shop_settings_update.py
new file mode 100644
index 0000000000..6a083bd9d5
--- /dev/null
+++ b/saleor/graphql/shop/mutations/shop_settings_update.py
@@ -0,0 +1,166 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.error_codes import ShopErrorCode
+from ....core.utils.url import validate_storefront_url
+from ....permission.enums import SitePermissions
+from ....site.models import DEFAULT_LIMIT_QUANTITY_PER_CHECKOUT
+from ...core import ResolveInfo
+from ...core.descriptions import ADDED_IN_31, ADDED_IN_314, DEPRECATED_IN_3X_INPUT
+from ...core.doc_category import DOC_CATEGORY_SHOP
+from ...core.enums import WeightUnitsEnum
+from ...core.mutations import BaseMutation
+from ...core.types import ShopError
+from ...site.dataloaders import get_site_promise
+from ..types import Shop
+
+
+class ShopSettingsInput(graphene.InputObjectType):
+ header_text = graphene.String(description="Header text.")
+ description = graphene.String(description="SEO description.")
+ track_inventory_by_default = graphene.Boolean(
+ description="Enable inventory tracking."
+ )
+ default_weight_unit = WeightUnitsEnum(description="Default weight unit.")
+ automatic_fulfillment_digital_products = graphene.Boolean(
+ description="Enable automatic fulfillment for all digital products."
+ )
+ fulfillment_auto_approve = graphene.Boolean(
+ description="Enable automatic approval of all new fulfillments." + ADDED_IN_31
+ )
+ fulfillment_allow_unpaid = graphene.Boolean(
+ description=(
+ "Enable ability to approve fulfillments which are unpaid." + ADDED_IN_31
+ )
+ )
+ default_digital_max_downloads = graphene.Int(
+ description="Default number of max downloads per digital content URL."
+ )
+ default_digital_url_valid_days = graphene.Int(
+ description="Default number of days which digital content URL will be valid."
+ )
+ default_mail_sender_name = graphene.String(
+ description="Default email sender's name."
+ )
+ default_mail_sender_address = graphene.String(
+ description="Default email sender's address."
+ )
+ customer_set_password_url = graphene.String(
+ description="URL of a view where customers can set their password."
+ )
+ reserve_stock_duration_anonymous_user = graphene.Int(
+ description=(
+ "Default number of minutes stock will be reserved for "
+ "anonymous checkout. Enter 0 or null to disable." + ADDED_IN_31
+ )
+ )
+ reserve_stock_duration_authenticated_user = graphene.Int(
+ description=(
+ "Default number of minutes stock will be reserved for "
+ "authenticated checkout. Enter 0 or null to disable." + ADDED_IN_31
+ )
+ )
+ limit_quantity_per_checkout = graphene.Int(
+ description=(
+ "Default number of maximum line quantity "
+ "in single checkout. Minimum possible value is 1, default "
+ f"value is {DEFAULT_LIMIT_QUANTITY_PER_CHECKOUT}." + ADDED_IN_31
+ )
+ )
+
+ enable_account_confirmation_by_email = graphene.Boolean(
+ description="Enable automatic account confirmation by email." + ADDED_IN_314
+ )
+
+ # deprecated
+ include_taxes_in_prices = graphene.Boolean(
+ description=(
+ f"Include taxes in prices. {DEPRECATED_IN_3X_INPUT} Use "
+ "`taxConfigurationUpdate` mutation to configure this setting per channel "
+ "or country."
+ )
+ )
+ display_gross_prices = graphene.Boolean(
+ description=(
+ f"Display prices with tax in store. {DEPRECATED_IN_3X_INPUT} Use "
+ "`taxConfigurationUpdate` mutation to configure this setting per channel "
+ "or country."
+ )
+ )
+ charge_taxes_on_shipping = graphene.Boolean(
+ description=(
+ f"Charge taxes on shipping. {DEPRECATED_IN_3X_INPUT} To enable taxes for "
+ "a shipping method, assign a tax class to the shipping method with "
+ "`shippingPriceCreate` or `shippingPriceUpdate` mutations."
+ ),
+ )
+
+
+class ShopSettingsUpdate(BaseMutation):
+ shop = graphene.Field(Shop, description="Updated shop.")
+
+ class Arguments:
+ input = ShopSettingsInput(
+ description="Fields required to update shop settings.", required=True
+ )
+
+ class Meta:
+ description = "Updates shop settings."
+ doc_category = DOC_CATEGORY_SHOP
+ permissions = (SitePermissions.MANAGE_SETTINGS,)
+ error_type_class = ShopError
+ error_type_field = "shop_errors"
+
+ @classmethod
+ def clean_input(cls, _info, _instance, data):
+ if data.get("customer_set_password_url"):
+ try:
+ validate_storefront_url(data["customer_set_password_url"])
+ except ValidationError as error:
+ raise ValidationError(
+ {"customer_set_password_url": error},
+ code=ShopErrorCode.INVALID.value,
+ )
+
+ if "reserve_stock_duration_anonymous_user" in data:
+ new_value = data["reserve_stock_duration_anonymous_user"]
+ if not new_value or new_value < 1:
+ data["reserve_stock_duration_anonymous_user"] = None
+ if "reserve_stock_duration_authenticated_user" in data:
+ new_value = data["reserve_stock_duration_authenticated_user"]
+ if not new_value or new_value < 1:
+ data["reserve_stock_duration_authenticated_user"] = None
+ if "limit_quantity_per_checkout" in data:
+ new_value = data["limit_quantity_per_checkout"]
+ if new_value is not None and new_value < 1:
+ raise ValidationError(
+ {
+ "limit_quantity_per_checkout": ValidationError(
+ "Quantity limit cannot be lower than 1.",
+ code=ShopErrorCode.INVALID.value,
+ )
+ }
+ )
+ if not new_value:
+ data["limit_quantity_per_checkout"] = None
+
+ return data
+
+ @classmethod
+ def construct_instance(cls, instance, cleaned_data):
+ for field_name, desired_value in cleaned_data.items():
+ current_value = getattr(instance, field_name)
+ if current_value != desired_value:
+ setattr(instance, field_name, desired_value)
+ return instance
+
+ @classmethod
+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ site = get_site_promise(info.context).get()
+ instance = site.settings
+ data = data.get("input")
+ cleaned_input = cls.clean_input(info, instance, data)
+ instance = cls.construct_instance(instance, cleaned_input)
+ cls.clean_instance(info, instance)
+ instance.save()
+ return ShopSettingsUpdate(shop=Shop())
diff --git a/saleor/graphql/shop/mutations/staff_notification_recipient_create.py b/saleor/graphql/shop/mutations/staff_notification_recipient_create.py
new file mode 100644
index 0000000000..486713a4ae
--- /dev/null
+++ b/saleor/graphql/shop/mutations/staff_notification_recipient_create.py
@@ -0,0 +1,84 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....account import models as account_models
+from ....core.error_codes import ShopErrorCode
+from ....permission.enums import SitePermissions
+from ...account.types import StaffNotificationRecipient
+from ...core.mutations import ModelMutation
+from ...core.types import ShopError
+
+
+class StaffNotificationRecipientInput(graphene.InputObjectType):
+ user = graphene.ID(
+ required=False,
+ description="The ID of the user subscribed to email notifications..",
+ )
+ email = graphene.String(
+ required=False,
+ description="Email address of a user subscribed to email notifications.",
+ )
+ active = graphene.Boolean(
+ required=False, description="Determines if a notification active."
+ )
+
+
+class StaffNotificationRecipientCreate(ModelMutation):
+ class Arguments:
+ input = StaffNotificationRecipientInput(
+ required=True,
+ description="Fields required to create a staff notification recipient.",
+ )
+
+ class Meta:
+ description = "Creates a new staff notification recipient."
+ model = account_models.StaffNotificationRecipient
+ object_type = StaffNotificationRecipient
+ permissions = (SitePermissions.MANAGE_SETTINGS,)
+ error_type_class = ShopError
+ error_type_field = "shop_errors"
+
+ @classmethod
+ def clean_input(cls, info, instance, data):
+ cleaned_input = super().clean_input(info, instance, data)
+ cls.validate_input(instance, cleaned_input)
+ email = cleaned_input.pop("email", None)
+ if email:
+ staff_user = account_models.User.objects.filter(email=email).first()
+ if staff_user:
+ cleaned_input["user"] = staff_user
+ else:
+ cleaned_input["staff_email"] = email
+ return cleaned_input
+
+ @staticmethod
+ def validate_input(instance, cleaned_input):
+ email = cleaned_input.get("email")
+ user = cleaned_input.get("user")
+ if not email and not user:
+ if instance.id and "user" in cleaned_input or "email" in cleaned_input:
+ raise ValidationError(
+ {
+ "staff_notification": ValidationError(
+ "User and email cannot be set empty",
+ code=ShopErrorCode.INVALID.value,
+ )
+ }
+ )
+ if not instance.id:
+ raise ValidationError(
+ {
+ "staff_notification": ValidationError(
+ "User or email is required",
+ code=ShopErrorCode.REQUIRED.value,
+ )
+ }
+ )
+ if user and not user.is_staff:
+ raise ValidationError(
+ {
+ "user": ValidationError(
+ "User has to be staff user", code=ShopErrorCode.INVALID.value
+ )
+ }
+ )
diff --git a/saleor/graphql/shop/mutations/staff_notification_recipient_delete.py b/saleor/graphql/shop/mutations/staff_notification_recipient_delete.py
new file mode 100644
index 0000000000..c54529035f
--- /dev/null
+++ b/saleor/graphql/shop/mutations/staff_notification_recipient_delete.py
@@ -0,0 +1,22 @@
+import graphene
+
+from ....account import models as account_models
+from ....permission.enums import SitePermissions
+from ...account.types import StaffNotificationRecipient
+from ...core.mutations import ModelDeleteMutation
+from ...core.types import ShopError
+
+
+class StaffNotificationRecipientDelete(ModelDeleteMutation):
+ class Arguments:
+ id = graphene.ID(
+ required=True, description="ID of a staff notification recipient to delete."
+ )
+
+ class Meta:
+ description = "Delete staff notification recipient."
+ model = account_models.StaffNotificationRecipient
+ object_type = StaffNotificationRecipient
+ permissions = (SitePermissions.MANAGE_SETTINGS,)
+ error_type_class = ShopError
+ error_type_field = "shop_errors"
diff --git a/saleor/graphql/shop/mutations/staff_notification_recipient_update.py b/saleor/graphql/shop/mutations/staff_notification_recipient_update.py
new file mode 100644
index 0000000000..7c85ea15b5
--- /dev/null
+++ b/saleor/graphql/shop/mutations/staff_notification_recipient_update.py
@@ -0,0 +1,29 @@
+import graphene
+
+from ....account import models as account_models
+from ....permission.enums import SitePermissions
+from ...account.types import StaffNotificationRecipient
+from ...core.types import ShopError
+from .staff_notification_recipient_create import (
+ StaffNotificationRecipientCreate,
+ StaffNotificationRecipientInput,
+)
+
+
+class StaffNotificationRecipientUpdate(StaffNotificationRecipientCreate):
+ class Arguments:
+ id = graphene.ID(
+ required=True, description="ID of a staff notification recipient to update."
+ )
+ input = StaffNotificationRecipientInput(
+ required=True,
+ description="Fields required to update a staff notification recipient.",
+ )
+
+ class Meta:
+ description = "Updates a staff notification recipient."
+ model = account_models.StaffNotificationRecipient
+ object_type = StaffNotificationRecipient
+ permissions = (SitePermissions.MANAGE_SETTINGS,)
+ error_type_class = ShopError
+ error_type_field = "shop_errors"
diff --git a/saleor/graphql/shop/tests/mutations/__init__.py b/saleor/graphql/shop/tests/mutations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/shop/tests/test_gift_card_settings_update.py b/saleor/graphql/shop/tests/mutations/test_gift_card_settings_update.py
similarity index 95%
rename from saleor/graphql/shop/tests/test_gift_card_settings_update.py
rename to saleor/graphql/shop/tests/mutations/test_gift_card_settings_update.py
index f4d0e4c450..79dcb0d2a0 100644
--- a/saleor/graphql/shop/tests/test_gift_card_settings_update.py
+++ b/saleor/graphql/shop/tests/mutations/test_gift_card_settings_update.py
@@ -1,9 +1,9 @@
-from ....core import TimePeriodType
-from ....site import GiftCardSettingsExpiryType
-from ....site.error_codes import GiftCardSettingsErrorCode
-from ...core.enums import TimePeriodTypeEnum
-from ...tests.utils import assert_no_permission, get_graphql_content
-from ..enums import GiftCardSettingsExpiryTypeEnum
+from .....core import TimePeriodType
+from .....site import GiftCardSettingsExpiryType
+from .....site.error_codes import GiftCardSettingsErrorCode
+from ....core.enums import TimePeriodTypeEnum
+from ....tests.utils import assert_no_permission, get_graphql_content
+from ...enums import GiftCardSettingsExpiryTypeEnum
GIFT_CARD_SETTINGS_UPDATE_MUTATION = """
mutation giftCardSettingsUpdate($input: GiftCardSettingsUpdateInput!) {
diff --git a/saleor/graphql/shop/tests/mutations/test_order_settings_update.py b/saleor/graphql/shop/tests/mutations/test_order_settings_update.py
new file mode 100644
index 0000000000..42f8f8f785
--- /dev/null
+++ b/saleor/graphql/shop/tests/mutations/test_order_settings_update.py
@@ -0,0 +1,159 @@
+from ....channel.enums import TransactionFlowStrategyEnum
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+ORDER_SETTINGS_UPDATE_MUTATION = """
+ mutation orderSettings($confirmOrders: Boolean, $fulfillGiftCards: Boolean) {
+ orderSettingsUpdate(
+ input: {
+ automaticallyConfirmAllNewOrders: $confirmOrders
+ automaticallyFulfillNonShippableGiftCard: $fulfillGiftCards
+ }
+ ) {
+ orderSettings {
+ automaticallyConfirmAllNewOrders
+ automaticallyFulfillNonShippableGiftCard
+ markAsPaidStrategy
+ defaultTransactionFlowStrategy
+ }
+ }
+ }
+"""
+
+
+def test_order_settings_update_by_staff(
+ staff_api_client, permission_group_manage_orders, channel_USD, channel_PLN
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(
+ ORDER_SETTINGS_UPDATE_MUTATION,
+ {"confirmOrders": False, "fulfillGiftCards": False},
+ )
+ content = get_graphql_content(response)
+
+ # then
+ response_settings = content["data"]["orderSettingsUpdate"]["orderSettings"]
+ assert response_settings["automaticallyConfirmAllNewOrders"] is False
+ assert response_settings["automaticallyFulfillNonShippableGiftCard"] is False
+ assert (
+ response_settings["defaultTransactionFlowStrategy"]
+ == TransactionFlowStrategyEnum.CHARGE.name
+ == channel_USD.default_transaction_flow_strategy.upper()
+ )
+ channel_PLN.refresh_from_db()
+ channel_USD.refresh_from_db()
+ assert channel_PLN.automatically_confirm_all_new_orders is False
+ assert channel_PLN.automatically_fulfill_non_shippable_gift_card is False
+ assert channel_USD.automatically_confirm_all_new_orders is False
+ 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_group_manage_orders, channel_USD, channel_PLN
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ QUERY = """
+ mutation {
+ orderSettingsUpdate(
+ input: {}
+ ) {
+ orderSettings {
+ automaticallyConfirmAllNewOrders
+ automaticallyFulfillNonShippableGiftCard
+ }
+ }
+ }
+ """
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY,
+ {},
+ )
+ content = get_graphql_content(response)
+
+ # then
+ response_settings = content["data"]["orderSettingsUpdate"]["orderSettings"]
+ assert response_settings["automaticallyConfirmAllNewOrders"] is True
+ assert response_settings["automaticallyFulfillNonShippableGiftCard"] is True
+ channel_PLN.refresh_from_db()
+ channel_USD.refresh_from_db()
+ assert channel_PLN.automatically_confirm_all_new_orders is True
+ assert channel_PLN.automatically_fulfill_non_shippable_gift_card is True
+ assert channel_USD.automatically_confirm_all_new_orders is True
+ assert channel_USD.automatically_fulfill_non_shippable_gift_card is True
+
+
+def test_order_settings_update_by_app(
+ app_api_client, permission_manage_orders, channel_USD, channel_PLN
+):
+ # given
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ # when
+ response = app_api_client.post_graphql(
+ ORDER_SETTINGS_UPDATE_MUTATION,
+ {"confirmOrders": False, "fulfillGiftCards": False},
+ )
+ content = get_graphql_content(response)
+
+ # then
+ response_settings = content["data"]["orderSettingsUpdate"]["orderSettings"]
+ assert response_settings["automaticallyConfirmAllNewOrders"] is False
+ assert response_settings["automaticallyFulfillNonShippableGiftCard"] is False
+ assert (
+ response_settings["defaultTransactionFlowStrategy"]
+ == TransactionFlowStrategyEnum.CHARGE.name
+ == channel_USD.default_transaction_flow_strategy.upper()
+ )
+ channel_PLN.refresh_from_db()
+ channel_USD.refresh_from_db()
+ assert channel_PLN.automatically_confirm_all_new_orders is False
+ assert channel_PLN.automatically_fulfill_non_shippable_gift_card is False
+ assert channel_USD.automatically_confirm_all_new_orders is False
+ assert channel_USD.automatically_fulfill_non_shippable_gift_card is False
+
+
+def test_order_settings_update_by_user_without_permissions(
+ user_api_client, channel_USD, channel_PLN
+):
+ # given
+
+ # when
+ response = user_api_client.post_graphql(
+ ORDER_SETTINGS_UPDATE_MUTATION,
+ {"confirmOrders": False, "fulfillGiftCards": False},
+ )
+
+ # then
+ assert_no_permission(response)
+ channel_PLN.refresh_from_db()
+ channel_USD.refresh_from_db()
+ assert channel_PLN.automatically_confirm_all_new_orders is True
+ assert channel_PLN.automatically_fulfill_non_shippable_gift_card is True
+ assert channel_USD.automatically_confirm_all_new_orders is True
+ assert channel_USD.automatically_fulfill_non_shippable_gift_card is True
diff --git a/saleor/graphql/shop/tests/mutations/test_shop_address_update.py b/saleor/graphql/shop/tests/mutations/test_shop_address_update.py
new file mode 100644
index 0000000000..dba610045a
--- /dev/null
+++ b/saleor/graphql/shop/tests/mutations/test_shop_address_update.py
@@ -0,0 +1,92 @@
+from .....account.models import Address
+from ....tests.utils import get_graphql_content
+
+MUTATION_SHOP_ADDRESS_UPDATE = """
+ mutation updateShopAddress($input: AddressInput){
+ shopAddressUpdate(input: $input){
+ errors{
+ field
+ message
+ }
+ }
+ }
+"""
+
+
+def test_mutation_update_company_address(
+ staff_api_client,
+ permission_manage_settings,
+ address,
+ site_settings,
+):
+ # given
+ variables = {
+ "input": {
+ "streetAddress1": address.street_address_1,
+ "city": address.city,
+ "country": address.country.code,
+ "postalCode": address.postal_code,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_SHOP_ADDRESS_UPDATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert "errors" not in content["data"]
+
+ site_settings.refresh_from_db()
+ assert site_settings.company_address
+ assert site_settings.company_address.street_address_1 == address.street_address_1
+ assert site_settings.company_address.city == address.city
+ assert site_settings.company_address.country.code == address.country.code
+
+
+def test_mutation_update_company_address_remove_address(
+ staff_api_client, permission_manage_settings, site_settings, address
+):
+ # given
+ site_settings.company_address = address
+ site_settings.save(update_fields=["company_address"])
+ variables = {"input": None}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_SHOP_ADDRESS_UPDATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert "errors" not in content["data"]
+
+ site_settings.refresh_from_db()
+ assert not site_settings.company_address
+ assert not Address.objects.filter(pk=address.pk).exists()
+
+
+def test_mutation_update_company_address_remove_address_without_address(
+ staff_api_client, permission_manage_settings, site_settings
+):
+ # given
+ variables = {"input": None}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_SHOP_ADDRESS_UPDATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert "errors" not in content["data"]
+
+ site_settings.refresh_from_db()
+ assert not site_settings.company_address
diff --git a/saleor/graphql/shop/tests/mutations/test_shop_domain_update.py b/saleor/graphql/shop/tests/mutations/test_shop_domain_update.py
new file mode 100644
index 0000000000..3b07a4b13e
--- /dev/null
+++ b/saleor/graphql/shop/tests/mutations/test_shop_domain_update.py
@@ -0,0 +1,36 @@
+from .....site.models import Site
+from ....tests.utils import get_graphql_content
+
+
+def test_shop_domain_update(staff_api_client, permission_manage_settings):
+ # given
+ query = """
+ mutation updateSettings($input: SiteDomainInput!) {
+ shopDomainUpdate(input: $input) {
+ shop {
+ name
+ domain {
+ host,
+ }
+ }
+ }
+ }
+ """
+ new_name = "saleor test store"
+ variables = {"input": {"domain": "lorem-ipsum.com", "name": new_name}}
+ site = Site.objects.get_current()
+ assert site.domain != "lorem-ipsum.com"
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shopDomainUpdate"]["shop"]
+ assert data["domain"]["host"] == "lorem-ipsum.com"
+ assert data["name"] == new_name
+ site.refresh_from_db()
+ assert site.domain == "lorem-ipsum.com"
+ assert site.name == new_name
diff --git a/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py
new file mode 100644
index 0000000000..fd78b70635
--- /dev/null
+++ b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py
@@ -0,0 +1,405 @@
+from unittest.mock import ANY
+
+import pytest
+
+from .....core.error_codes import ShopErrorCode
+from .....site.models import Site
+from ....tests.utils import get_graphql_content
+
+SHOP_SETTINGS_UPDATE_MUTATION = """
+ mutation updateSettings($input: ShopSettingsInput!) {
+ shopSettingsUpdate(input: $input) {
+ shop {
+ automaticFulfillmentDigitalProducts
+ defaultDigitalMaxDownloads
+ defaultDigitalUrlValidDays
+ headerText,
+ includeTaxesInPrices,
+ chargeTaxesOnShipping,
+ fulfillmentAutoApprove,
+ fulfillmentAllowUnpaid
+ enableAccountConfirmationByEmail
+ reserveStockDurationAnonymousUser
+ reserveStockDurationAuthenticatedUser
+ limitQuantityPerCheckout
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
+def test_shop_digital_content_settings_mutation(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ # given
+ query = SHOP_SETTINGS_UPDATE_MUTATION
+
+ max_downloads = 15
+ url_valid_days = 30
+ variables = {
+ "input": {
+ "automaticFulfillmentDigitalProducts": True,
+ "defaultDigitalMaxDownloads": max_downloads,
+ "defaultDigitalUrlValidDays": url_valid_days,
+ }
+ }
+
+ assert not site_settings.automatic_fulfillment_digital_products
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["shopSettingsUpdate"]["shop"]
+ assert data["automaticFulfillmentDigitalProducts"]
+ assert data["defaultDigitalMaxDownloads"]
+ assert data["defaultDigitalUrlValidDays"]
+ site_settings.refresh_from_db()
+ assert site_settings.automatic_fulfillment_digital_products
+ assert site_settings.default_digital_max_downloads == max_downloads
+ assert site_settings.default_digital_url_valid_days == url_valid_days
+
+
+def test_shop_settings_mutation(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ # given
+ query = SHOP_SETTINGS_UPDATE_MUTATION
+ assert site_settings.enable_account_confirmation_by_email
+ charge_taxes_on_shipping = site_settings.charge_taxes_on_shipping
+ new_charge_taxes_on_shipping = not charge_taxes_on_shipping
+ variables = {
+ "input": {
+ "includeTaxesInPrices": False,
+ "headerText": "Lorem ipsum",
+ "chargeTaxesOnShipping": new_charge_taxes_on_shipping,
+ "fulfillmentAllowUnpaid": False,
+ "enableAccountConfirmationByEmail": False,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["shopSettingsUpdate"]["shop"]
+
+ # then
+ assert data["headerText"] == "Lorem ipsum"
+ assert data["includeTaxesInPrices"] is False
+ assert data["chargeTaxesOnShipping"] == new_charge_taxes_on_shipping
+ assert data["fulfillmentAutoApprove"] is True
+ assert data["fulfillmentAllowUnpaid"] is False
+ assert data["enableAccountConfirmationByEmail"] is False
+
+ site_settings.refresh_from_db()
+ assert not site_settings.include_taxes_in_prices
+ assert site_settings.charge_taxes_on_shipping == new_charge_taxes_on_shipping
+ assert site_settings.enable_account_confirmation_by_email is False
+
+
+def test_shop_reservation_settings_mutation(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ # given
+ query = SHOP_SETTINGS_UPDATE_MUTATION
+ variables = {
+ "input": {
+ "reserveStockDurationAnonymousUser": 42,
+ "reserveStockDurationAuthenticatedUser": 24,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shopSettingsUpdate"]["shop"]
+ assert data["reserveStockDurationAnonymousUser"] == 42
+ assert data["reserveStockDurationAuthenticatedUser"] == 24
+ site_settings.refresh_from_db()
+ assert site_settings.reserve_stock_duration_anonymous_user == 42
+ assert site_settings.reserve_stock_duration_authenticated_user == 24
+
+
+def test_shop_reservation_disable_settings_mutation(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ # given
+ query = SHOP_SETTINGS_UPDATE_MUTATION
+ variables = {
+ "input": {
+ "reserveStockDurationAnonymousUser": None,
+ "reserveStockDurationAuthenticatedUser": None,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shopSettingsUpdate"]["shop"]
+ assert data["reserveStockDurationAnonymousUser"] is None
+ assert data["reserveStockDurationAuthenticatedUser"] is None
+ site_settings.refresh_from_db()
+ assert site_settings.reserve_stock_duration_anonymous_user is None
+ assert site_settings.reserve_stock_duration_authenticated_user is None
+
+
+def test_shop_reservation_set_negative_settings_mutation(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ # given
+ query = SHOP_SETTINGS_UPDATE_MUTATION
+ variables = {
+ "input": {
+ "reserveStockDurationAnonymousUser": -14,
+ "reserveStockDurationAuthenticatedUser": -6,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shopSettingsUpdate"]["shop"]
+ assert data["reserveStockDurationAnonymousUser"] is None
+ assert data["reserveStockDurationAuthenticatedUser"] is None
+ site_settings.refresh_from_db()
+ assert site_settings.reserve_stock_duration_anonymous_user is None
+ assert site_settings.reserve_stock_duration_authenticated_user is None
+
+
[email protected]("quantity_value", [25, 1, None])
+def test_limit_quantity_per_checkout_mutation(
+ staff_api_client, site_settings, permission_manage_settings, quantity_value
+):
+ # given
+ query = SHOP_SETTINGS_UPDATE_MUTATION
+ variables = {"input": {"limitQuantityPerCheckout": quantity_value}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shopSettingsUpdate"]["shop"]
+ site_settings.refresh_from_db()
+
+ assert data["limitQuantityPerCheckout"] == quantity_value
+ assert site_settings.limit_quantity_per_checkout == quantity_value
+
+
[email protected]("quantity_value", [0, -25])
+def test_limit_quantity_per_checkout_neg_or_zero_value(
+ staff_api_client, site_settings, permission_manage_settings, quantity_value
+):
+ # given
+ query = SHOP_SETTINGS_UPDATE_MUTATION
+ variables = {"input": {"limitQuantityPerCheckout": quantity_value}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["shopSettingsUpdate"]["errors"]
+ site_settings.refresh_from_db()
+
+ assert len(errors) == 1
+ assert errors.pop() == {
+ "field": "limitQuantityPerCheckout",
+ "message": "Quantity limit cannot be lower than 1.",
+ "code": ShopErrorCode.INVALID.name,
+ }
+
+ assert site_settings.limit_quantity_per_checkout == 50 # default
+
+
+def test_shop_customer_set_password_url_update(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ # given
+ customer_set_password_url = "http://www.example.com/set_pass/"
+ variables = {"input": {"customerSetPasswordUrl": customer_set_password_url}}
+ assert site_settings.customer_set_password_url != customer_set_password_url
+
+ # when
+ response = staff_api_client.post_graphql(
+ SHOP_SETTINGS_UPDATE_MUTATION,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shopSettingsUpdate"]
+ assert not data["errors"]
+ Site.objects.clear_cache()
+ site_settings = Site.objects.get_current().settings
+ assert site_settings.customer_set_password_url == customer_set_password_url
+
+
+ "customer_set_password_url",
+ [
+ ("http://not-allowed-storefron.com/pass"),
+ ("http://[value-error-in-urlparse@test/pass"),
+ ("without-protocole.com/pass"),
+ ],
+)
+def test_shop_customer_set_password_url_update_invalid_url(
+ staff_api_client,
+ site_settings,
+ permission_manage_settings,
+ customer_set_password_url,
+):
+ # given
+ variables = {"input": {"customerSetPasswordUrl": customer_set_password_url}}
+ assert not site_settings.customer_set_password_url
+
+ # when
+ response = staff_api_client.post_graphql(
+ SHOP_SETTINGS_UPDATE_MUTATION,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shopSettingsUpdate"]
+ assert data["errors"][0] == {
+ "field": "customerSetPasswordUrl",
+ "code": ShopErrorCode.INVALID.name,
+ "message": ANY,
+ }
+ site_settings.refresh_from_db()
+ assert not site_settings.customer_set_password_url
+
+
+MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS = """
+ mutation updateDefaultSenderSettings($input: ShopSettingsInput!) {
+ shopSettingsUpdate(input: $input) {
+ shop {
+ defaultMailSenderName
+ defaultMailSenderAddress
+ }
+ errors {
+ field
+ message
+ }
+ }
+ }
+"""
+
+
+def test_update_default_sender_settings(staff_api_client, permission_manage_settings):
+ # given
+ query = MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS
+
+ variables = {
+ "input": {
+ "defaultMailSenderName": "Dummy Name",
+ "defaultMailSenderAddress": "[email protected]",
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["shopSettingsUpdate"]["shop"]
+ assert data["defaultMailSenderName"] == "Dummy Name"
+ assert data["defaultMailSenderAddress"] == "[email protected]"
+
+
+ "sender_name",
+ (
+ "\nDummy Name",
+ "\rDummy Name",
+ "Dummy Name\r",
+ "Dummy Name\n",
+ "Dummy\rName",
+ "Dummy\nName",
+ ),
+)
+def test_update_default_sender_settings_invalid_name(
+ staff_api_client, permission_manage_settings, sender_name
+):
+ # given
+ query = MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS
+
+ variables = {"input": {"defaultMailSenderName": sender_name}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ errors = content["data"]["shopSettingsUpdate"]["errors"]
+ assert errors == [
+ {"field": "defaultMailSenderName", "message": "New lines are not allowed."}
+ ]
+
+
+ "sender_email",
+ (
+ "dummy@example\r.com",
+ "dummy@example\n.com",
+ ),
+)
+def test_update_default_sender_settings_invalid_email(
+ staff_api_client, permission_manage_settings, sender_email
+):
+ # given
+ query = MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS
+
+ variables = {"input": {"defaultMailSenderAddress": sender_email}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ errors = content["data"]["shopSettingsUpdate"]["errors"]
+ assert errors == [
+ {"field": "defaultMailSenderAddress", "message": "Enter a valid email address."}
+ ]
diff --git a/saleor/graphql/shop/tests/mutations/test_staff_notification_recipient_create.py b/saleor/graphql/shop/tests/mutations/test_staff_notification_recipient_create.py
new file mode 100644
index 0000000000..e9eab4d061
--- /dev/null
+++ b/saleor/graphql/shop/tests/mutations/test_staff_notification_recipient_create.py
@@ -0,0 +1,170 @@
+import graphene
+
+from ....tests.utils import get_graphql_content
+
+MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE = """
+ mutation StaffNotificationRecipient ($input: StaffNotificationRecipientInput!) {
+ staffNotificationRecipientCreate(input: $input) {
+ staffNotificationRecipient {
+ active
+ email
+ user {
+ id
+ firstName
+ lastName
+ email
+ }
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
+def test_staff_notification_create_mutation(
+ staff_api_client, staff_user, permission_manage_settings
+):
+ # given
+ user_id = graphene.Node.to_global_id("User", staff_user.id)
+ variables = {"input": {"user": user_id}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["staffNotificationRecipientCreate"] == {
+ "staffNotificationRecipient": {
+ "active": True,
+ "email": staff_user.email,
+ "user": {
+ "id": user_id,
+ "firstName": staff_user.first_name,
+ "lastName": staff_user.last_name,
+ "email": staff_user.email,
+ },
+ },
+ "errors": [],
+ }
+
+
+def test_staff_notification_create_mutation_with_staffs_email(
+ staff_api_client, staff_user, permission_manage_settings
+):
+ # given
+ user_id = graphene.Node.to_global_id("User", staff_user.id)
+ variables = {"input": {"email": staff_user.email}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["staffNotificationRecipientCreate"] == {
+ "staffNotificationRecipient": {
+ "active": True,
+ "email": staff_user.email,
+ "user": {
+ "id": user_id,
+ "firstName": staff_user.first_name,
+ "lastName": staff_user.last_name,
+ "email": staff_user.email,
+ },
+ },
+ "errors": [],
+ }
+
+
+def test_staff_notification_create_mutation_with_customer_user(
+ staff_api_client, customer_user, permission_manage_settings
+):
+ # given
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variables = {"input": {"user": user_id}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["staffNotificationRecipientCreate"] == {
+ "staffNotificationRecipient": None,
+ "errors": [
+ {"code": "INVALID", "field": "user", "message": "User has to be staff user"}
+ ],
+ }
+
+
+def test_staff_notification_create_mutation_with_email(
+ staff_api_client, permission_manage_settings, permission_manage_staff
+):
+ # given
+ staff_email = "[email protected]"
+ variables = {"input": {"email": staff_email}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
+ variables,
+ permissions=[permission_manage_settings, permission_manage_staff],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["staffNotificationRecipientCreate"] == {
+ "staffNotificationRecipient": {
+ "active": True,
+ "email": staff_email,
+ "user": None,
+ },
+ "errors": [],
+ }
+
+
+def test_staff_notification_create_mutation_with_empty_email(
+ staff_api_client, permission_manage_settings
+):
+ # given
+ staff_email = ""
+ variables = {"input": {"email": staff_email}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["staffNotificationRecipientCreate"] == {
+ "staffNotificationRecipient": None,
+ "errors": [
+ {
+ "code": "INVALID",
+ "field": "staffNotification",
+ "message": "User and email cannot be set empty",
+ }
+ ],
+ }
diff --git a/saleor/graphql/shop/tests/mutations/test_staff_notification_recipient_update.py b/saleor/graphql/shop/tests/mutations/test_staff_notification_recipient_update.py
new file mode 100644
index 0000000000..5acb5469a6
--- /dev/null
+++ b/saleor/graphql/shop/tests/mutations/test_staff_notification_recipient_update.py
@@ -0,0 +1,124 @@
+import graphene
+
+from ....tests.utils import get_graphql_content
+
+MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE = """
+ mutation StaffNotificationRecipient (
+ $id: ID!,
+ $input: StaffNotificationRecipientInput!
+ ) {
+ staffNotificationRecipientUpdate(id: $id, input: $input) {
+ staffNotificationRecipient {
+ active
+ email
+ user {
+ firstName
+ lastName
+ email
+ }
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
+def test_staff_notification_update_mutation(
+ staff_api_client,
+ staff_user,
+ permission_manage_settings,
+ staff_notification_recipient,
+):
+ # given
+ old_email = staff_notification_recipient.get_email()
+ assert staff_notification_recipient.active
+ staff_notification_recipient_id = graphene.Node.to_global_id(
+ "StaffNotificationRecipient", staff_notification_recipient.id
+ )
+ variables = {"id": staff_notification_recipient_id, "input": {"active": False}}
+
+ # when
+ staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+
+ # then
+ staff_notification_recipient.refresh_from_db()
+ assert not staff_notification_recipient.active
+ assert staff_notification_recipient.get_email() == old_email
+
+
+def test_staff_notification_update_mutation_with_empty_user(
+ staff_api_client,
+ staff_user,
+ permission_manage_settings,
+ staff_notification_recipient,
+):
+ # given
+ staff_notification_recipient_id = graphene.Node.to_global_id(
+ "StaffNotificationRecipient", staff_notification_recipient.id
+ )
+ variables = {"id": staff_notification_recipient_id, "input": {"user": ""}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ staff_notification_recipient.refresh_from_db()
+ assert content["data"]["staffNotificationRecipientUpdate"] == {
+ "staffNotificationRecipient": None,
+ "errors": [
+ {
+ "code": "INVALID",
+ "field": "staffNotification",
+ "message": "User and email cannot be set empty",
+ }
+ ],
+ }
+
+
+def test_staff_notification_update_mutation_with_empty_email(
+ staff_api_client,
+ staff_user,
+ permission_manage_settings,
+ staff_notification_recipient,
+):
+ # given
+ staff_notification_recipient_id = graphene.Node.to_global_id(
+ "StaffNotificationRecipient", staff_notification_recipient.id
+ )
+ variables = {"id": staff_notification_recipient_id, "input": {"email": ""}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ staff_notification_recipient.refresh_from_db()
+ assert content["data"]["staffNotificationRecipientUpdate"] == {
+ "staffNotificationRecipient": None,
+ "errors": [
+ {
+ "code": "INVALID",
+ "field": "staffNotification",
+ "message": "User and email cannot be set empty",
+ }
+ ],
+ }
diff --git a/saleor/graphql/shop/tests/queries/__init__.py b/saleor/graphql/shop/tests/queries/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/shop/tests/queries/test_gift_card_settings.py b/saleor/graphql/shop/tests/queries/test_gift_card_settings.py
new file mode 100644
index 0000000000..9588068fb6
--- /dev/null
+++ b/saleor/graphql/shop/tests/queries/test_gift_card_settings.py
@@ -0,0 +1,101 @@
+from .....core import TimePeriodType
+from .....site import GiftCardSettingsExpiryType
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+GIFT_CARD_SETTINGS_QUERY = """
+ query giftCardSettings {
+ giftCardSettings {
+ expiryType
+ expiryPeriod {
+ type
+ amount
+ }
+ }
+ }
+"""
+
+
+def test_gift_card_settings_query_as_staff(
+ staff_api_client, permission_manage_gift_card, site_settings
+):
+ # given
+ assert site_settings.gift_card_expiry_period is None
+
+ staff_api_client.user.user_permissions.add(permission_manage_gift_card)
+
+ # when
+ response = staff_api_client.post_graphql(GIFT_CARD_SETTINGS_QUERY)
+
+ # then
+ content = get_graphql_content(response)
+
+ assert (
+ content["data"]["giftCardSettings"]["expiryType"]
+ == site_settings.gift_card_expiry_type.upper()
+ )
+ assert content["data"]["giftCardSettings"]["expiryPeriod"] is None
+
+
+def test_query_gift_card_settings_expiry_period(
+ staff_api_client, permission_manage_gift_card, site_settings
+):
+ # given
+ expiry_type = GiftCardSettingsExpiryType.EXPIRY_PERIOD
+ expiry_period_type = TimePeriodType.MONTH
+ expiry_period = 3
+ site_settings.gift_card_expiry_type = expiry_type
+ site_settings.gift_card_expiry_period_type = expiry_period_type
+ site_settings.gift_card_expiry_period = expiry_period
+ site_settings.save(
+ update_fields=[
+ "gift_card_expiry_type",
+ "gift_card_expiry_period_type",
+ "gift_card_expiry_period",
+ ]
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_gift_card)
+
+ # when
+ response = staff_api_client.post_graphql(GIFT_CARD_SETTINGS_QUERY)
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["giftCardSettings"]["expiryType"] == expiry_type.upper()
+ assert (
+ content["data"]["giftCardSettings"]["expiryPeriod"]["type"]
+ == expiry_period_type.upper()
+ )
+ assert (
+ content["data"]["giftCardSettings"]["expiryPeriod"]["amount"] == expiry_period
+ )
+
+
+def test_gift_card_settings_query_as_app(
+ app_api_client, permission_manage_gift_card, site_settings
+):
+ # given
+ assert site_settings.gift_card_expiry_period is None
+
+ # when
+ response = app_api_client.post_graphql(
+ GIFT_CARD_SETTINGS_QUERY, permissions=[permission_manage_gift_card]
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert (
+ content["data"]["giftCardSettings"]["expiryType"]
+ == site_settings.gift_card_expiry_type.upper()
+ )
+ assert content["data"]["giftCardSettings"]["expiryPeriod"] is None
+
+
+def test_gift_card_settings_query_as_user(user_api_client, site_settings):
+ # when
+ response = user_api_client.post_graphql(GIFT_CARD_SETTINGS_QUERY)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/shop/tests/queries/test_order_settings.py b/saleor/graphql/shop/tests/queries/test_order_settings.py
new file mode 100644
index 0000000000..0cb55f123f
--- /dev/null
+++ b/saleor/graphql/shop/tests/queries/test_order_settings.py
@@ -0,0 +1,68 @@
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+ORDER_SETTINGS_QUERY = """
+ query orderSettings {
+ orderSettings {
+ automaticallyConfirmAllNewOrders
+ automaticallyFulfillNonShippableGiftCard
+ }
+ }
+"""
+
+
+def test_order_settings_query_one_channel(
+ staff_api_client, permission_manage_orders, channel_USD
+):
+ # given
+ channel_USD.automatically_confirm_all_new_orders = False
+ channel_USD.automatically_fulfill_non_shippable_gift_card = True
+ channel_USD.save()
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_SETTINGS_QUERY)
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["orderSettings"]["automaticallyConfirmAllNewOrders"] is False
+ assert (
+ content["data"]["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
+ is True
+ )
+
+
+def test_order_settings_query_multiple_channels(
+ staff_api_client, permission_manage_orders, channel_USD, channel_PLN
+):
+ # given
+ channel_USD.automatically_confirm_all_new_orders = False
+ channel_USD.automatically_fulfill_non_shippable_gift_card = True
+ channel_USD.save()
+
+ channel_PLN.automatically_confirm_all_new_orders = True
+ channel_PLN.automatically_fulfill_non_shippable_gift_card = False
+ channel_PLN.save()
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_SETTINGS_QUERY)
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["orderSettings"]["automaticallyConfirmAllNewOrders"] is True
+ assert (
+ content["data"]["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
+ is False
+ )
+
+
+def test_order_settings_query_as_user(user_api_client, channel_USD, channel_PLN):
+ # when
+ response = user_api_client.post_graphql(ORDER_SETTINGS_QUERY)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/shop/tests/queries/test_shop.py b/saleor/graphql/shop/tests/queries/test_shop.py
new file mode 100644
index 0000000000..d1bcdb0e4f
--- /dev/null
+++ b/saleor/graphql/shop/tests/queries/test_shop.py
@@ -0,0 +1,832 @@
+import re
+
+import graphene
+import pytest
+from django_countries import countries
+
+from ..... import __version__
+from .....permission.enums import get_permissions_codename
+from .....shipping import PostalCodeRuleInclusionType
+from .....shipping.models import ShippingMethod
+from ....account.enums import CountryCodeEnum
+from ....core.utils import str_to_enum
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+COUNTRIES_QUERY = """
+ query {
+ shop {
+ countries%(attributes)s {
+ code
+ country
+ }
+ }
+ }
+"""
+
+
+def test_query_countries(user_api_client):
+ # when
+ response = user_api_client.post_graphql(COUNTRIES_QUERY % {"attributes": ""})
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]
+ assert len(data["countries"]) == len(countries)
+
+
+ "language_code, expected_value",
+ (
+ ("", "Afghanistan"),
+ ("(languageCode: EN)", "Afghanistan"),
+ ("(languageCode: PL)", "Afganistan"),
+ ("(languageCode: DE)", "Afghanistan"),
+ ),
+)
+def test_query_countries_with_translation(
+ language_code, expected_value, user_api_client
+):
+ # when
+ response = user_api_client.post_graphql(
+ COUNTRIES_QUERY % {"attributes": language_code}
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]
+ assert len(data["countries"]) == len(countries)
+ assert data["countries"][0]["code"] == "AF"
+ assert data["countries"][0]["country"] == expected_value
+
+
+LIMIT_INFO_QUERY = """
+ {
+ shop {
+ limits {
+ currentUsage {
+ channels
+ }
+ allowedUsage {
+ channels
+ }
+ }
+ }
+ }
+"""
+
+
+def test_cannot_get_shop_limit_info_when_not_staff(user_api_client):
+ # given
+ query = LIMIT_INFO_QUERY
+
+ # when
+ response = user_api_client.post_graphql(query)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_get_shop_limit_info_returns_null_by_default(staff_api_client):
+ # given
+ query = LIMIT_INFO_QUERY
+
+ # when
+ response = staff_api_client.post_graphql(query)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"] == {
+ "shop": {
+ "limits": {
+ "currentUsage": {"channels": None},
+ "allowedUsage": {"channels": None},
+ }
+ }
+ }
+
+
+API_VERSION_QUERY = """
+ query {
+ shop {
+ version
+ }
+ }
+"""
+
+
+def test_version_query_as_anonymous_user(api_client):
+ # when
+ response = api_client.post_graphql(API_VERSION_QUERY)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_version_query_as_customer(user_api_client):
+ # when
+ response = user_api_client.post_graphql(API_VERSION_QUERY)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_version_query_as_app(app_api_client):
+ # when
+ response = app_api_client.post_graphql(API_VERSION_QUERY)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["shop"]["version"] == __version__
+
+
+def test_version_query_as_staff_user(staff_api_client):
+ # when
+ response = staff_api_client.post_graphql(API_VERSION_QUERY)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["shop"]["version"] == __version__
+
+
+def test_schema_version_query(api_client):
+ # given
+ query = """
+ query {
+ shop {
+ schemaVersion
+ }
+ }
+ """
+ m = re.match(r"^(\d+)\.(\d+)\.\d+", __version__)
+ assert m is not None
+ major, minor = m.groups()
+
+ # when
+ response = api_client.post_graphql(query)
+ content = get_graphql_content(response)
+
+ # then
+ assert content["data"]["shop"]["schemaVersion"] == f"{major}.{minor}"
+
+
+CHANNEL_CURRENCIES_QUERY = """
+ query {
+ shop {
+ channelCurrencies
+ }
+ }
+"""
+
+
+def test_fetch_channel_currencies(
+ staff_api_client, channel_PLN, channel_USD, other_channel_USD
+):
+ # given
+ query = CHANNEL_CURRENCIES_QUERY
+
+ # when
+ response = staff_api_client.post_graphql(query)
+
+ # then
+ content = get_graphql_content(response)
+ assert set(content["data"]["shop"]["channelCurrencies"]) == {
+ channel_PLN.currency_code,
+ channel_USD.currency_code,
+ }
+
+
+def test_fetch_channel_currencies_by_app(
+ app_api_client, channel_PLN, channel_USD, other_channel_USD
+):
+ # given
+ query = CHANNEL_CURRENCIES_QUERY
+
+ # when
+ response = app_api_client.post_graphql(query)
+
+ # then
+ content = get_graphql_content(response)
+ assert set(content["data"]["shop"]["channelCurrencies"]) == {
+ channel_PLN.currency_code,
+ channel_USD.currency_code,
+ }
+
+
+def test_fetch_channel_currencies_by_customer(api_client, channel_PLN, channel_USD):
+ # given
+ query = CHANNEL_CURRENCIES_QUERY
+
+ # when
+ response = api_client.post_graphql(query)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_name(user_api_client, site_settings):
+ # given
+ query = """
+ query {
+ shop {
+ name
+ description
+ }
+ }
+ """
+
+ # when
+ response = user_api_client.post_graphql(query)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]
+ assert data["description"] == site_settings.description
+ assert data["name"] == site_settings.site.name
+
+
+def test_query_company_address(user_api_client, site_settings, address):
+ query = """
+ query {
+ shop{
+ companyAddress{
+ city
+ streetAddress1
+ postalCode
+ }
+ }
+ }
+ """
+ # given
+ site_settings.company_address = address
+ site_settings.save()
+
+ # when
+ response = user_api_client.post_graphql(query)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]
+ company_address = data["companyAddress"]
+ assert company_address["city"] == address.city
+ assert company_address["streetAddress1"] == address.street_address_1
+ assert company_address["postalCode"] == address.postal_code
+
+
+def test_query_domain(user_api_client, site_settings, settings):
+ # given
+ query = """
+ query {
+ shop {
+ domain {
+ host
+ sslEnabled
+ url
+ }
+ }
+ }
+ """
+
+ # when
+ response = user_api_client.post_graphql(query)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]
+ assert data["domain"]["host"] == site_settings.site.domain
+ assert data["domain"]["sslEnabled"] == settings.ENABLE_SSL
+ assert data["domain"]["url"]
+
+
+def test_query_languages(settings, user_api_client):
+ # given
+ query = """
+ query {
+ shop {
+ languages {
+ code
+ language
+ }
+ }
+ }
+ """
+
+ # when
+ response = user_api_client.post_graphql(query)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]
+ assert len(data["languages"]) == len(settings.LANGUAGES)
+
+
+def test_query_permissions(staff_api_client):
+ # given
+ query = """
+ query {
+ shop {
+ permissions {
+ code
+ name
+ }
+ }
+ }
+ """
+ permissions_codenames = set(get_permissions_codename())
+
+ # when
+ response = staff_api_client.post_graphql(query)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]
+ permissions = data["permissions"]
+ permissions_codes = {permission.get("code") for permission in permissions}
+ assert len(permissions_codes) == len(permissions_codenames)
+ for code in permissions_codes:
+ assert code in [str_to_enum(code) for code in permissions_codenames]
+
+
+def test_query_charge_taxes_on_shipping(api_client, site_settings):
+ # given
+ query = """
+ query {
+ shop {
+ chargeTaxesOnShipping
+ }
+ }"""
+
+ # when
+ response = api_client.post_graphql(query)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]
+ charge_taxes_on_shipping = site_settings.charge_taxes_on_shipping
+ assert data["chargeTaxesOnShipping"] == charge_taxes_on_shipping
+
+
+def test_query_digital_content_settings(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ # given
+ query = """
+ query {
+ shop {
+ automaticFulfillmentDigitalProducts
+ defaultDigitalMaxDownloads
+ defaultDigitalUrlValidDays
+ }
+ }"""
+
+ max_download = 2
+ url_valid_days = 3
+ site_settings.automatic_fulfillment_digital_products = True
+ site_settings.default_digital_max_downloads = max_download
+ site_settings.default_digital_url_valid_days = url_valid_days
+ site_settings.save()
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, permissions=[permission_manage_settings]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]
+ automatic_fulfillment = site_settings.automatic_fulfillment_digital_products
+ assert data["automaticFulfillmentDigitalProducts"] == automatic_fulfillment
+ assert data["defaultDigitalMaxDownloads"] == max_download
+ assert data["defaultDigitalUrlValidDays"] == url_valid_days
+
+
+QUERY_RETRIEVE_DEFAULT_MAIL_SENDER_SETTINGS = """
+ {
+ shop {
+ defaultMailSenderName
+ defaultMailSenderAddress
+ }
+ }
+"""
+
+
+def test_query_default_mail_sender_settings(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ # given
+ site_settings.default_mail_sender_name = "Mirumee Labs Info"
+ site_settings.default_mail_sender_address = "[email protected]"
+ site_settings.save(
+ update_fields=["default_mail_sender_name", "default_mail_sender_address"]
+ )
+
+ query = QUERY_RETRIEVE_DEFAULT_MAIL_SENDER_SETTINGS
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, permissions=[permission_manage_settings]
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["shop"]
+ assert data["defaultMailSenderName"] == "Mirumee Labs Info"
+ assert data["defaultMailSenderAddress"] == "[email protected]"
+
+
+def test_query_default_mail_sender_settings_not_set(
+ staff_api_client, site_settings, permission_manage_settings, settings
+):
+ # given
+ site_settings.default_mail_sender_name = ""
+ site_settings.default_mail_sender_address = None
+ site_settings.save(
+ update_fields=["default_mail_sender_name", "default_mail_sender_address"]
+ )
+
+ settings.DEFAULT_FROM_EMAIL = "[email protected]"
+
+ query = QUERY_RETRIEVE_DEFAULT_MAIL_SENDER_SETTINGS
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, permissions=[permission_manage_settings]
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["shop"]
+ assert data["defaultMailSenderName"] == ""
+ assert data["defaultMailSenderAddress"] is None
+
+
+def test_query_default_country(user_api_client, settings):
+ # given
+ settings.DEFAULT_COUNTRY = "US"
+ query = """
+ query {
+ shop {
+ defaultCountry {
+ code
+ country
+ }
+ }
+ }
+ """
+
+ # when
+ response = user_api_client.post_graphql(query)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]["defaultCountry"]
+ assert data["code"] == settings.DEFAULT_COUNTRY
+ assert data["country"] == "United States of America"
+
+
+AVAILABLE_EXTERNAL_AUTHENTICATIONS_QUERY = """
+ query{
+ shop {
+ availableExternalAuthentications{
+ id
+ name
+ }
+ }
+ }
+"""
+
+
+ "external_auths",
+ [
+ [{"id": "auth1", "name": "Auth-1"}],
+ [{"id": "auth1", "name": "Auth-1"}, {"id": "auth2", "name": "Auth-2"}],
+ [],
+ ],
+)
+def test_query_available_external_authentications(
+ external_auths, user_api_client, monkeypatch
+):
+ # given
+ monkeypatch.setattr(
+ "saleor.plugins.manager.PluginsManager.list_external_authentications",
+ lambda self, active_only: external_auths,
+ )
+ query = AVAILABLE_EXTERNAL_AUTHENTICATIONS_QUERY
+
+ # when
+ response = user_api_client.post_graphql(query)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]["availableExternalAuthentications"]
+ assert data == external_auths
+
+
+AVAILABLE_PAYMENT_GATEWAYS_QUERY = """
+ query Shop($currency: String){
+ shop {
+ availablePaymentGateways(currency: $currency) {
+ id
+ name
+ }
+ }
+ }
+"""
+
+
+def test_query_available_payment_gateways(user_api_client, sample_gateway, channel_USD):
+ # given
+ query = AVAILABLE_PAYMENT_GATEWAYS_QUERY
+
+ # when
+ response = user_api_client.post_graphql(query)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]["availablePaymentGateways"]
+ assert {gateway["id"] for gateway in data} == {
+ "mirumee.payments.dummy",
+ "sampleDummy.active",
+ }
+ assert {gateway["name"] for gateway in data} == {
+ "Dummy",
+ "SampleDummy",
+ }
+
+
+def test_query_available_payment_gateways_specified_currency_USD(
+ user_api_client, sample_gateway, channel_USD
+):
+ # given
+ query = AVAILABLE_PAYMENT_GATEWAYS_QUERY
+
+ # when
+ response = user_api_client.post_graphql(query, {"currency": "USD"})
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]["availablePaymentGateways"]
+ assert {gateway["id"] for gateway in data} == {
+ "mirumee.payments.dummy",
+ "sampleDummy.active",
+ }
+ assert {gateway["name"] for gateway in data} == {
+ "Dummy",
+ "SampleDummy",
+ }
+
+
+def test_query_available_payment_gateways_specified_currency_EUR(
+ user_api_client, sample_gateway, channel_USD
+):
+ # given
+ query = AVAILABLE_PAYMENT_GATEWAYS_QUERY
+
+ # when
+ response = user_api_client.post_graphql(query, {"currency": "EUR"})
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]["availablePaymentGateways"]
+ assert data[0]["id"] == "sampleDummy.active"
+ assert data[0]["name"] == "SampleDummy"
+
+
+AVAILABLE_SHIPPING_METHODS_QUERY = """
+ query Shop($channel: String!, $address: AddressInput){
+ shop {
+ availableShippingMethods(channel: $channel, address: $address) {
+ id
+ name
+ }
+ }
+ }
+"""
+
+
+def test_query_available_shipping_methods_no_address(
+ staff_api_client, shipping_method, shipping_method_channel_PLN, channel_USD
+):
+ # given
+ query = AVAILABLE_SHIPPING_METHODS_QUERY
+
+ # when
+ response = staff_api_client.post_graphql(query, {"channel": channel_USD.slug})
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]["availableShippingMethods"]
+ assert len(data) > 0
+ assert {ship_meth["id"] for ship_meth in data} == {
+ graphene.Node.to_global_id("ShippingMethod", ship_meth.pk)
+ for ship_meth in ShippingMethod.objects.filter(
+ shipping_zone__channels__slug=channel_USD.slug,
+ channel_listings__channel__slug=channel_USD.slug,
+ )
+ }
+
+
+def test_query_available_shipping_methods_no_channel_shipping_zones(
+ staff_api_client, shipping_method, shipping_method_channel_PLN, channel_USD
+):
+ # given
+ query = AVAILABLE_SHIPPING_METHODS_QUERY
+ channel_USD.shipping_zones.clear()
+
+ # when
+ response = staff_api_client.post_graphql(query, {"channel": channel_USD.slug})
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]["availableShippingMethods"]
+ assert len(data) == 0
+
+
+def test_query_available_shipping_methods_for_given_address(
+ staff_api_client,
+ channel_USD,
+ shipping_method,
+ shipping_zone_without_countries,
+ address,
+):
+ # given
+ query = AVAILABLE_SHIPPING_METHODS_QUERY
+ shipping_method_count = ShippingMethod.objects.count()
+ variables = {
+ "channel": channel_USD.slug,
+ "address": {"country": CountryCodeEnum.US.name},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]["availableShippingMethods"]
+ assert len(data) == shipping_method_count - 1
+ assert graphene.Node.to_global_id(
+ "ShippingMethodType",
+ shipping_zone_without_countries.shipping_methods.first().pk,
+ ) not in {ship_meth["id"] for ship_meth in data}
+
+
+def test_query_available_shipping_methods_for_excluded_postal_code(
+ staff_api_client, channel_USD, shipping_method
+):
+ # given
+ query = AVAILABLE_SHIPPING_METHODS_QUERY
+ variables = {
+ "channel": channel_USD.slug,
+ "address": {"country": CountryCodeEnum.PL.name, "postalCode": "53-601"},
+ }
+ shipping_method.postal_code_rules.create(
+ start="53-600", end="54-600", inclusion_type=PostalCodeRuleInclusionType.EXCLUDE
+ )
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]["availableShippingMethods"]
+ assert graphene.Node.to_global_id("ShippingMethodType", shipping_method.pk) not in {
+ ship_meth["id"] for ship_meth in data
+ }
+
+
+def test_query_available_shipping_methods_for_included_postal_code(
+ staff_api_client, channel_USD, shipping_method
+):
+ # given
+ query = AVAILABLE_SHIPPING_METHODS_QUERY
+ variables = {
+ "channel": channel_USD.slug,
+ "address": {"country": CountryCodeEnum.PL.name, "postalCode": "53-601"},
+ }
+ shipping_method.postal_code_rules.create(
+ start="53-600", end="54-600", inclusion_type=PostalCodeRuleInclusionType.INCLUDE
+ )
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shop"]["availableShippingMethods"]
+ assert graphene.Node.to_global_id("ShippingMethod", shipping_method.pk) in {
+ ship_meth["id"] for ship_meth in data
+ }
+
+
+def test_staff_notification_query(
+ staff_api_client,
+ staff_user,
+ permission_manage_settings,
+ staff_notification_recipient,
+):
+ # given
+ query = """
+ {
+ shop {
+ staffNotificationRecipients {
+ active
+ email
+ user {
+ firstName
+ lastName
+ email
+ }
+ }
+ }
+ }
+ """
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, permissions=[permission_manage_settings]
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["shop"]["staffNotificationRecipients"] == [
+ {
+ "active": True,
+ "email": staff_user.email,
+ "user": {
+ "firstName": staff_user.first_name,
+ "lastName": staff_user.last_name,
+ "email": staff_user.email,
+ },
+ }
+ ]
+
+
+COUNTRY_FILTER_QUERY = """
+ query($filter: CountryFilterInput!) {
+ shop {
+ countries(filter: $filter){
+ code
+ }
+ }
+ }
+
+"""
+
+
+def test_query_countries_filter_shiping_zones_attached_true(
+ user_api_client, shipping_zones
+):
+ # given
+ variables = {"filter": {"attachedToShippingZones": True}}
+ fixture_countries_code_set = {zone.countries[0].code for zone in shipping_zones}
+
+ # when
+ response = user_api_client.post_graphql(COUNTRY_FILTER_QUERY, variables=variables)
+ content = get_graphql_content(response)
+
+ data = content["data"]["shop"]["countries"]
+ countries_codes_results = {country["code"] for country in data}
+
+ # then
+ assert countries_codes_results == fixture_countries_code_set
+ assert len(data) == len(shipping_zones)
+
+
+def test_query_countries_filter_shiping_zones_attached_false(
+ user_api_client, shipping_zones
+):
+ # given
+ variables = {"filter": {"attachedToShippingZones": False}}
+ fixture_countries_code_set = {zone.countries[0].code for zone in shipping_zones}
+
+ # when
+ response = user_api_client.post_graphql(COUNTRY_FILTER_QUERY, variables=variables)
+ content = get_graphql_content(response)
+
+ data = content["data"]["shop"]["countries"]
+ countries_codes_results = {country["code"] for country in data}
+
+ # then
+ assert not any(
+ code in countries_codes_results for code in fixture_countries_code_set
+ )
+ assert len(data) == (len(countries) - len(shipping_zones))
+
+
+def test_query_countries_filter_shiping_zones_attached_none(
+ user_api_client, shipping_zones
+):
+ # given
+ variables = {"filter": {"attachedToShippingZones": None}}
+
+ # when
+ response = user_api_client.post_graphql(COUNTRY_FILTER_QUERY, variables=variables)
+ content = get_graphql_content(response)
+
+ data = content["data"]["shop"]["countries"]
+
+ # then
+ assert len(data) == len(countries)
diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.py
deleted file mode 100644
index 9eab2c103e..0000000000
--- a/saleor/graphql/shop/tests/test_shop.py
+++ /dev/null
@@ -1,1822 +0,0 @@
-import re
-from unittest.mock import ANY
-
-import graphene
-import pytest
-from django_countries import countries
-
-from .... import __version__
-from ....account.models import Address
-from ....core import TimePeriodType
-from ....core.error_codes import ShopErrorCode
-from ....permission.enums import get_permissions_codename
-from ....shipping import PostalCodeRuleInclusionType
-from ....shipping.models import ShippingMethod
-from ....site import GiftCardSettingsExpiryType
-from ....site.models import Site
-from ...account.enums import CountryCodeEnum
-from ...channel.enums import TransactionFlowStrategyEnum
-from ...core.utils import str_to_enum
-from ...tests.utils import assert_no_permission, get_graphql_content
-
-COUNTRIES_QUERY = """
- query {
- shop {
- countries%(attributes)s {
- code
- country
- }
- }
- }
-"""
-
-LIMIT_INFO_QUERY = """
- {
- shop {
- limits {
- currentUsage {
- channels
- }
- allowedUsage {
- channels
- }
- }
- }
- }
-"""
-
-
-def test_query_countries(user_api_client):
- response = user_api_client.post_graphql(COUNTRIES_QUERY % {"attributes": ""})
- content = get_graphql_content(response)
- data = content["data"]["shop"]
- assert len(data["countries"]) == len(countries)
-
-
- "language_code, expected_value",
- (
- ("", "Afghanistan"),
- ("(languageCode: EN)", "Afghanistan"),
- ("(languageCode: PL)", "Afganistan"),
- ("(languageCode: DE)", "Afghanistan"),
- ),
-)
-def test_query_countries_with_translation(
- language_code, expected_value, user_api_client
-):
- response = user_api_client.post_graphql(
- COUNTRIES_QUERY % {"attributes": language_code}
- )
- content = get_graphql_content(response)
- data = content["data"]["shop"]
- assert len(data["countries"]) == len(countries)
- assert data["countries"][0]["code"] == "AF"
- assert data["countries"][0]["country"] == expected_value
-
-
-def test_query_name(user_api_client, site_settings):
- query = """
- query {
- shop {
- name
- description
- }
- }
- """
- response = user_api_client.post_graphql(query)
- content = get_graphql_content(response)
- data = content["data"]["shop"]
- assert data["description"] == site_settings.description
- assert data["name"] == site_settings.site.name
-
-
-def test_query_company_address(user_api_client, site_settings, address):
- query = """
- query {
- shop{
- companyAddress{
- city
- streetAddress1
- postalCode
- }
- }
- }
- """
- site_settings.company_address = address
- site_settings.save()
- response = user_api_client.post_graphql(query)
- content = get_graphql_content(response)
- data = content["data"]["shop"]
- company_address = data["companyAddress"]
- assert company_address["city"] == address.city
- assert company_address["streetAddress1"] == address.street_address_1
- assert company_address["postalCode"] == address.postal_code
-
-
-def test_query_domain(user_api_client, site_settings, settings):
- query = """
- query {
- shop {
- domain {
- host
- sslEnabled
- url
- }
- }
- }
- """
- response = user_api_client.post_graphql(query)
- content = get_graphql_content(response)
- data = content["data"]["shop"]
- assert data["domain"]["host"] == site_settings.site.domain
- assert data["domain"]["sslEnabled"] == settings.ENABLE_SSL
- assert data["domain"]["url"]
-
-
-def test_query_languages(settings, user_api_client):
- query = """
- query {
- shop {
- languages {
- code
- language
- }
- }
- }
- """
- response = user_api_client.post_graphql(query)
- content = get_graphql_content(response)
- data = content["data"]["shop"]
- assert len(data["languages"]) == len(settings.LANGUAGES)
-
-
-def test_query_permissions(staff_api_client):
- query = """
- query {
- shop {
- permissions {
- code
- name
- }
- }
- }
- """
- permissions_codenames = set(get_permissions_codename())
- response = staff_api_client.post_graphql(query)
- content = get_graphql_content(response)
- data = content["data"]["shop"]
- permissions = data["permissions"]
- permissions_codes = {permission.get("code") for permission in permissions}
- assert len(permissions_codes) == len(permissions_codenames)
- for code in permissions_codes:
- assert code in [str_to_enum(code) for code in permissions_codenames]
-
-
-def test_query_charge_taxes_on_shipping(api_client, site_settings):
- query = """
- query {
- shop {
- chargeTaxesOnShipping
- }
- }"""
- response = api_client.post_graphql(query)
- content = get_graphql_content(response)
- data = content["data"]["shop"]
- charge_taxes_on_shipping = site_settings.charge_taxes_on_shipping
- assert data["chargeTaxesOnShipping"] == charge_taxes_on_shipping
-
-
-def test_query_digital_content_settings(
- staff_api_client, site_settings, permission_manage_settings
-):
- query = """
- query {
- shop {
- automaticFulfillmentDigitalProducts
- defaultDigitalMaxDownloads
- defaultDigitalUrlValidDays
- }
- }"""
-
- max_download = 2
- url_valid_days = 3
- site_settings.automatic_fulfillment_digital_products = True
- site_settings.default_digital_max_downloads = max_download
- site_settings.default_digital_url_valid_days = url_valid_days
- site_settings.save()
-
- response = staff_api_client.post_graphql(
- query, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
- data = content["data"]["shop"]
- automatic_fulfillment = site_settings.automatic_fulfillment_digital_products
- assert data["automaticFulfillmentDigitalProducts"] == automatic_fulfillment
- assert data["defaultDigitalMaxDownloads"] == max_download
- assert data["defaultDigitalUrlValidDays"] == url_valid_days
-
-
-QUERY_RETRIEVE_DEFAULT_MAIL_SENDER_SETTINGS = """
- {
- shop {
- defaultMailSenderName
- defaultMailSenderAddress
- }
- }
-"""
-
-
-def test_query_default_mail_sender_settings(
- staff_api_client, site_settings, permission_manage_settings
-):
- site_settings.default_mail_sender_name = "Mirumee Labs Info"
- site_settings.default_mail_sender_address = "[email protected]"
- site_settings.save(
- update_fields=["default_mail_sender_name", "default_mail_sender_address"]
- )
-
- query = QUERY_RETRIEVE_DEFAULT_MAIL_SENDER_SETTINGS
-
- response = staff_api_client.post_graphql(
- query, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
-
- data = content["data"]["shop"]
- assert data["defaultMailSenderName"] == "Mirumee Labs Info"
- assert data["defaultMailSenderAddress"] == "[email protected]"
-
-
-def test_query_default_mail_sender_settings_not_set(
- staff_api_client, site_settings, permission_manage_settings, settings
-):
- site_settings.default_mail_sender_name = ""
- site_settings.default_mail_sender_address = None
- site_settings.save(
- update_fields=["default_mail_sender_name", "default_mail_sender_address"]
- )
-
- settings.DEFAULT_FROM_EMAIL = "[email protected]"
-
- query = QUERY_RETRIEVE_DEFAULT_MAIL_SENDER_SETTINGS
-
- response = staff_api_client.post_graphql(
- query, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
-
- data = content["data"]["shop"]
- assert data["defaultMailSenderName"] == ""
- assert data["defaultMailSenderAddress"] is None
-
-
-def test_shop_digital_content_settings_mutation(
- staff_api_client, site_settings, permission_manage_settings
-):
- # given
- query = """
- mutation updateSettings($input: ShopSettingsInput!) {
- shopSettingsUpdate(input: $input) {
- shop {
- automaticFulfillmentDigitalProducts
- defaultDigitalMaxDownloads
- defaultDigitalUrlValidDays
- }
- errors {
- field,
- message
- }
- }
- }
- """
-
- max_downloads = 15
- url_valid_days = 30
- variables = {
- "input": {
- "automaticFulfillmentDigitalProducts": True,
- "defaultDigitalMaxDownloads": max_downloads,
- "defaultDigitalUrlValidDays": url_valid_days,
- }
- }
-
- assert not site_settings.automatic_fulfillment_digital_products
-
- # when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
-
- # then
- data = content["data"]["shopSettingsUpdate"]["shop"]
- assert data["automaticFulfillmentDigitalProducts"]
- assert data["defaultDigitalMaxDownloads"]
- assert data["defaultDigitalUrlValidDays"]
- site_settings.refresh_from_db()
- assert site_settings.automatic_fulfillment_digital_products
- assert site_settings.default_digital_max_downloads == max_downloads
- assert site_settings.default_digital_url_valid_days == url_valid_days
-
-
-def test_shop_settings_mutation(
- staff_api_client, site_settings, permission_manage_settings
-):
- # given
- query = """
- mutation updateSettings($input: ShopSettingsInput!) {
- shopSettingsUpdate(input: $input) {
- shop {
- headerText,
- includeTaxesInPrices,
- chargeTaxesOnShipping,
- fulfillmentAutoApprove,
- fulfillmentAllowUnpaid
- enableAccountConfirmationByEmail
-
- }
- errors {
- field,
- message
- }
- }
- }
- """
- assert site_settings.enable_account_confirmation_by_email
- charge_taxes_on_shipping = site_settings.charge_taxes_on_shipping
- new_charge_taxes_on_shipping = not charge_taxes_on_shipping
- variables = {
- "input": {
- "includeTaxesInPrices": False,
- "headerText": "Lorem ipsum",
- "chargeTaxesOnShipping": new_charge_taxes_on_shipping,
- "fulfillmentAllowUnpaid": False,
- "enableAccountConfirmationByEmail": False,
- }
- }
-
- # when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
- data = content["data"]["shopSettingsUpdate"]["shop"]
-
- # then
- assert data["headerText"] == "Lorem ipsum"
- assert data["includeTaxesInPrices"] is False
- assert data["chargeTaxesOnShipping"] == new_charge_taxes_on_shipping
- assert data["fulfillmentAutoApprove"] is True
- assert data["fulfillmentAllowUnpaid"] is False
- assert data["enableAccountConfirmationByEmail"] is False
-
- site_settings.refresh_from_db()
- assert not site_settings.include_taxes_in_prices
- assert site_settings.charge_taxes_on_shipping == new_charge_taxes_on_shipping
- assert site_settings.enable_account_confirmation_by_email is False
-
-
-def test_shop_reservation_settings_mutation(
- staff_api_client, site_settings, permission_manage_settings
-):
- query = """
- mutation updateSettings($input: ShopSettingsInput!) {
- shopSettingsUpdate(input: $input) {
- shop {
- reserveStockDurationAnonymousUser
- reserveStockDurationAuthenticatedUser
- }
- errors {
- field,
- message
- }
- }
- }
- """
- variables = {
- "input": {
- "reserveStockDurationAnonymousUser": 42,
- "reserveStockDurationAuthenticatedUser": 24,
- }
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
- data = content["data"]["shopSettingsUpdate"]["shop"]
- assert data["reserveStockDurationAnonymousUser"] == 42
- assert data["reserveStockDurationAuthenticatedUser"] == 24
- site_settings.refresh_from_db()
- assert site_settings.reserve_stock_duration_anonymous_user == 42
- assert site_settings.reserve_stock_duration_authenticated_user == 24
-
-
-def test_shop_reservation_disable_settings_mutation(
- staff_api_client, site_settings, permission_manage_settings
-):
- query = """
- mutation updateSettings($input: ShopSettingsInput!) {
- shopSettingsUpdate(input: $input) {
- shop {
- reserveStockDurationAnonymousUser
- reserveStockDurationAuthenticatedUser
- }
- errors {
- field,
- message
- }
- }
- }
- """
- variables = {
- "input": {
- "reserveStockDurationAnonymousUser": None,
- "reserveStockDurationAuthenticatedUser": None,
- }
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
- data = content["data"]["shopSettingsUpdate"]["shop"]
- assert data["reserveStockDurationAnonymousUser"] is None
- assert data["reserveStockDurationAuthenticatedUser"] is None
- site_settings.refresh_from_db()
- assert site_settings.reserve_stock_duration_anonymous_user is None
- assert site_settings.reserve_stock_duration_authenticated_user is None
-
-
-def test_shop_reservation_set_negative_settings_mutation(
- staff_api_client, site_settings, permission_manage_settings
-):
- query = """
- mutation updateSettings($input: ShopSettingsInput!) {
- shopSettingsUpdate(input: $input) {
- shop {
- reserveStockDurationAnonymousUser
- reserveStockDurationAuthenticatedUser
- }
- errors {
- field,
- message
- }
- }
- }
- """
- variables = {
- "input": {
- "reserveStockDurationAnonymousUser": -14,
- "reserveStockDurationAuthenticatedUser": -6,
- }
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
- data = content["data"]["shopSettingsUpdate"]["shop"]
- assert data["reserveStockDurationAnonymousUser"] is None
- assert data["reserveStockDurationAuthenticatedUser"] is None
- site_settings.refresh_from_db()
- assert site_settings.reserve_stock_duration_anonymous_user is None
- assert site_settings.reserve_stock_duration_authenticated_user is None
-
-
[email protected]("quantity_value", [25, 1, None])
-def test_limit_quantity_per_checkout_mutation(
- staff_api_client, site_settings, permission_manage_settings, quantity_value
-):
- query = """
- mutation updateSettings($input: ShopSettingsInput!) {
- shopSettingsUpdate(input: $input) {
- shop {
- limitQuantityPerCheckout
- }
- errors {
- field,
- message
- }
- }
- }
- """
- variables = {"input": {"limitQuantityPerCheckout": quantity_value}}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
- data = content["data"]["shopSettingsUpdate"]["shop"]
- site_settings.refresh_from_db()
-
- assert data["limitQuantityPerCheckout"] == quantity_value
- assert site_settings.limit_quantity_per_checkout == quantity_value
-
-
[email protected]("quantity_value", [0, -25])
-def test_limit_quantity_per_checkout_neg_or_zero_value(
- staff_api_client, site_settings, permission_manage_settings, quantity_value
-):
- query = """
- mutation updateSettings($input: ShopSettingsInput!) {
- shopSettingsUpdate(input: $input) {
- shop {
- limitQuantityPerCheckout
- }
- errors {
- field,
- message
- }
- }
- }
- """
- variables = {"input": {"limitQuantityPerCheckout": quantity_value}}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
- errors = content["data"]["shopSettingsUpdate"]["errors"]
- site_settings.refresh_from_db()
-
- assert len(errors) == 1
- assert errors.pop() == {
- "field": "limitQuantityPerCheckout",
- "message": "Quantity limit cannot be lower than 1.",
- }
-
- assert site_settings.limit_quantity_per_checkout == 50 # default
-
-
-MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS = """
- mutation updateDefaultSenderSettings($input: ShopSettingsInput!) {
- shopSettingsUpdate(input: $input) {
- shop {
- defaultMailSenderName
- defaultMailSenderAddress
- }
- errors {
- field
- message
- }
- }
- }
-"""
-
-
-def test_update_default_sender_settings(staff_api_client, permission_manage_settings):
- query = MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS
-
- variables = {
- "input": {
- "defaultMailSenderName": "Dummy Name",
- "defaultMailSenderAddress": "[email protected]",
- }
- }
-
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
-
- data = content["data"]["shopSettingsUpdate"]["shop"]
- assert data["defaultMailSenderName"] == "Dummy Name"
- assert data["defaultMailSenderAddress"] == "[email protected]"
-
-
- "sender_name",
- (
- "\nDummy Name",
- "\rDummy Name",
- "Dummy Name\r",
- "Dummy Name\n",
- "Dummy\rName",
- "Dummy\nName",
- ),
-)
-def test_update_default_sender_settings_invalid_name(
- staff_api_client, permission_manage_settings, sender_name
-):
- query = MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS
-
- variables = {"input": {"defaultMailSenderName": sender_name}}
-
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
-
- errors = content["data"]["shopSettingsUpdate"]["errors"]
- assert errors == [
- {"field": "defaultMailSenderName", "message": "New lines are not allowed."}
- ]
-
-
- "sender_email",
- (
- "dummy@example\r.com",
- "dummy@example\n.com",
- ),
-)
-def test_update_default_sender_settings_invalid_email(
- staff_api_client, permission_manage_settings, sender_email
-):
- query = MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS
-
- variables = {"input": {"defaultMailSenderAddress": sender_email}}
-
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
-
- errors = content["data"]["shopSettingsUpdate"]["errors"]
- assert errors == [
- {"field": "defaultMailSenderAddress", "message": "Enter a valid email address."}
- ]
-
-
-def test_shop_domain_update(staff_api_client, permission_manage_settings):
- query = """
- mutation updateSettings($input: SiteDomainInput!) {
- shopDomainUpdate(input: $input) {
- shop {
- name
- domain {
- host,
- }
- }
- }
- }
- """
- new_name = "saleor test store"
- variables = {"input": {"domain": "lorem-ipsum.com", "name": new_name}}
- site = Site.objects.get_current()
- assert site.domain != "lorem-ipsum.com"
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
- data = content["data"]["shopDomainUpdate"]["shop"]
- assert data["domain"]["host"] == "lorem-ipsum.com"
- assert data["name"] == new_name
- site.refresh_from_db()
- assert site.domain == "lorem-ipsum.com"
- assert site.name == new_name
-
-
-MUTATION_CUSTOMER_SET_PASSWORD_URL_UPDATE = """
- mutation updateSettings($customerSetPasswordUrl: String!) {
- shopSettingsUpdate(input: {customerSetPasswordUrl: $customerSetPasswordUrl}){
- shop {
- customerSetPasswordUrl
- }
- errors {
- message
- field
- code
- }
- }
- }
-"""
-
-
-def test_shop_customer_set_password_url_update(
- staff_api_client, site_settings, permission_manage_settings
-):
- customer_set_password_url = "http://www.example.com/set_pass/"
- variables = {"customerSetPasswordUrl": customer_set_password_url}
- assert site_settings.customer_set_password_url != customer_set_password_url
- response = staff_api_client.post_graphql(
- MUTATION_CUSTOMER_SET_PASSWORD_URL_UPDATE,
- variables,
- permissions=[permission_manage_settings],
- )
- content = get_graphql_content(response)
- data = content["data"]["shopSettingsUpdate"]
- assert not data["errors"]
- Site.objects.clear_cache()
- site_settings = Site.objects.get_current().settings
- assert site_settings.customer_set_password_url == customer_set_password_url
-
-
- "customer_set_password_url",
- [
- ("http://not-allowed-storefron.com/pass"),
- ("http://[value-error-in-urlparse@test/pass"),
- ("without-protocole.com/pass"),
- ],
-)
-def test_shop_customer_set_password_url_update_invalid_url(
- staff_api_client,
- site_settings,
- permission_manage_settings,
- customer_set_password_url,
-):
- variables = {"customerSetPasswordUrl": customer_set_password_url}
- assert not site_settings.customer_set_password_url
- response = staff_api_client.post_graphql(
- MUTATION_CUSTOMER_SET_PASSWORD_URL_UPDATE,
- variables,
- permissions=[permission_manage_settings],
- )
- content = get_graphql_content(response)
- data = content["data"]["shopSettingsUpdate"]
- assert data["errors"][0] == {
- "field": "customerSetPasswordUrl",
- "code": ShopErrorCode.INVALID.name,
- "message": ANY,
- }
- site_settings.refresh_from_db()
- assert not site_settings.customer_set_password_url
-
-
-def test_query_default_country(user_api_client, settings):
- settings.DEFAULT_COUNTRY = "US"
- query = """
- query {
- shop {
- defaultCountry {
- code
- country
- }
- }
- }
- """
- response = user_api_client.post_graphql(query)
- content = get_graphql_content(response)
- data = content["data"]["shop"]["defaultCountry"]
- assert data["code"] == settings.DEFAULT_COUNTRY
- assert data["country"] == "United States of America"
-
-
-AVAILABLE_EXTERNAL_AUTHENTICATIONS_QUERY = """
- query{
- shop {
- availableExternalAuthentications{
- id
- name
- }
- }
- }
-"""
-
-
- "external_auths",
- [
- [{"id": "auth1", "name": "Auth-1"}],
- [{"id": "auth1", "name": "Auth-1"}, {"id": "auth2", "name": "Auth-2"}],
- [],
- ],
-)
-def test_query_available_external_authentications(
- external_auths, user_api_client, monkeypatch
-):
- monkeypatch.setattr(
- "saleor.plugins.manager.PluginsManager.list_external_authentications",
- lambda self, active_only: external_auths,
- )
- query = AVAILABLE_EXTERNAL_AUTHENTICATIONS_QUERY
- response = user_api_client.post_graphql(query)
- content = get_graphql_content(response)
- data = content["data"]["shop"]["availableExternalAuthentications"]
- assert data == external_auths
-
-
-AVAILABLE_PAYMENT_GATEWAYS_QUERY = """
- query Shop($currency: String){
- shop {
- availablePaymentGateways(currency: $currency) {
- id
- name
- }
- }
- }
-"""
-
-
-def test_query_available_payment_gateways(user_api_client, sample_gateway, channel_USD):
- query = AVAILABLE_PAYMENT_GATEWAYS_QUERY
- response = user_api_client.post_graphql(query)
- content = get_graphql_content(response)
- data = content["data"]["shop"]["availablePaymentGateways"]
- assert {gateway["id"] for gateway in data} == {
- "mirumee.payments.dummy",
- "sampleDummy.active",
- }
- assert {gateway["name"] for gateway in data} == {
- "Dummy",
- "SampleDummy",
- }
-
-
-def test_query_available_payment_gateways_specified_currency_USD(
- user_api_client, sample_gateway, channel_USD
-):
- query = AVAILABLE_PAYMENT_GATEWAYS_QUERY
- response = user_api_client.post_graphql(query, {"currency": "USD"})
- content = get_graphql_content(response)
- data = content["data"]["shop"]["availablePaymentGateways"]
- assert {gateway["id"] for gateway in data} == {
- "mirumee.payments.dummy",
- "sampleDummy.active",
- }
- assert {gateway["name"] for gateway in data} == {
- "Dummy",
- "SampleDummy",
- }
-
-
-def test_query_available_payment_gateways_specified_currency_EUR(
- user_api_client, sample_gateway, channel_USD
-):
- query = AVAILABLE_PAYMENT_GATEWAYS_QUERY
- response = user_api_client.post_graphql(query, {"currency": "EUR"})
- content = get_graphql_content(response)
- data = content["data"]["shop"]["availablePaymentGateways"]
- assert data[0]["id"] == "sampleDummy.active"
- assert data[0]["name"] == "SampleDummy"
-
-
-AVAILABLE_SHIPPING_METHODS_QUERY = """
- query Shop($channel: String!, $address: AddressInput){
- shop {
- availableShippingMethods(channel: $channel, address: $address) {
- id
- name
- }
- }
- }
-"""
-
-
-def test_query_available_shipping_methods_no_address(
- staff_api_client, shipping_method, shipping_method_channel_PLN, channel_USD
-):
- # given
- query = AVAILABLE_SHIPPING_METHODS_QUERY
-
- # when
- response = staff_api_client.post_graphql(query, {"channel": channel_USD.slug})
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["shop"]["availableShippingMethods"]
- assert len(data) > 0
- assert {ship_meth["id"] for ship_meth in data} == {
- graphene.Node.to_global_id("ShippingMethod", ship_meth.pk)
- for ship_meth in ShippingMethod.objects.filter(
- shipping_zone__channels__slug=channel_USD.slug,
- channel_listings__channel__slug=channel_USD.slug,
- )
- }
-
-
-def test_query_available_shipping_methods_no_channel_shipping_zones(
- staff_api_client, shipping_method, shipping_method_channel_PLN, channel_USD
-):
- # given
- query = AVAILABLE_SHIPPING_METHODS_QUERY
- channel_USD.shipping_zones.clear()
-
- # when
- response = staff_api_client.post_graphql(query, {"channel": channel_USD.slug})
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["shop"]["availableShippingMethods"]
- assert len(data) == 0
-
-
-def test_query_available_shipping_methods_for_given_address(
- staff_api_client,
- channel_USD,
- shipping_method,
- shipping_zone_without_countries,
- address,
-):
- # given
- query = AVAILABLE_SHIPPING_METHODS_QUERY
- shipping_method_count = ShippingMethod.objects.count()
- variables = {
- "channel": channel_USD.slug,
- "address": {"country": CountryCodeEnum.US.name},
- }
-
- # when
- response = staff_api_client.post_graphql(query, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["shop"]["availableShippingMethods"]
- assert len(data) == shipping_method_count - 1
- assert graphene.Node.to_global_id(
- "ShippingMethodType",
- shipping_zone_without_countries.shipping_methods.first().pk,
- ) not in {ship_meth["id"] for ship_meth in data}
-
-
-def test_query_available_shipping_methods_for_excluded_postal_code(
- staff_api_client, channel_USD, shipping_method
-):
- # given
- query = AVAILABLE_SHIPPING_METHODS_QUERY
- variables = {
- "channel": channel_USD.slug,
- "address": {"country": CountryCodeEnum.PL.name, "postalCode": "53-601"},
- }
- shipping_method.postal_code_rules.create(
- start="53-600", end="54-600", inclusion_type=PostalCodeRuleInclusionType.EXCLUDE
- )
-
- # when
- response = staff_api_client.post_graphql(query, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["shop"]["availableShippingMethods"]
- assert graphene.Node.to_global_id("ShippingMethodType", shipping_method.pk) not in {
- ship_meth["id"] for ship_meth in data
- }
-
-
-def test_query_available_shipping_methods_for_included_postal_code(
- staff_api_client, channel_USD, shipping_method
-):
- # given
- query = AVAILABLE_SHIPPING_METHODS_QUERY
- variables = {
- "channel": channel_USD.slug,
- "address": {"country": CountryCodeEnum.PL.name, "postalCode": "53-601"},
- }
- shipping_method.postal_code_rules.create(
- start="53-600", end="54-600", inclusion_type=PostalCodeRuleInclusionType.INCLUDE
- )
-
- # when
- response = staff_api_client.post_graphql(query, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["shop"]["availableShippingMethods"]
- assert graphene.Node.to_global_id("ShippingMethod", shipping_method.pk) in {
- ship_meth["id"] for ship_meth in data
- }
-
-
-MUTATION_SHOP_ADDRESS_UPDATE = """
- mutation updateShopAddress($input: AddressInput){
- shopAddressUpdate(input: $input){
- errors{
- field
- message
- }
- }
- }
-"""
-
-
-def test_mutation_update_company_address(
- staff_api_client,
- permission_manage_settings,
- address,
- site_settings,
-):
- variables = {
- "input": {
- "streetAddress1": address.street_address_1,
- "city": address.city,
- "country": address.country.code,
- "postalCode": address.postal_code,
- }
- }
-
- response = staff_api_client.post_graphql(
- MUTATION_SHOP_ADDRESS_UPDATE,
- variables,
- permissions=[permission_manage_settings],
- )
- content = get_graphql_content(response)
- assert "errors" not in content["data"]
-
- site_settings.refresh_from_db()
- assert site_settings.company_address
- assert site_settings.company_address.street_address_1 == address.street_address_1
- assert site_settings.company_address.city == address.city
- assert site_settings.company_address.country.code == address.country.code
-
-
-def test_mutation_update_company_address_remove_address(
- staff_api_client, permission_manage_settings, site_settings, address
-):
- site_settings.company_address = address
- site_settings.save(update_fields=["company_address"])
- variables = {"input": None}
-
- response = staff_api_client.post_graphql(
- MUTATION_SHOP_ADDRESS_UPDATE,
- variables,
- permissions=[permission_manage_settings],
- )
- content = get_graphql_content(response)
- assert "errors" not in content["data"]
-
- site_settings.refresh_from_db()
- assert not site_settings.company_address
- assert not Address.objects.filter(pk=address.pk).exists()
-
-
-def test_mutation_update_company_address_remove_address_without_address(
- staff_api_client, permission_manage_settings, site_settings
-):
- variables = {"input": None}
-
- response = staff_api_client.post_graphql(
- MUTATION_SHOP_ADDRESS_UPDATE,
- variables,
- permissions=[permission_manage_settings],
- )
- content = get_graphql_content(response)
- assert "errors" not in content["data"]
-
- site_settings.refresh_from_db()
- assert not site_settings.company_address
-
-
-def test_staff_notification_query(
- staff_api_client,
- staff_user,
- permission_manage_settings,
- staff_notification_recipient,
-):
- query = """
- {
- shop {
- staffNotificationRecipients {
- active
- email
- user {
- firstName
- lastName
- email
- }
- }
- }
- }
- """
-
- response = staff_api_client.post_graphql(
- query, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
-
- assert content["data"]["shop"]["staffNotificationRecipients"] == [
- {
- "active": True,
- "email": staff_user.email,
- "user": {
- "firstName": staff_user.first_name,
- "lastName": staff_user.last_name,
- "email": staff_user.email,
- },
- }
- ]
-
-
-MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE = """
- mutation StaffNotificationRecipient ($input: StaffNotificationRecipientInput!) {
- staffNotificationRecipientCreate(input: $input) {
- staffNotificationRecipient {
- active
- email
- user {
- id
- firstName
- lastName
- email
- }
- }
- errors {
- field
- message
- code
- }
- }
- }
-"""
-
-
-def test_staff_notification_create_mutation(
- staff_api_client, staff_user, permission_manage_settings
-):
- user_id = graphene.Node.to_global_id("User", staff_user.id)
- variables = {"input": {"user": user_id}}
- response = staff_api_client.post_graphql(
- MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
- variables,
- permissions=[permission_manage_settings],
- )
- content = get_graphql_content(response)
-
- assert content["data"]["staffNotificationRecipientCreate"] == {
- "staffNotificationRecipient": {
- "active": True,
- "email": staff_user.email,
- "user": {
- "id": user_id,
- "firstName": staff_user.first_name,
- "lastName": staff_user.last_name,
- "email": staff_user.email,
- },
- },
- "errors": [],
- }
-
-
-def test_staff_notification_create_mutation_with_staffs_email(
- staff_api_client, staff_user, permission_manage_settings
-):
- user_id = graphene.Node.to_global_id("User", staff_user.id)
- variables = {"input": {"email": staff_user.email}}
- response = staff_api_client.post_graphql(
- MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
- variables,
- permissions=[permission_manage_settings],
- )
- content = get_graphql_content(response)
-
- assert content["data"]["staffNotificationRecipientCreate"] == {
- "staffNotificationRecipient": {
- "active": True,
- "email": staff_user.email,
- "user": {
- "id": user_id,
- "firstName": staff_user.first_name,
- "lastName": staff_user.last_name,
- "email": staff_user.email,
- },
- },
- "errors": [],
- }
-
-
-def test_staff_notification_create_mutation_with_customer_user(
- staff_api_client, customer_user, permission_manage_settings
-):
- user_id = graphene.Node.to_global_id("User", customer_user.id)
- variables = {"input": {"user": user_id}}
- response = staff_api_client.post_graphql(
- MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
- variables,
- permissions=[permission_manage_settings],
- )
- content = get_graphql_content(response)
-
- assert content["data"]["staffNotificationRecipientCreate"] == {
- "staffNotificationRecipient": None,
- "errors": [
- {"code": "INVALID", "field": "user", "message": "User has to be staff user"}
- ],
- }
-
-
-def test_staff_notification_create_mutation_with_email(
- staff_api_client, permission_manage_settings, permission_manage_staff
-):
- staff_email = "[email protected]"
- variables = {"input": {"email": staff_email}}
- response = staff_api_client.post_graphql(
- MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
- variables,
- permissions=[permission_manage_settings, permission_manage_staff],
- )
- content = get_graphql_content(response)
-
- assert content["data"]["staffNotificationRecipientCreate"] == {
- "staffNotificationRecipient": {
- "active": True,
- "email": staff_email,
- "user": None,
- },
- "errors": [],
- }
-
-
-def test_staff_notification_create_mutation_with_empty_email(
- staff_api_client, permission_manage_settings
-):
- staff_email = ""
- variables = {"input": {"email": staff_email}}
- response = staff_api_client.post_graphql(
- MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE,
- variables,
- permissions=[permission_manage_settings],
- )
- content = get_graphql_content(response)
-
- assert content["data"]["staffNotificationRecipientCreate"] == {
- "staffNotificationRecipient": None,
- "errors": [
- {
- "code": "INVALID",
- "field": "staffNotification",
- "message": "User and email cannot be set empty",
- }
- ],
- }
-
-
-MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE = """
- mutation StaffNotificationRecipient (
- $id: ID!,
- $input: StaffNotificationRecipientInput!
- ) {
- staffNotificationRecipientUpdate(id: $id, input: $input) {
- staffNotificationRecipient {
- active
- email
- user {
- firstName
- lastName
- email
- }
- }
- errors {
- field
- message
- code
- }
- }
- }
-"""
-
-
-def test_staff_notification_update_mutation(
- staff_api_client,
- staff_user,
- permission_manage_settings,
- staff_notification_recipient,
-):
- old_email = staff_notification_recipient.get_email()
- assert staff_notification_recipient.active
- staff_notification_recipient_id = graphene.Node.to_global_id(
- "StaffNotificationRecipient", staff_notification_recipient.id
- )
- variables = {"id": staff_notification_recipient_id, "input": {"active": False}}
- staff_api_client.post_graphql(
- MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE,
- variables,
- permissions=[permission_manage_settings],
- )
- staff_notification_recipient.refresh_from_db()
- assert not staff_notification_recipient.active
- assert staff_notification_recipient.get_email() == old_email
-
-
-def test_staff_notification_update_mutation_with_empty_user(
- staff_api_client,
- staff_user,
- permission_manage_settings,
- staff_notification_recipient,
-):
- staff_notification_recipient_id = graphene.Node.to_global_id(
- "StaffNotificationRecipient", staff_notification_recipient.id
- )
- variables = {"id": staff_notification_recipient_id, "input": {"user": ""}}
- response = staff_api_client.post_graphql(
- MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE,
- variables,
- permissions=[permission_manage_settings],
- )
- content = get_graphql_content(response)
-
- staff_notification_recipient.refresh_from_db()
- assert content["data"]["staffNotificationRecipientUpdate"] == {
- "staffNotificationRecipient": None,
- "errors": [
- {
- "code": "INVALID",
- "field": "staffNotification",
- "message": "User and email cannot be set empty",
- }
- ],
- }
-
-
-def test_staff_notification_update_mutation_with_empty_email(
- staff_api_client,
- staff_user,
- permission_manage_settings,
- staff_notification_recipient,
-):
- staff_notification_recipient_id = graphene.Node.to_global_id(
- "StaffNotificationRecipient", staff_notification_recipient.id
- )
- variables = {"id": staff_notification_recipient_id, "input": {"email": ""}}
- response = staff_api_client.post_graphql(
- MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE,
- variables,
- permissions=[permission_manage_settings],
- )
- content = get_graphql_content(response)
-
- staff_notification_recipient.refresh_from_db()
- assert content["data"]["staffNotificationRecipientUpdate"] == {
- "staffNotificationRecipient": None,
- "errors": [
- {
- "code": "INVALID",
- "field": "staffNotification",
- "message": "User and email cannot be set empty",
- }
- ],
- }
-
-
-ORDER_SETTINGS_UPDATE_MUTATION = """
- mutation orderSettings($confirmOrders: Boolean, $fulfillGiftCards: Boolean) {
- orderSettingsUpdate(
- input: {
- automaticallyConfirmAllNewOrders: $confirmOrders
- automaticallyFulfillNonShippableGiftCard: $fulfillGiftCards
- }
- ) {
- orderSettings {
- automaticallyConfirmAllNewOrders
- automaticallyFulfillNonShippableGiftCard
- markAsPaidStrategy
- defaultTransactionFlowStrategy
- }
- }
- }
-"""
-
-
-def test_order_settings_update_by_staff(
- staff_api_client, permission_group_manage_orders, channel_USD, channel_PLN
-):
- # given
- permission_group_manage_orders.user_set.add(staff_api_client.user)
-
- # when
- response = staff_api_client.post_graphql(
- ORDER_SETTINGS_UPDATE_MUTATION,
- {"confirmOrders": False, "fulfillGiftCards": False},
- )
- content = get_graphql_content(response)
-
- # then
- response_settings = content["data"]["orderSettingsUpdate"]["orderSettings"]
- assert response_settings["automaticallyConfirmAllNewOrders"] is False
- assert response_settings["automaticallyFulfillNonShippableGiftCard"] is False
- assert (
- response_settings["defaultTransactionFlowStrategy"]
- == TransactionFlowStrategyEnum.CHARGE.name
- == channel_USD.default_transaction_flow_strategy.upper()
- )
- channel_PLN.refresh_from_db()
- channel_USD.refresh_from_db()
- assert channel_PLN.automatically_confirm_all_new_orders is False
- assert channel_PLN.automatically_fulfill_non_shippable_gift_card is False
- assert channel_USD.automatically_confirm_all_new_orders is False
- 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_group_manage_orders, channel_USD, channel_PLN
-):
- # given
- permission_group_manage_orders.user_set.add(staff_api_client.user)
- QUERY = """
- mutation {
- orderSettingsUpdate(
- input: {}
- ) {
- orderSettings {
- automaticallyConfirmAllNewOrders
- automaticallyFulfillNonShippableGiftCard
- }
- }
- }
- """
-
- # when
- response = staff_api_client.post_graphql(
- QUERY,
- {},
- )
- content = get_graphql_content(response)
-
- # then
- response_settings = content["data"]["orderSettingsUpdate"]["orderSettings"]
- assert response_settings["automaticallyConfirmAllNewOrders"] is True
- assert response_settings["automaticallyFulfillNonShippableGiftCard"] is True
- channel_PLN.refresh_from_db()
- channel_USD.refresh_from_db()
- assert channel_PLN.automatically_confirm_all_new_orders is True
- assert channel_PLN.automatically_fulfill_non_shippable_gift_card is True
- assert channel_USD.automatically_confirm_all_new_orders is True
- assert channel_USD.automatically_fulfill_non_shippable_gift_card is True
-
-
-def test_order_settings_update_by_app(
- app_api_client, permission_manage_orders, channel_USD, channel_PLN
-):
- # given
- app_api_client.app.permissions.set([permission_manage_orders])
-
- # when
- response = app_api_client.post_graphql(
- ORDER_SETTINGS_UPDATE_MUTATION,
- {"confirmOrders": False, "fulfillGiftCards": False},
- )
- content = get_graphql_content(response)
-
- # then
- response_settings = content["data"]["orderSettingsUpdate"]["orderSettings"]
- assert response_settings["automaticallyConfirmAllNewOrders"] is False
- assert response_settings["automaticallyFulfillNonShippableGiftCard"] is False
- assert (
- response_settings["defaultTransactionFlowStrategy"]
- == TransactionFlowStrategyEnum.CHARGE.name
- == channel_USD.default_transaction_flow_strategy.upper()
- )
- channel_PLN.refresh_from_db()
- channel_USD.refresh_from_db()
- assert channel_PLN.automatically_confirm_all_new_orders is False
- assert channel_PLN.automatically_fulfill_non_shippable_gift_card is False
- assert channel_USD.automatically_confirm_all_new_orders is False
- assert channel_USD.automatically_fulfill_non_shippable_gift_card is False
-
-
-def test_order_settings_update_by_user_without_permissions(
- user_api_client, channel_USD, channel_PLN
-):
- # given
-
- # when
- response = user_api_client.post_graphql(
- ORDER_SETTINGS_UPDATE_MUTATION,
- {"confirmOrders": False, "fulfillGiftCards": False},
- )
-
- # then
- assert_no_permission(response)
- channel_PLN.refresh_from_db()
- channel_USD.refresh_from_db()
- assert channel_PLN.automatically_confirm_all_new_orders is True
- assert channel_PLN.automatically_fulfill_non_shippable_gift_card is True
- assert channel_USD.automatically_confirm_all_new_orders is True
- assert channel_USD.automatically_fulfill_non_shippable_gift_card is True
-
-
-ORDER_SETTINGS_QUERY = """
- query orderSettings {
- orderSettings {
- automaticallyConfirmAllNewOrders
- automaticallyFulfillNonShippableGiftCard
- }
- }
-"""
-
-
-def test_order_settings_query_one_channel(
- staff_api_client, permission_manage_orders, channel_USD
-):
- # given
- channel_USD.automatically_confirm_all_new_orders = False
- channel_USD.automatically_fulfill_non_shippable_gift_card = True
- channel_USD.save()
-
- staff_api_client.user.user_permissions.add(permission_manage_orders)
-
- # when
- response = staff_api_client.post_graphql(ORDER_SETTINGS_QUERY)
-
- # then
- content = get_graphql_content(response)
-
- assert content["data"]["orderSettings"]["automaticallyConfirmAllNewOrders"] is False
- assert (
- content["data"]["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
- is True
- )
-
-
-def test_order_settings_query_multiple_channels(
- staff_api_client, permission_manage_orders, channel_USD, channel_PLN
-):
- # given
- channel_USD.automatically_confirm_all_new_orders = False
- channel_USD.automatically_fulfill_non_shippable_gift_card = True
- channel_USD.save()
-
- channel_PLN.automatically_confirm_all_new_orders = True
- channel_PLN.automatically_fulfill_non_shippable_gift_card = False
- channel_PLN.save()
-
- staff_api_client.user.user_permissions.add(permission_manage_orders)
-
- # when
- response = staff_api_client.post_graphql(ORDER_SETTINGS_QUERY)
-
- # then
- content = get_graphql_content(response)
-
- assert content["data"]["orderSettings"]["automaticallyConfirmAllNewOrders"] is True
- assert (
- content["data"]["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
- is False
- )
-
-
-def test_order_settings_query_as_user(user_api_client, channel_USD, channel_PLN):
- response = user_api_client.post_graphql(ORDER_SETTINGS_QUERY)
- assert_no_permission(response)
-
-
-GIFT_CARD_SETTINGS_QUERY = """
- query giftCardSettings {
- giftCardSettings {
- expiryType
- expiryPeriod {
- type
- amount
- }
- }
- }
-"""
-
-
-def test_gift_card_settings_query_as_staff(
- staff_api_client, permission_manage_gift_card, site_settings
-):
- assert site_settings.gift_card_expiry_period is None
-
- staff_api_client.user.user_permissions.add(permission_manage_gift_card)
- response = staff_api_client.post_graphql(GIFT_CARD_SETTINGS_QUERY)
- content = get_graphql_content(response)
-
- assert (
- content["data"]["giftCardSettings"]["expiryType"]
- == site_settings.gift_card_expiry_type.upper()
- )
- assert content["data"]["giftCardSettings"]["expiryPeriod"] is None
-
-
-def test_query_gift_card_settings_expiry_period(
- staff_api_client, permission_manage_gift_card, site_settings
-):
- expiry_type = GiftCardSettingsExpiryType.EXPIRY_PERIOD
- expiry_period_type = TimePeriodType.MONTH
- expiry_period = 3
- site_settings.gift_card_expiry_type = expiry_type
- site_settings.gift_card_expiry_period_type = expiry_period_type
- site_settings.gift_card_expiry_period = expiry_period
- site_settings.save(
- update_fields=[
- "gift_card_expiry_type",
- "gift_card_expiry_period_type",
- "gift_card_expiry_period",
- ]
- )
-
- staff_api_client.user.user_permissions.add(permission_manage_gift_card)
- response = staff_api_client.post_graphql(GIFT_CARD_SETTINGS_QUERY)
- content = get_graphql_content(response)
-
- assert content["data"]["giftCardSettings"]["expiryType"] == expiry_type.upper()
- assert (
- content["data"]["giftCardSettings"]["expiryPeriod"]["type"]
- == expiry_period_type.upper()
- )
- assert (
- content["data"]["giftCardSettings"]["expiryPeriod"]["amount"] == expiry_period
- )
-
-
-def test_gift_card_settings_query_as_app(
- app_api_client, permission_manage_gift_card, site_settings
-):
- assert site_settings.gift_card_expiry_period is None
-
- response = app_api_client.post_graphql(
- GIFT_CARD_SETTINGS_QUERY, permissions=[permission_manage_gift_card]
- )
- content = get_graphql_content(response)
-
- assert (
- content["data"]["giftCardSettings"]["expiryType"]
- == site_settings.gift_card_expiry_type.upper()
- )
- assert content["data"]["giftCardSettings"]["expiryPeriod"] is None
-
-
-def test_gift_card_settings_query_as_user(user_api_client, site_settings):
- response = user_api_client.post_graphql(GIFT_CARD_SETTINGS_QUERY)
- assert_no_permission(response)
-
-
-API_VERSION_QUERY = """
- query {
- shop {
- version
- }
- }
-"""
-
-
-def test_version_query_as_anonymous_user(api_client):
- response = api_client.post_graphql(API_VERSION_QUERY)
- assert_no_permission(response)
-
-
-def test_version_query_as_customer(user_api_client):
- response = user_api_client.post_graphql(API_VERSION_QUERY)
- assert_no_permission(response)
-
-
-def test_version_query_as_app(app_api_client):
- response = app_api_client.post_graphql(API_VERSION_QUERY)
- content = get_graphql_content(response)
- assert content["data"]["shop"]["version"] == __version__
-
-
-def test_version_query_as_staff_user(staff_api_client):
- response = staff_api_client.post_graphql(API_VERSION_QUERY)
- content = get_graphql_content(response)
- assert content["data"]["shop"]["version"] == __version__
-
-
-def test_schema_version_query(api_client):
- # given
- query = """
- query {
- shop {
- schemaVersion
- }
- }
- """
- m = re.match(r"^(\d+)\.(\d+)\.\d+", __version__)
- assert m is not None
- major, minor = m.groups()
-
- # when
- response = api_client.post_graphql(query)
- content = get_graphql_content(response)
-
- # then
- assert content["data"]["shop"]["schemaVersion"] == f"{major}.{minor}"
-
-
-def test_cannot_get_shop_limit_info_when_not_staff(user_api_client):
- query = LIMIT_INFO_QUERY
- response = user_api_client.post_graphql(query)
- assert_no_permission(response)
-
-
-def test_get_shop_limit_info_returns_null_by_default(staff_api_client):
- query = LIMIT_INFO_QUERY
- response = staff_api_client.post_graphql(query)
- content = get_graphql_content(response)
- assert content["data"] == {
- "shop": {
- "limits": {
- "currentUsage": {"channels": None},
- "allowedUsage": {"channels": None},
- }
- }
- }
-
-
-CHANNEL_CURRENCIES_QUERY = """
- query {
- shop {
- channelCurrencies
- }
- }
-"""
-
-
-def test_fetch_channel_currencies(
- staff_api_client, channel_PLN, channel_USD, other_channel_USD
-):
- query = CHANNEL_CURRENCIES_QUERY
- response = staff_api_client.post_graphql(query)
- content = get_graphql_content(response)
- assert set(content["data"]["shop"]["channelCurrencies"]) == {
- channel_PLN.currency_code,
- channel_USD.currency_code,
- }
-
-
-def test_fetch_channel_currencies_by_app(
- app_api_client, channel_PLN, channel_USD, other_channel_USD
-):
- query = CHANNEL_CURRENCIES_QUERY
- response = app_api_client.post_graphql(query)
- content = get_graphql_content(response)
- assert set(content["data"]["shop"]["channelCurrencies"]) == {
- channel_PLN.currency_code,
- channel_USD.currency_code,
- }
-
-
-def test_fetch_channel_currencies_by_customer(api_client, channel_PLN, channel_USD):
- query = CHANNEL_CURRENCIES_QUERY
- response = api_client.post_graphql(query)
- assert_no_permission(response)
-
-
-COUNTRY_FILTER_QUERY = """
- query($filter: CountryFilterInput!) {
- shop {
- countries(filter: $filter){
- code
- }
- }
- }
-
-"""
-
-
-def test_query_countries_filter_shiping_zones_attached_true(
- user_api_client, shipping_zones
-):
- # given
- variables = {"filter": {"attachedToShippingZones": True}}
- fixture_countries_code_set = {zone.countries[0].code for zone in shipping_zones}
-
- # when
- response = user_api_client.post_graphql(COUNTRY_FILTER_QUERY, variables=variables)
- content = get_graphql_content(response)
-
- data = content["data"]["shop"]["countries"]
- countries_codes_results = {country["code"] for country in data}
-
- # then
- assert countries_codes_results == fixture_countries_code_set
- assert len(data) == len(shipping_zones)
-
-
-def test_query_countries_filter_shiping_zones_attached_false(
- user_api_client, shipping_zones
-):
- # given
- variables = {"filter": {"attachedToShippingZones": False}}
- fixture_countries_code_set = {zone.countries[0].code for zone in shipping_zones}
-
- # when
- response = user_api_client.post_graphql(COUNTRY_FILTER_QUERY, variables=variables)
- content = get_graphql_content(response)
-
- data = content["data"]["shop"]["countries"]
- countries_codes_results = {country["code"] for country in data}
-
- # then
- assert not any(
- code in countries_codes_results for code in fixture_countries_code_set
- )
- assert len(data) == (len(countries) - len(shipping_zones))
-
-
-def test_query_countries_filter_shiping_zones_attached_none(
- user_api_client, shipping_zones
-):
- # given
- variables = {"filter": {"attachedToShippingZones": None}}
-
- # when
- response = user_api_client.post_graphql(COUNTRY_FILTER_QUERY, variables=variables)
- content = get_graphql_content(response)
-
- data = content["data"]["shop"]["countries"]
-
- # then
- assert len(data) == len(countries)
diff --git a/saleor/graphql/shop/tests/test_shop_taxes.py b/saleor/graphql/shop/tests/test_shop_taxes.py
index 0aee5dbe4e..ab49316cca 100644
--- a/saleor/graphql/shop/tests/test_shop_taxes.py
+++ b/saleor/graphql/shop/tests/test_shop_taxes.py
@@ -71,6 +71,7 @@ def vatlayer(db, tax_rates, taxes):
def test_query_countries_with_tax(user_api_client, vatlayer, tax_rates):
+ # given
query = """
query {
shop {
@@ -87,7 +88,11 @@ def test_query_countries_with_tax(user_api_client, vatlayer, tax_rates):
}
}
"""
+
+ # when
response = user_api_client.post_graphql(query)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["shop"]["countries"]
vat = VAT.objects.first()
@@ -109,6 +114,7 @@ def test_query_countries_with_tax(user_api_client, vatlayer, tax_rates):
def test_query_default_country_with_tax(user_api_client, settings, vatlayer, tax_rates):
+ # given
settings.DEFAULT_COUNTRY = "PL"
query = """
query {
@@ -122,7 +128,11 @@ def test_query_default_country_with_tax(user_api_client, settings, vatlayer, tax
}
}
"""
+
+ # when
response = user_api_client.post_graphql(query)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["shop"]["defaultCountry"]
assert data["code"] == settings.DEFAULT_COUNTRY