Skip to content

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

Move orderSetting to Channel type (#11417)

Krzysztof Waliczek2c23939761db
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b29b14da52..e1ae653c95 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,11 @@ All notable, unreleased changes to this project will be documented in this file.
### Breaking changes
### GraphQL API
+- Move `orderSettings` query to `Channel` type - #11417 by @kadewu:
+ - Mutation `Channel.channelCreate` and `Channel.channelUpdate` have new `orderSettings` input.
+ - Deprecate `Shop.orderSettings` query. Use `Channel.orderSettings` query instead.
+ - Deprecate `Shop.orderSettingsUpdate` mutation. Use `Channel.channelUpdate` instead.
+
### Other changes
@@ -49,7 +54,6 @@ Just so you know, changes mentioned in this section are in a preview state and c
### Breaking changes
### GraphQL API
-
- Add ability to filter and sort products of a category - #10917 by @yemeksepeti-cihankarluk, @ogunheper
- Add `filter` argument to `Category.products`
- Add `sortBy` argument to `Category.products`
diff --git a/saleor/channel/migrations/0008_update_null_order_settings.py b/saleor/channel/migrations/0008_update_null_order_settings.py
new file mode 100644
index 0000000000..3b2e640643
--- /dev/null
+++ b/saleor/channel/migrations/0008_update_null_order_settings.py
@@ -0,0 +1,37 @@
+from django.db import migrations
+from django.db.models import Q
+
+# In case of worker working on upplied 0007 migration and old code,
+# could have happen to create `Channel` with null site settings.
+# This migration makes sure to covers such cases.
+
+# Small note: Filtering null values is only for performance.
+# Updating all channells would have ended up with the same result.
+def set_order_settings(apps, schema_editor):
+ SiteSettings = apps.get_model("site", "SiteSettings")
+ Channel = apps.get_model("channel", "Channel")
+
+ site_settings = SiteSettings.objects.first()
+
+ Channel.objects.filter(
+ Q(automatically_confirm_all_new_orders__isnull=True)
+ | Q(automatically_fulfill_non_shippable_gift_card__isnull=True)
+ ).update(
+ automatically_confirm_all_new_orders=(
+ site_settings.automatically_confirm_all_new_orders
+ ),
+ automatically_fulfill_non_shippable_gift_card=(
+ site_settings.automatically_fulfill_non_shippable_gift_card
+ ),
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("channel", "0007_order_settings_per_channel"),
+ ]
+
+ operations = [
+ migrations.RunPython(set_order_settings, migrations.RunPython.noop),
+ ]
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index d5cad867d0..6a517a4728 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -540,7 +540,7 @@ def _create_order(
status = (
OrderStatus.UNFULFILLED
- if site_settings.automatically_confirm_all_new_orders
+ if checkout_info.channel.automatically_confirm_all_new_orders
else OrderStatus.UNCONFIRMED
)
order = Order.objects.create(
@@ -1100,7 +1100,7 @@ def _create_order_from_checkout(
# status
status = (
OrderStatus.UNFULFILLED
- if site_settings.automatically_confirm_all_new_orders
+ if checkout_info.channel.automatically_confirm_all_new_orders
else OrderStatus.UNCONFIRMED
)
checkout_metadata = get_or_create_checkout_metadata(checkout_info.checkout)
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index f0fb3fcb77..d28c163e05 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -1030,8 +1030,9 @@ def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(
is_anonymous_user,
non_shippable_gift_card_product,
):
- site_settings.automatically_fulfill_non_shippable_gift_card = False
- site_settings.save(update_fields=["automatically_fulfill_non_shippable_gift_card"])
+ channel = checkout_with_gift_card_items.channel
+ channel.automatically_fulfill_non_shippable_gift_card = False
+ channel.save()
checkout_user = None if is_anonymous_user else customer_user
checkout = checkout_with_gift_card_items
diff --git a/saleor/checkout/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.py
index 80b543ab07..3d7f409699 100644
--- a/saleor/checkout/tests/test_order_from_checkout.py
+++ b/saleor/checkout/tests/test_order_from_checkout.py
@@ -371,8 +371,9 @@ def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(
non_shippable_gift_card_product,
app,
):
- site_settings.automatically_fulfill_non_shippable_gift_card = False
- site_settings.save(update_fields=["automatically_fulfill_non_shippable_gift_card"])
+ channel = checkout_with_gift_card_items.channel
+ channel.automatically_fulfill_non_shippable_gift_card = False
+ channel.save()
checkout_user = None if is_anonymous_user else customer_user
checkout = checkout_with_gift_card_items
diff --git a/saleor/graphql/account/mutations/permission_group.py b/saleor/graphql/account/mutations/permission_group.py
index 70ce72efcb..dbc61c6b18 100644
--- a/saleor/graphql/account/mutations/permission_group.py
+++ b/saleor/graphql/account/mutations/permission_group.py
@@ -111,7 +111,7 @@ class PermissionGroupCreate(ModelMutation):
)
@classmethod
- def check_permissions(cls, context, permissions=None):
+ def check_permissions(cls, context, permissions=None, **data):
app = get_app_promise(context).get()
if app:
raise PermissionDenied(
@@ -462,7 +462,7 @@ class PermissionGroupDelete(ModelDeleteMutation):
cls.check_if_group_can_be_removed(requestor, instance)
@classmethod
- def check_permissions(cls, context, permissions=None):
+ def check_permissions(cls, context, permissions=None, **data):
app = get_app_promise(context).get()
if app:
raise PermissionDenied(
diff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.py
index 1986de4157..156069fe87 100644
--- a/saleor/graphql/account/mutations/staff.py
+++ b/saleor/graphql/account/mutations/staff.py
@@ -233,7 +233,7 @@ class StaffCreate(ModelMutation):
error_type_field = "staff_errors"
@classmethod
- def check_permissions(cls, context, permissions=None):
+ def check_permissions(cls, context, permissions=None, **data):
app = get_app_promise(context).get()
if app:
raise PermissionDenied(
diff --git a/saleor/graphql/account/utils.py b/saleor/graphql/account/utils.py
index ba22a65704..2e3acd858c 100644
--- a/saleor/graphql/account/utils.py
+++ b/saleor/graphql/account/utils.py
@@ -83,7 +83,7 @@ class StaffDeleteMixin(UserDeleteMixin):
abstract = True
@classmethod
- def check_permissions(cls, context: SaleorContext, permissions=None):
+ def check_permissions(cls, context: SaleorContext, permissions=None, **data):
if get_app_promise(context).get():
raise PermissionDenied(
message="Apps are not allowed to perform this mutation."
diff --git a/saleor/graphql/channel/mutations/channel_create.py b/saleor/graphql/channel/mutations/channel_create.py
index e57ac8e232..50bc4d71a9 100644
--- a/saleor/graphql/channel/mutations/channel_create.py
+++ b/saleor/graphql/channel/mutations/channel_create.py
@@ -7,7 +7,13 @@ from ....permission.enums import ChannelPermissions
from ....tax.models import TaxConfiguration
from ...account.enums import CountryCodeEnum
from ...core import ResolveInfo
-from ...core.descriptions import ADDED_IN_31, ADDED_IN_35, ADDED_IN_37, PREVIEW_FEATURE
+from ...core.descriptions import (
+ ADDED_IN_31,
+ ADDED_IN_35,
+ ADDED_IN_37,
+ ADDED_IN_312,
+ PREVIEW_FEATURE,
+)
from ...core.mutations import ModelMutation
from ...core.types import ChannelError, NonNullList
from ...plugins.dataloaders import get_plugin_manager_promise
@@ -25,6 +31,20 @@ class StockSettingsInput(graphene.InputObjectType):
)
+class OrderSettingsInput(graphene.InputObjectType):
+ 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 ChannelInput(graphene.InputObjectType):
is_active = graphene.Boolean(description="isActive flag.")
stock_settings = graphene.Field(
@@ -44,6 +64,11 @@ class ChannelInput(graphene.InputObjectType):
+ PREVIEW_FEATURE,
required=False,
)
+ order_settings = graphene.Field(
+ OrderSettingsInput,
+ description="The channel order settings" + ADDED_IN_312,
+ required=False,
+ )
class ChannelCreateInput(ChannelInput):
@@ -90,7 +115,21 @@ class ChannelCreate(ModelMutation):
cleaned_input["slug"] = slugify(slug)
if stock_settings := cleaned_input.get("stock_settings"):
cleaned_input["allocation_strategy"] = stock_settings["allocation_strategy"]
-
+ if order_settings := cleaned_input.get("order_settings"):
+ automatically_confirm_all_new_orders = order_settings.get(
+ "automatically_confirm_all_new_orders"
+ )
+ if automatically_confirm_all_new_orders is not None:
+ cleaned_input[
+ "automatically_confirm_all_new_orders"
+ ] = automatically_confirm_all_new_orders
+ automatically_fulfill_non_shippable_gift_card = order_settings.get(
+ "automatically_fulfill_non_shippable_gift_card"
+ )
+ if automatically_fulfill_non_shippable_gift_card is not None:
+ cleaned_input[
+ "automatically_fulfill_non_shippable_gift_card"
+ ] = automatically_fulfill_non_shippable_gift_card
return cleaned_input
@classmethod
diff --git a/saleor/graphql/channel/mutations/channel_update.py b/saleor/graphql/channel/mutations/channel_update.py
index 44bddcd9d3..7f23749e91 100644
--- a/saleor/graphql/channel/mutations/channel_update.py
+++ b/saleor/graphql/channel/mutations/channel_update.py
@@ -5,7 +5,7 @@ from django.utils.text import slugify
from ....channel import models
from ....channel.error_codes import ChannelErrorCode
from ....core.tracing import traced_atomic_transaction
-from ....permission.enums import ChannelPermissions
+from ....permission.enums import ChannelPermissions, OrderPermissions
from ....shipping.tasks import (
drop_invalid_shipping_methods_relations_for_given_channels,
)
@@ -53,10 +53,16 @@ class ChannelUpdate(ModelMutation):
)
class Meta:
- description = "Update a channel."
+ description = (
+ "Update a channel.\n\n"
+ "Requires one of the following permissions: MANAGE_CHANNELS.\n"
+ "Requires one of the following permissions "
+ "when updating only orderSettings field: "
+ "MANAGE_CHANNELS, MANAGE_ORDERS."
+ )
+ auto_permission_message = False
model = models.Channel
object_type = Channel
- permissions = (ChannelPermissions.MANAGE_CHANNELS,)
error_type_class = ChannelError
error_type_field = "channel_errors"
@@ -84,9 +90,30 @@ class ChannelUpdate(ModelMutation):
cleaned_input["slug"] = slugify(slug)
if stock_settings := cleaned_input.get("stock_settings"):
cleaned_input["allocation_strategy"] = stock_settings["allocation_strategy"]
+ if order_settings := cleaned_input.get("order_settings"):
+ cleaned_input["automatically_confirm_all_new_orders"] = order_settings[
+ "automatically_confirm_all_new_orders"
+ ]
+ cleaned_input[
+ "automatically_fulfill_non_shippable_gift_card"
+ ] = order_settings["automatically_fulfill_non_shippable_gift_card"]
return cleaned_input
+ @classmethod
+ def check_permissions(cls, context, permissions=None, **data):
+ permissions = [ChannelPermissions.MANAGE_CHANNELS]
+
+ # Permission MANAGE_ORDERS or MANAGE_CHANNELS is required to update
+ # orderSettings. MANAGE_ORDERS can be used only when
+ # channelUpdate mutation will get OrderSettingsInput and
+ # not any other fields. Otherwise needed permission is MANAGE_CHANNELS.
+ input = data["data"]["input"]
+ if "order_settings" in input and len(input) == 1:
+ permissions.append(OrderPermissions.MANAGE_ORDERS)
+
+ return super().check_permissions(context, permissions, **data)
+
@classmethod
def _save_m2m(cls, info: ResolveInfo, instance, cleaned_data):
with traced_atomic_transaction():
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_create.py b/saleor/graphql/channel/tests/mutations/test_channel_create.py
index 780e04efe3..14c86cc352 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_create.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_create.py
@@ -33,6 +33,10 @@ CHANNEL_CREATE_MUTATION = """
stockSettings {
allocationStrategy
}
+ orderSettings {
+ automaticallyConfirmAllNewOrders
+ automaticallyFulfillNonShippableGiftCard
+ }
}
errors{
field
@@ -61,6 +65,10 @@ def test_channel_create_mutation_as_staff_user(
"currencyCode": currency_code,
"defaultCountry": default_country,
"stockSettings": {"allocationStrategy": allocation_strategy},
+ "orderSettings": {
+ "automaticallyConfirmAllNewOrders": False,
+ "automaticallyFulfillNonShippableGiftCard": False,
+ },
}
}
@@ -86,6 +94,11 @@ def test_channel_create_mutation_as_staff_user(
== default_country
)
assert channel_data["stockSettings"]["allocationStrategy"] == allocation_strategy
+ assert channel_data["orderSettings"]["automaticallyConfirmAllNewOrders"] is False
+ assert (
+ channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
+ is False
+ )
def test_channel_create_mutation_as_app(
@@ -131,6 +144,11 @@ def test_channel_create_mutation_as_app(
channel_data["stockSettings"]["allocationStrategy"]
== AllocationStrategyEnum.PRIORITIZE_SORTING_ORDER.name
)
+ assert channel_data["orderSettings"]["automaticallyConfirmAllNewOrders"] is True
+ assert (
+ channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
+ is True
+ )
def test_channel_create_mutation_as_customer(user_api_client):
@@ -147,6 +165,10 @@ def test_channel_create_mutation_as_customer(user_api_client):
"currencyCode": currency_code,
"defaultCountry": default_country,
"stockSettings": {"allocationStrategy": allocation_strategy},
+ "orderSettings": {
+ "automaticallyConfirmAllNewOrders": False,
+ "automaticallyFulfillNonShippableGiftCard": False,
+ },
}
}
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.py
index cde546614a..320ad606eb 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py
@@ -32,6 +32,10 @@ CHANNEL_UPDATE_MUTATION = """
stockSettings {
allocationStrategy
}
+ orderSettings {
+ automaticallyConfirmAllNewOrders
+ automaticallyFulfillNonShippableGiftCard
+ }
}
errors{
field
@@ -61,6 +65,10 @@ def test_channel_update_mutation_as_staff_user(
"slug": slug,
"defaultCountry": default_country,
"stockSettings": {"allocationStrategy": allocation_strategy},
+ "orderSettings": {
+ "automaticallyConfirmAllNewOrders": False,
+ "automaticallyFulfillNonShippableGiftCard": False,
+ },
},
}
@@ -86,6 +94,11 @@ def test_channel_update_mutation_as_staff_user(
== default_country
)
assert channel_data["stockSettings"]["allocationStrategy"] == allocation_strategy
+ assert channel_data["orderSettings"]["automaticallyConfirmAllNewOrders"] is False
+ assert (
+ channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
+ is False
+ )
def test_channel_update_mutation_as_app(
@@ -701,3 +714,133 @@ def test_channel_update_mutation_duplicated_warehouses(
assert errors[0]["field"] == "warehouses"
assert errors[0]["code"] == ChannelErrorCode.DUPLICATED_INPUT_ITEM.name
assert errors[0]["warehouses"] == [add_warehouse]
+
+
+def test_channel_update_order_settings_manage_orders(
+ permission_manage_orders,
+ staff_api_client,
+ channel_USD,
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": channel_id,
+ "input": {
+ "orderSettings": {
+ "automaticallyConfirmAllNewOrders": False,
+ "automaticallyFulfillNonShippableGiftCard": False,
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_orders,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelUpdate"]
+ assert not data["errors"]
+ channel_data = data["channel"]
+ assert channel_data["orderSettings"]["automaticallyConfirmAllNewOrders"] is False
+ assert (
+ channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
+ is False
+ )
+
+
+def test_channel_update_order_settings_manage_orders_as_app(
+ permission_manage_orders,
+ app_api_client,
+ channel_USD,
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": channel_id,
+ "input": {
+ "orderSettings": {
+ "automaticallyConfirmAllNewOrders": False,
+ "automaticallyFulfillNonShippableGiftCard": False,
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_orders,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelUpdate"]
+ assert not data["errors"]
+ channel_data = data["channel"]
+ assert channel_data["orderSettings"]["automaticallyConfirmAllNewOrders"] is False
+ assert (
+ channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
+ is False
+ )
+
+
+def test_channel_update_order_settings_manage_orders_permission_denied(
+ permission_manage_orders,
+ staff_api_client,
+ channel_USD,
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": channel_id,
+ "input": {
+ "name": "newNAme",
+ "orderSettings": {
+ "automaticallyConfirmAllNewOrders": False,
+ "automaticallyFulfillNonShippableGiftCard": False,
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_orders,),
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_channel_update_order_settings_manage_orders_as_app_permission_denied(
+ permission_manage_orders,
+ app_api_client,
+ channel_USD,
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": channel_id,
+ "input": {
+ "name": "newNAme",
+ "orderSettings": {
+ "automaticallyConfirmAllNewOrders": False,
+ "automaticallyFulfillNonShippableGiftCard": False,
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_orders,),
+ )
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/channel/tests/queries/test_channel.py b/saleor/graphql/channel/tests/queries/test_channel.py
index fc89dc7c61..ec69ad73c6 100644
--- a/saleor/graphql/channel/tests/queries/test_channel.py
+++ b/saleor/graphql/channel/tests/queries/test_channel.py
@@ -30,7 +30,7 @@ def test_query_channel_as_staff_user(staff_api_client, channel_USD):
variables = {"id": channel_id}
# when
- response = staff_api_client.post_graphql(QUERY_CHANNEL, variables)
+ response = staff_api_client.post_graphql(QUERY_CHANNEL, variables=variables)
content = get_graphql_content(response)
# then
@@ -52,7 +52,7 @@ def test_query_channel_as_app(app_api_client, channel_USD):
variables = {"id": channel_id}
# when
- response = app_api_client.post_graphql(QUERY_CHANNEL, variables)
+ response = app_api_client.post_graphql(QUERY_CHANNEL, variables=variables)
content = get_graphql_content(response)
# then
@@ -273,3 +273,131 @@ def test_query_channel_returns_supported_shipping_methods_with_countries_input(
assert sm_per_country[0]["countryCode"] == "PL"
assert len(sm_per_country[0]["shippingMethods"]) == 1
assert sm_per_country[0]["shippingMethods"][0]["id"] == expected_shipping_method_id
+
+
+QUERY_CHANNEL_ORDER_SETTINGS = """
+ query getChannel($id: ID){
+ channel(id: $id){
+ id
+ name
+ slug
+ currencyCode
+ stockSettings{
+ allocationStrategy
+ }
+ orderSettings {
+ automaticallyConfirmAllNewOrders
+ automaticallyFulfillNonShippableGiftCard
+ }
+ }
+ }
+"""
+
+
+def test_query_channel_order_settings_as_staff_user(
+ permission_manage_channels, staff_api_client, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {"id": channel_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_CHANNEL_ORDER_SETTINGS,
+ variables=variables,
+ permissions=[permission_manage_channels],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ channel_data = content["data"]["channel"]
+ assert channel_data["id"] == channel_id
+ assert channel_data["name"] == channel_USD.name
+ assert channel_data["slug"] == channel_USD.slug
+ assert channel_data["currencyCode"] == channel_USD.currency_code
+ allocation_strategy = channel_data["stockSettings"]["allocationStrategy"]
+ assert (
+ AllocationStrategyEnum[allocation_strategy].value
+ == channel_USD.allocation_strategy
+ )
+ assert (
+ channel_data["orderSettings"]["automaticallyConfirmAllNewOrders"]
+ == channel_USD.automatically_confirm_all_new_orders
+ )
+ assert (
+ channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
+ == channel_USD.automatically_fulfill_non_shippable_gift_card
+ )
+
+
+def test_query_channel_order_settings_as_app(
+ permission_manage_channels,
+ app_api_client,
+ channel_USD,
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {"id": channel_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_CHANNEL_ORDER_SETTINGS,
+ variables=variables,
+ permissions=[permission_manage_channels],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ channel_data = content["data"]["channel"]
+ assert channel_data["id"] == channel_id
+ assert channel_data["name"] == channel_USD.name
+ assert channel_data["slug"] == channel_USD.slug
+ assert channel_data["currencyCode"] == channel_USD.currency_code
+ allocation_strategy = channel_data["stockSettings"]["allocationStrategy"]
+ assert (
+ AllocationStrategyEnum[allocation_strategy].value
+ == channel_USD.allocation_strategy
+ )
+ assert (
+ channel_data["orderSettings"]["automaticallyConfirmAllNewOrders"]
+ == channel_USD.automatically_confirm_all_new_orders
+ )
+ assert (
+ channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
+ == channel_USD.automatically_fulfill_non_shippable_gift_card
+ )
+
+
+def test_query_channel_order_settings_as_staff_user_no_permission(
+ staff_api_client, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {"id": channel_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_CHANNEL_ORDER_SETTINGS,
+ variables=variables,
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_channel_order_settings_as_app_no_permission(
+ app_api_client,
+ channel_USD,
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {"id": channel_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_CHANNEL_ORDER_SETTINGS,
+ variables=variables,
+ )
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.py
index 3a6c3f77cb..daa8232236 100644
--- a/saleor/graphql/channel/types.py
+++ b/saleor/graphql/channel/types.py
@@ -12,7 +12,7 @@ from promise import Promise
from ...channel import models
from ...core.models import ModelWithMetadata
from ...permission.auth_filters import AuthorizationFilters
-from ...permission.enums import ChannelPermissions
+from ...permission.enums import ChannelPermissions, OrderPermissions
from ..account.enums import CountryCodeEnum
from ..core import ResolveInfo
from ..core.descriptions import (
@@ -20,6 +20,7 @@ from ..core.descriptions import (
ADDED_IN_35,
ADDED_IN_36,
ADDED_IN_37,
+ ADDED_IN_312,
PREVIEW_FEATURE,
)
from ..core.fields import PermissionsField
@@ -161,7 +162,28 @@ class StockSettings(ObjectType):
)
-class Channel(ModelObjectType[models.Channel]):
+class OrderSettings(ObjectType):
+ automatically_confirm_all_new_orders = graphene.Boolean(
+ required=True,
+ description=(
+ "When disabled, all new orders from checkout "
+ "will be marked as unconfirmed. When enabled orders from checkout will "
+ "become unfulfilled immediately."
+ ),
+ )
+ automatically_fulfill_non_shippable_gift_card = graphene.Boolean(
+ required=True,
+ description=(
+ "When enabled, all non-shippable gift card orders "
+ "will be fulfilled automatically."
+ ),
+ )
+
+ class Meta:
+ description = "Represents the channel-specific order settings."
+
+
+class Channel(ModelObjectType):
id = graphene.GlobalID(required=True)
slug = graphene.String(
required=True,
@@ -252,6 +274,15 @@ class Channel(ModelObjectType[models.Channel]):
AuthorizationFilters.AUTHENTICATED_STAFF_USER,
],
)
+ order_settings = PermissionsField(
+ OrderSettings,
+ description="Channel-specific order settings." + ADDED_IN_312,
+ required=True,
+ permissions=[
+ ChannelPermissions.MANAGE_CHANNELS,
+ OrderPermissions.MANAGE_ORDERS,
+ ],
+ )
class Meta:
description = "Represents channel."
@@ -385,3 +416,14 @@ class Channel(ModelObjectType[models.Channel]):
@staticmethod
def resolve_stock_settings(root: models.Channel, _info: ResolveInfo):
return StockSettings(allocation_strategy=root.allocation_strategy)
+
+ @staticmethod
+ def resolve_order_settings(root: models.Channel, _info):
+ return OrderSettings(
+ automatically_confirm_all_new_orders=(
+ root.automatically_confirm_all_new_orders
+ ),
+ automatically_fulfill_non_shippable_gift_card=(
+ root.automatically_fulfill_non_shippable_gift_card
+ ),
+ )
diff --git a/saleor/graphql/checkout/mutations/order_create_from_checkout.py b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
index 523fba1832..1249311893 100644
--- a/saleor/graphql/checkout/mutations/order_create_from_checkout.py
+++ b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
@@ -86,7 +86,7 @@ class OrderCreateFromCheckout(BaseMutation):
support_private_meta_field = True
@classmethod
- def check_permissions(cls, context, permissions=None):
+ def check_permissions(cls, context, permissions=None, **data):
"""Determine whether app has rights to perform this mutation."""
permissions = permissions or cls._meta.permissions
app = getattr(context, "app", None)
diff --git a/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py b/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py
index ca6f457268..23caefd4f9 100644
--- a/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py
@@ -98,8 +98,9 @@ def test_checkout_complete(
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout_info, lines, address
)
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -259,8 +260,9 @@ def test_checkout_complete_for_token_as_input(
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout_info, lines, address
)
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
payment = payment_dummy
payment.is_active = True
payment.order = None
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
index c006b516fa..d853c289f7 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
@@ -233,7 +233,6 @@ def test_checkout_complete_with_inactive_channel(
def test_checkout_complete(
order_confirmed_mock,
_recalculate_order_prices_mock,
- site_settings,
user_api_client,
checkout_with_gift_card,
gift_card,
@@ -266,8 +265,9 @@ def test_checkout_complete(
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout_info, lines, address
)
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -347,7 +347,6 @@ def test_checkout_complete(
@patch("saleor.plugins.manager.PluginsManager.order_confirmed")
def test_checkout_complete_with_metadata(
order_confirmed_mock,
- site_settings,
user_api_client,
checkout_with_gift_card,
gift_card,
@@ -375,8 +374,9 @@ def test_checkout_complete_with_metadata(
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout_info, lines, address
)
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -451,8 +451,9 @@ def test_checkout_complete_with_metadata_updates_existing_keys(
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout_info, lines, address
)
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -645,9 +646,10 @@ def test_checkout_complete_gift_card_bought(
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout_info, lines, address
)
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.automatically_fulfill_non_shippable_gift_card = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.automatically_fulfill_non_shippable_gift_card = True
+ channel.save()
payment = payment_txn_captured
payment.is_active = True
@@ -736,8 +738,9 @@ def test_checkout_complete_with_variant_without_sku(
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout_info, lines, address
)
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -811,8 +814,9 @@ def test_checkout_complete_requires_confirmation(
payment_dummy,
checkout_ready_to_complete,
):
- site_settings.automatically_confirm_all_new_orders = False
- site_settings.save()
+ channel = checkout_ready_to_complete.channel
+ channel.automatically_confirm_all_new_orders = False
+ channel.save()
Site.objects.clear_cache()
payment = payment_dummy
payment.checkout = checkout_ready_to_complete
@@ -1451,8 +1455,9 @@ def test_checkout_complete_checkout_without_lines(
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout_info, lines, address
)
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -2728,8 +2733,9 @@ def test_checkout_complete_with_preorder_variant(
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout_info, lines, address
)
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -3754,8 +3760,9 @@ def test_checkout_complete_reservations_drop(
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout_info, lines, address
)
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -3805,8 +3812,9 @@ def test_checkout_complete_payment_create_create_run_in_meantime(
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout_info, lines, address
)
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
payment = payment_dummy
payment.is_active = True
payment.order = None
diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
index 66481a18fc..0a3c907413 100644
--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
@@ -145,8 +145,9 @@ def test_order_from_checkout(
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout_info, lines, address
)
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
orders_count = Order.objects.count()
variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
@@ -240,8 +241,9 @@ def test_order_from_checkout_with_metadata(
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout_info, lines, address
)
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
orders_count = Order.objects.count()
variables = {
@@ -352,9 +354,10 @@ def test_order_from_checkout_gift_card_bought(
txn.amount = amount
txn.save(update_fields=["amount"])
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.automatically_fulfill_non_shippable_gift_card = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.automatically_fulfill_non_shippable_gift_card = True
+ channel.save()
orders_count = Order.objects.count()
variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
@@ -447,8 +450,9 @@ def test_order_from_checkout_with_variant_without_sku(
checkout_line_variant.sku = None
checkout_line_variant.save()
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
orders_count = Order.objects.count()
variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
@@ -523,8 +527,9 @@ def test_order_from_checkout_requires_confirmation(
site_settings,
checkout_ready_to_complete,
):
- site_settings.automatically_confirm_all_new_orders = False
- site_settings.save()
+ channel = checkout_ready_to_complete.channel
+ channel.automatically_confirm_all_new_orders = False
+ channel.save()
variables = {
"id": graphene.Node.to_global_id("Checkout", checkout_ready_to_complete.pk),
@@ -720,8 +725,9 @@ def test_order_from_checkout_checkout_without_lines(
lines, _ = fetch_checkout_lines(checkout)
assert not lines
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
response = app_api_client.post_graphql(
@@ -1199,8 +1205,9 @@ def test_order_from_draft_create_with_preorder_variant(
total = calculations.calculate_checkout_total_with_gift_cards(
manager, checkout_info, lines, address
)
- site_settings.automatically_confirm_all_new_orders = True
- site_settings.save()
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
orders_count = Order.objects.count()
variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
diff --git a/saleor/graphql/core/descriptions.py b/saleor/graphql/core/descriptions.py
index 6cfa828420..c4928970a1 100644
--- a/saleor/graphql/core/descriptions.py
+++ b/saleor/graphql/core/descriptions.py
@@ -22,6 +22,7 @@ ADDED_IN_38 = "\n\nAdded in Saleor 3.8."
ADDED_IN_39 = "\n\nAdded in Saleor 3.9."
ADDED_IN_310 = "\n\nAdded in Saleor 3.10."
ADDED_IN_311 = "\n\nAdded in Saleor 3.11."
+ADDED_IN_312 = "\n\nAdded in Saleor 3.12."
PREVIEW_FEATURE = (
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index 86b66b5877..abcfc88b72 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -484,7 +484,7 @@ class BaseMutation(graphene.Mutation):
return instance
@classmethod
- def check_permissions(cls, context, permissions=None):
+ def check_permissions(cls, context, permissions=None, **data):
"""Determine whether user or app has rights to perform this mutation.
Default implementation assumes that account is allowed to perform any
@@ -504,7 +504,7 @@ class BaseMutation(graphene.Mutation):
set_mutation_flag_in_context(info.context)
setup_context_user(info.context)
- if not cls.check_permissions(info.context):
+ if not cls.check_permissions(info.context, data=data):
raise PermissionDenied(permissions=cls._meta.permissions)
manager = get_plugin_manager_promise(info.context).get()
result = manager.perform_mutation(
diff --git a/saleor/graphql/meta/mutations.py b/saleor/graphql/meta/mutations.py
index 5afeeecba8..d6a5064457 100644
--- a/saleor/graphql/meta/mutations.py
+++ b/saleor/graphql/meta/mutations.py
@@ -175,7 +175,7 @@ class BaseMetadataMutation(BaseMutation):
return graphene_type._meta.model
@classmethod
- def check_permissions(cls, context, permissions=None):
+ def check_permissions(cls, context, permissions=None, **data):
is_app = bool(getattr(context, "app", None))
if is_app and permissions and AccountPermissions.MANAGE_STAFF in permissions:
raise PermissionDenied(
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 3dfd67d4fe..7ae10e7a87 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -692,7 +692,7 @@ class TransactionCreate(BaseMutation):
permissions = (PaymentPermissions.HANDLE_PAYMENTS,)
@classmethod
- def check_permissions(cls, context, permissions=None):
+ def check_permissions(cls, context, permissions=None, **data):
"""Determine whether app has rights to perform this mutation."""
permissions = permissions or cls._meta.permissions
if app := getattr(context, "app", None):
@@ -1018,7 +1018,7 @@ class TransactionRequestAction(BaseMutation):
)
@classmethod
- def check_permissions(cls, context, permissions=None):
+ def check_permissions(cls, context, permissions=None, **data):
required_permissions = permissions or cls._meta.permissions
requestor = get_user_or_app_from_context(context)
for required_permission in required_permissions:
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 3bd4d7cc61..9eea50597f 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -233,11 +233,11 @@ type Query {
shop: Shop!
"""
- Order related settings from site settings.
+ Order related settings from site settings. Returns `orderSettings` for the first `channel` in alphabetical order.
Requires one of the following permissions: MANAGE_ORDERS.
"""
- orderSettings: OrderSettings
+ orderSettings: OrderSettings @deprecated(reason: "This field will be removed in Saleor 4.0. Use the `channel` query to fetch the `orderSettings` field instead.")
"""
Gift card related settings from site settings.
@@ -4348,6 +4348,15 @@ type Channel implements Node {
Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER.
"""
stockSettings: StockSettings!
+
+ """
+ Channel-specific order settings.
+
+ Added in Saleor 3.12.
+
+ Requires one of the following permissions: MANAGE_CHANNELS, MANAGE_ORDERS.
+ """
+ orderSettings: OrderSettings!
}
"""
@@ -4748,6 +4757,19 @@ enum AllocationStrategyEnum {
PRIORITIZE_HIGH_STOCK
}
+"""Represents the channel-specific order settings."""
+type OrderSettings {
+ """
+ When disabled, all new orders from checkout will be marked as unconfirmed. When enabled orders from checkout will become unfulfilled immediately.
+ """
+ automaticallyConfirmAllNewOrders: Boolean!
+
+ """
+ When enabled, all non-shippable gift card orders will be fulfilled automatically.
+ """
+ automaticallyFulfillNonShippableGiftCard: Boolean!
+}
+
"""Represents shipping method postal code rule."""
type ShippingMethodPostalCodeRule implements Node {
"""The ID of the object."""
@@ -10763,12 +10785,6 @@ type Limits {
warehouses: Int
}
-"""Order related settings from site settings."""
-type OrderSettings {
- automaticallyConfirmAllNewOrders: Boolean!
- automaticallyFulfillNonShippableGiftCard: Boolean!
-}
-
"""Gift card related settings from site settings."""
type GiftCardSettings {
"""The gift card expiry type settings."""
@@ -12339,14 +12355,14 @@ type Mutation {
): ShopAddressUpdate
"""
- Update shop order settings.
+ Update shop order settings across all channels. Returns `orderSettings` for the first `channel` in alphabetical order.
Requires one of the following permissions: MANAGE_ORDERS.
"""
orderSettingsUpdate(
"""Fields required to update shop order settings."""
input: OrderSettingsUpdateInput!
- ): OrderSettingsUpdate
+ ): OrderSettingsUpdate @deprecated(reason: "\\n\\nDEPRECATED: this mutation will be removed in Saleor 4.0. Use `channelUpdate` mutation instead.")
"""
Update gift card settings.
@@ -15087,9 +15103,10 @@ type Mutation {
): ChannelCreate
"""
- Update a channel.
+ Update a channel.
Requires one of the following permissions: MANAGE_CHANNELS.
+ Requires one of the following permissions when updating only orderSettings field: MANAGE_CHANNELS, MANAGE_ORDERS.
"""
channelUpdate(
"""ID of a channel to update."""
@@ -16899,7 +16916,7 @@ type ShopAddressUpdate {
}
"""
-Update shop order settings.
+Update shop order settings across all channels. Returns `orderSettings` for the first `channel` in alphabetical order.
Requires one of the following permissions: MANAGE_ORDERS.
"""
@@ -16930,12 +16947,12 @@ enum OrderSettingsErrorCode {
input OrderSettingsUpdateInput {
"""
- When disabled, all new orders from checkout will be marked as unconfirmed. When enabled orders from checkout will become unfulfilled immediately.
+ 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
"""
automaticallyConfirmAllNewOrders: Boolean
"""
- When enabled, all non-shippable gift card orders will be fulfilled automatically.
+ When enabled, all non-shippable gift card orders will be fulfilled automatically. By defualt set to True.
"""
automaticallyFulfillNonShippableGiftCard: Boolean
}
@@ -22354,6 +22371,13 @@ input ChannelCreateInput {
"""
addWarehouses: [ID!]
+ """
+ The channel order settings
+
+ Added in Saleor 3.12.
+ """
+ orderSettings: OrderSettingsInput
+
"""Name of the channel."""
name: String!
@@ -22380,10 +22404,23 @@ input StockSettingsInput {
allocationStrategy: AllocationStrategyEnum!
}
+input OrderSettingsInput {
+ """
+ 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
+ """
+ automaticallyConfirmAllNewOrders: Boolean
+
+ """
+ When enabled, all non-shippable gift card orders will be fulfilled automatically. By defualt set to True.
+ """
+ automaticallyFulfillNonShippableGiftCard: Boolean
+}
+
"""
-Update a channel.
+Update a channel.
Requires one of the following permissions: MANAGE_CHANNELS.
+Requires one of the following permissions when updating only orderSettings field: MANAGE_CHANNELS, MANAGE_ORDERS.
"""
type ChannelUpdate {
channelErrors: [ChannelError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
@@ -22416,6 +22453,13 @@ input ChannelUpdateInput {
"""
addWarehouses: [ID!]
+ """
+ The channel order settings
+
+ Added in Saleor 3.12.
+ """
+ orderSettings: OrderSettingsInput
+
"""Name of the channel."""
name: String
diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.py
index 19b2f212fd..c03893ad38 100644
--- a/saleor/graphql/shop/mutations.py
+++ b/saleor/graphql/shop/mutations.py
@@ -2,14 +2,16 @@ 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
+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, DEPRECATED_IN_3X_INPUT, PREVIEW_FEATURE
from ..core.enums import WeightUnitsEnum
@@ -22,7 +24,7 @@ from ..core.types import (
)
from ..site.dataloaders import get_site_promise
from .enums import GiftCardSettingsExpiryTypeEnum
-from .types import GiftCardSettings, OrderSettings, Shop
+from .types import GiftCardSettings, Shop
class ShopSettingsInput(graphene.InputObjectType):
@@ -372,12 +374,12 @@ class OrderSettingsUpdateInput(graphene.InputObjectType):
required=False,
description="When disabled, all new orders from checkout "
"will be marked as unconfirmed. When enabled orders from checkout will "
- "become unfulfilled immediately.",
+ "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.",
+ "will be fulfilled automatically. By defualt set to True.",
)
@@ -390,7 +392,10 @@ class OrderSettingsUpdate(BaseMutation):
)
class Meta:
- description = "Update shop order settings."
+ description = (
+ "Update shop order settings across all channels. "
+ "Returns `orderSettings` for the first `channel` in alphabetical order. "
+ )
permissions = (OrderPermissions.MANAGE_ORDERS,)
error_type_class = OrderSettingsError
error_type_field = "order_settings_errors"
@@ -401,18 +406,38 @@ class OrderSettingsUpdate(BaseMutation):
"automatically_confirm_all_new_orders",
"automatically_fulfill_non_shippable_gift_card",
]
- site = get_site_promise(info.context).get()
- instance = site.settings
- update_fields = []
+
+ 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,
+ )
+
+ update_fields = {}
for field in FIELDS:
- value = data["input"].get(field)
- if value is not None:
- setattr(instance, field, value)
- update_fields.append(field)
+ if field in data["input"]:
+ update_fields[field] = data["input"][field]
if update_fields:
- instance.save(update_fields=update_fields)
- return OrderSettingsUpdate(order_settings=instance)
+ 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
+ ),
+ )
+ return OrderSettingsUpdate(order_settings=order_settings)
class GiftCardSettingsUpdateInput(graphene.InputObjectType):
diff --git a/saleor/graphql/shop/schema.py b/saleor/graphql/shop/schema.py
index 2101702047..24cb5025f7 100644
--- a/saleor/graphql/shop/schema.py
+++ b/saleor/graphql/shop/schema.py
@@ -1,7 +1,9 @@
import graphene
+from ...channel import models as channel_models
from ...permission.enums import GiftcardPermissions, OrderPermissions
-from ..core.descriptions import DEPRECATED_IN_3X_MUTATION
+from ..channel.types import OrderSettings
+from ..core.descriptions import DEPRECATED_IN_3X_FIELD, DEPRECATED_IN_3X_MUTATION
from ..core.fields import PermissionsField
from ..site.dataloaders import load_site_callback
from ..translations.mutations import ShopSettingsTranslate
@@ -16,7 +18,7 @@ from .mutations import (
StaffNotificationRecipientDelete,
StaffNotificationRecipientUpdate,
)
-from .types import GiftCardSettings, OrderSettings, Shop
+from .types import GiftCardSettings, Shop
class ShopQueries(graphene.ObjectType):
@@ -27,7 +29,15 @@ class ShopQueries(graphene.ObjectType):
)
order_settings = PermissionsField(
OrderSettings,
- description="Order related settings from site settings.",
+ description=(
+ "Order related settings from site settings. "
+ "Returns `orderSettings` for the first `channel` in "
+ "alphabetical order."
+ ),
+ deprecation_reason=(
+ f"{DEPRECATED_IN_3X_FIELD} "
+ "Use the `channel` query to fetch the `orderSettings` field instead."
+ ),
permissions=[OrderPermissions.MANAGE_ORDERS],
)
gift_card_settings = PermissionsField(
@@ -40,9 +50,22 @@ class ShopQueries(graphene.ObjectType):
def resolve_shop(self, _info):
return Shop()
- @load_site_callback
- def resolve_order_settings(self, _info, site):
- return site.settings
+ def resolve_order_settings(self, _info):
+ channel = (
+ channel_models.Channel.objects.filter(is_active=True)
+ .order_by("slug")
+ .first()
+ )
+ if channel is None:
+ return None
+ return 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
+ ),
+ )
@load_site_callback
def resolve_gift_card_settings(self, _info, site):
@@ -62,5 +85,9 @@ class ShopMutations(graphene.ObjectType):
shop_settings_translate = ShopSettingsTranslate.Field()
shop_address_update = ShopAddressUpdate.Field()
- order_settings_update = OrderSettingsUpdate.Field()
+ order_settings_update = OrderSettingsUpdate.Field(
+ deprecation_reason=(
+ DEPRECATED_IN_3X_MUTATION + " Use `channelUpdate` mutation instead."
+ )
+ )
gift_card_settings_update = GiftCardSettingsUpdate.Field()
diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.py
index e6ba11c939..1a37708d34 100644
--- a/saleor/graphql/shop/tests/test_shop.py
+++ b/saleor/graphql/shop/tests/test_shop.py
@@ -1339,71 +1339,111 @@ ORDER_SETTINGS_UPDATE_MUTATION = """
def test_order_settings_update_by_staff(
- staff_api_client, permission_manage_orders, site_settings
+ staff_api_client, permission_manage_orders, channel_USD, channel_PLN
):
- assert site_settings.automatically_confirm_all_new_orders is True
+ # given
staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # 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
- site_settings.refresh_from_db()
- assert site_settings.automatically_confirm_all_new_orders is False
- assert site_settings.automatically_fulfill_non_shippable_gift_card is False
+ 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_nothing_changed(
- staff_api_client, permission_manage_orders, site_settings
+ staff_api_client, permission_manage_orders, channel_USD, channel_PLN
):
- assert site_settings.automatically_confirm_all_new_orders is True
+ # given
staff_api_client.user.user_permissions.add(permission_manage_orders)
+ QUERY = """
+ mutation {
+ orderSettingsUpdate(
+ input: {}
+ ) {
+ orderSettings {
+ automaticallyConfirmAllNewOrders
+ automaticallyFulfillNonShippableGiftCard
+ }
+ }
+ }
+ """
+
+ # when
response = staff_api_client.post_graphql(
- ORDER_SETTINGS_UPDATE_MUTATION,
+ 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
- site_settings.refresh_from_db()
- assert site_settings.automatically_confirm_all_new_orders is True
- assert site_settings.automatically_fulfill_non_shippable_gift_card 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, site_settings
+ app_api_client, permission_manage_orders, channel_USD, channel_PLN
):
- assert site_settings.automatically_confirm_all_new_orders is True
+ # 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
- site_settings.refresh_from_db()
- assert site_settings.automatically_confirm_all_new_orders is False
- assert site_settings.automatically_fulfill_non_shippable_gift_card is False
+ 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, permission_manage_orders, site_settings
+ user_api_client, channel_USD, channel_PLN
):
- assert site_settings.automatically_confirm_all_new_orders is True
+ # given
+
+ # when
response = user_api_client.post_graphql(
ORDER_SETTINGS_UPDATE_MUTATION,
{"confirmOrders": False, "fulfillGiftCards": False},
)
+
+ # then
assert_no_permission(response)
- site_settings.refresh_from_db()
- assert site_settings.automatically_confirm_all_new_orders is True
- assert site_settings.automatically_fulfill_non_shippable_gift_card 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
ORDER_SETTINGS_QUERY = """
@@ -1416,33 +1456,57 @@ ORDER_SETTINGS_QUERY = """
"""
-def test_order_settings_query_as_staff(
- staff_api_client, permission_manage_orders, site_settings
+def test_order_settings_query_one_channel(
+ staff_api_client, permission_manage_orders, channel_USD
):
- assert site_settings.automatically_confirm_all_new_orders is True
- assert site_settings.automatically_fulfill_non_shippable_gift_card is True
+ # given
+ channel_USD.automatically_confirm_all_new_orders = False
+ channel_USD.automatically_fulfill_non_shippable_gift_card = True
+ channel_USD.save()
- site_settings.automatically_confirm_all_new_orders = False
- site_settings.automatically_fulfill_non_shippable_gift_card = False
- site_settings.save(
- update_fields=[
- "automatically_confirm_all_new_orders",
- "automatically_fulfill_non_shippable_gift_card",
- ]
+ 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 False
+ assert content["data"]["orderSettings"]["automaticallyConfirmAllNewOrders"] is True
assert (
content["data"]["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
is False
)
-def test_order_settings_query_as_user(user_api_client, site_settings):
+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)
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 4a80f96273..dd5db3722d 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -116,8 +116,8 @@ def order_created(
payment=payment,
manager=manager,
)
- site_settings = Site.objects.get_current().settings
- if site_settings.automatically_confirm_all_new_orders or from_draft:
+ channel = order_info.channel
+ if channel.automatically_confirm_all_new_orders or from_draft:
order_confirmed(order, user, app, manager)
@@ -162,7 +162,7 @@ def handle_fully_paid_order(
if site_settings is None:
site_settings = Site.objects.get_current().settings
- if site_settings.automatically_fulfill_non_shippable_gift_card:
+ if order_info.channel.automatically_fulfill_non_shippable_gift_card:
order_lines = [line.line for line in order_info.lines_data]
fulfill_non_shippable_gift_cards(
order, order_lines, site_settings, user, app, manager
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index 83b0dd1147..3106f29c13 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -150,8 +150,9 @@ def test_handle_fully_paid_order_gift_cards_created(
"""Ensure the non shippable gift card are fulfilled when the flag for automatic
fulfillment non shippable gift card is set."""
# given
- site_settings.automatically_fulfill_non_shippable_gift_card = True
- site_settings.save(update_fields=["automatically_fulfill_non_shippable_gift_card"])
+ channel = order_with_lines.channel
+ channel.automatically_fulfill_non_shippable_gift_card = True
+ channel.save()
order = order_with_lines
@@ -221,8 +222,9 @@ def test_handle_fully_paid_order_gift_cards_not_created(
"""Ensure the non shippable gift card are not fulfilled when the flag for
automatic fulfillment non shippable gift card is not set."""
# given
- site_settings.automatically_fulfill_non_shippable_gift_card = False
- site_settings.save(update_fields=["automatically_fulfill_non_shippable_gift_card"])
+ channel = order_with_lines.channel
+ channel.automatically_fulfill_non_shippable_gift_card = False
+ channel.save()
order = order_with_lines
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index b36a34f6fb..a1dff0a752 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -5,7 +5,6 @@ from urllib.parse import urlencode, urljoin
import opentracing
import opentracing.tags
from django.contrib.auth.hashers import make_password
-from django.contrib.sites.models import Site
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse, HttpResponseNotFound
@@ -377,8 +376,9 @@ class AdyenGatewayPlugin(BasePlugin):
@property
def order_auto_confirmation(self):
- site_settings = Site.objects.get_current().settings
- return site_settings.automatically_confirm_all_new_orders
+ if self.channel is None:
+ return False
+ return self.channel.automatically_confirm_all_new_orders
def process_payment(
self, payment_information: "PaymentData", previous_value
diff --git a/saleor/payment/gateways/stripe/plugin.py b/saleor/payment/gateways/stripe/plugin.py
index df1c34540a..df17fe5c06 100644
--- a/saleor/payment/gateways/stripe/plugin.py
+++ b/saleor/payment/gateways/stripe/plugin.py
@@ -138,8 +138,9 @@ class StripeGatewayPlugin(BasePlugin):
@property
def order_auto_confirmation(self):
- site_settings = Site.objects.get_current().settings
- return site_settings.automatically_confirm_all_new_orders
+ if not self.channel:
+ return False
+ return self.channel.automatically_confirm_all_new_orders
def _get_transaction_details_for_stripe_status(
self, status: str
diff --git a/saleor/payment/gateways/stripe/tests/test_plugin.py b/saleor/payment/gateways/stripe/tests/test_plugin.py
index c0f5d7aab9..724184b5b2 100644
--- a/saleor/payment/gateways/stripe/tests/test_plugin.py
+++ b/saleor/payment/gateways/stripe/tests/test_plugin.py
@@ -7,7 +7,6 @@ from stripe.error import AuthenticationError, StripeError
from stripe.stripe_object import StripeObject
from .....plugins.models import PluginConfiguration
-from .....site.models import Site
from .... import TransactionKind
from ....interface import GatewayResponse, PaymentMethodInfo, StorePaymentMethodEnum
from ....utils import (
@@ -942,9 +941,8 @@ def test_process_payment_with_disabled_order_auto_confirmation(
channel_USD,
):
- site_settings = Site.objects.get_current().settings
- site_settings.automatically_confirm_all_new_orders = False
- site_settings.save(update_fields=["automatically_confirm_all_new_orders"])
+ channel_USD.automatically_confirm_all_new_orders = False
+ channel_USD.save()
payment_intent = Mock()
mocked_payment_intent.return_value = payment_intent
diff --git a/saleor/site/migrations/0035_sitesettings_separate_state_remove_order_settings.py b/saleor/site/migrations/0035_sitesettings_separate_state_remove_order_settings.py
new file mode 100644
index 0000000000..470467e418
--- /dev/null
+++ b/saleor/site/migrations/0035_sitesettings_separate_state_remove_order_settings.py
@@ -0,0 +1,71 @@
+# Generated by Django 3.2.16 on 2022-12-14 09:28
+
+from django.db import migrations, models
+
+# Separate state and database changes in migration to avoid downtime.
+# For next release will be prepared migration to remove the field from database.
+
+# Database fields in this migration are changed to null to allow adding new rows.
+# To reverse that operation, we will set all values for `SiteSettings` regarding the
+# first channel in alphabetical order.
+
+
+def update_order_settings_values_to_match_first_channel(apps, schema_editor):
+ SiteSettings = apps.get_model("site", "SiteSettings")
+ Channel = apps.get_model("channel", "Channel")
+
+ channel = Channel.objects.filter(is_active=True).order_by("slug").first()
+
+ if channel:
+ SiteSettings.objects.update(
+ automatically_confirm_all_new_orders=(
+ channel.automatically_confirm_all_new_orders
+ ),
+ automatically_fulfill_non_shippable_gift_card=(
+ channel.automatically_fulfill_non_shippable_gift_card
+ ),
+ )
+ else:
+ SiteSettings.objects.update(
+ automatically_confirm_all_new_orders=True,
+ automatically_fulfill_non_shippable_gift_card=True,
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("site", "0034_sitesettings_limit_quantity_per_checkout"),
+ ("channel", "0008_update_null_order_settings"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ database_operations=[
+ migrations.AlterField(
+ model_name="sitesettings",
+ name="automatically_fulfill_non_shippable_gift_card",
+ field=models.BooleanField(null=True, blank=True),
+ ),
+ migrations.AlterField(
+ model_name="sitesettings",
+ name="automatically_confirm_all_new_orders",
+ field=models.BooleanField(null=True, blank=True),
+ ),
+ migrations.RunPython(
+ migrations.RunPython.noop,
+ update_order_settings_values_to_match_first_channel,
+ ),
+ ],
+ state_operations=[
+ migrations.RemoveField(
+ model_name="sitesettings",
+ name="automatically_fulfill_non_shippable_gift_card",
+ ),
+ migrations.RemoveField(
+ model_name="sitesettings",
+ name="automatically_confirm_all_new_orders",
+ ),
+ ],
+ )
+ ]
diff --git a/saleor/site/models.py b/saleor/site/models.py
index 621bba21b7..35a866e18f 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -65,7 +65,6 @@ class SiteSettings(models.Model):
)
default_mail_sender_address = models.EmailField(blank=True, null=True)
customer_set_password_url = models.CharField(max_length=255, blank=True, null=True)
- automatically_confirm_all_new_orders = models.BooleanField(default=True)
fulfillment_auto_approve = models.BooleanField(default=True)
fulfillment_allow_unpaid = models.BooleanField(default=True)
@@ -92,7 +91,6 @@ class SiteSettings(models.Model):
max_length=32, choices=TimePeriodType.CHOICES, null=True, blank=True
)
gift_card_expiry_period = models.PositiveIntegerField(null=True, blank=True)
- automatically_fulfill_non_shippable_gift_card = models.BooleanField(default=True)
# deprecated
charge_taxes_on_shipping = models.BooleanField(default=True)