Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Better checkout error feedback (#13458)
Maciej Korycinski63efdd6ec67b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex aa97810780..68fbc1bbcb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -87,6 +87,11 @@ Shipping methods can be removed by the user after it has been assigned to a chec- Add support for unhandled field `Shop.trackInventoryByDefault` for `productVariantCreate` and `productVariantBulkCreate` - #13492 by @Smit-Parmar- - Add `AttributeBulkUpdate` mutation - #13532 by @SzymJ+- Better checkout error feedback - #13458 by @korycins+ - Add `Checkout.problems` field+ - Add `CheckoutLine.problems` field+ - Add `CheckoutSettingsInput` to `ChannelCreateInput` & `ChannelUpdateInput`+ - Add `checkoutSettings` field to `Channel`### Saleor Appsdiff --git a/saleor/channel/migrations/0015_channel_use_legacy_error_flow_for_checkout.py b/saleor/channel/migrations/0015_channel_use_legacy_error_flow_for_checkout.pynew file mode 100644index 0000000000..81ebade5eb--- /dev/null+++ b/saleor/channel/migrations/0015_channel_use_legacy_error_flow_for_checkout.py@@ -0,0 +1,25 @@+# Generated by Django 3.2.19 on 2023-06-07 13:23++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("channel", "0014_channel_allow_to_create_order_without_payment"),+ ]++ operations = [+ migrations.AddField(+ model_name="channel",+ name="use_legacy_error_flow_for_checkout",+ field=models.BooleanField(default=True),+ ),+ migrations.RunSQL(+ """+ ALTER TABLE channel_channel+ ALTER COLUMN use_legacy_error_flow_for_checkout+ SET DEFAULT true;+ """,+ migrations.RunSQL.noop,+ ),+ ]diff --git a/saleor/channel/models.py b/saleor/channel/models.pyindex dbb6d717b8..a9feab0638 100644--- a/saleor/channel/models.py+++ b/saleor/channel/models.py@@ -44,6 +44,8 @@ class Channel(ModelWithMetadata):default=timedelta(days=60),)+ use_legacy_error_flow_for_checkout = models.BooleanField(default=True)+class Meta(ModelWithMetadata.Meta):ordering = ("slug",)app_label = "channel"diff --git a/saleor/checkout/problems.py b/saleor/checkout/problems.pynew file mode 100644index 0000000000..972019a95e--- /dev/null+++ b/saleor/checkout/problems.py@@ -0,0 +1,198 @@+import datetime+from collections import defaultdict+from dataclasses import dataclass+from typing import Iterable, Optional, Tuple, Union++import pytz++from ..graphql.channel import ChannelContext+from ..product.models import ProductChannelListing, ProductVariant+from ..warehouse.models import Stock+from .fetch import CheckoutInfo, CheckoutLineInfo+from .models import CheckoutLine+++@dataclass+class CheckoutLineProblemInsufficientStock:+ available_quantity: int+ line: CheckoutLine+ variant: Optional[ChannelContext[ProductVariant]] = None+++@dataclass+class CheckoutLineProblemVariantNotAvailable:+ line: CheckoutLine+++CHECKOUT_LINE_PROBLEM_TYPE = Union[+ CheckoutLineProblemInsufficientStock, CheckoutLineProblemVariantNotAvailable+]+CHECKOUT_PROBLEM_TYPE = Union[+ CheckoutLineProblemInsufficientStock, CheckoutLineProblemVariantNotAvailable+]++VARIANT_ID = int+PRODUCT_ID = int+CHANNEL_SLUG = str+COUNTRY_CODE = str++CHECKOUT_LINE_PK_TYPE = str+++def get_insufficient_stock_lines(+ lines: Iterable["CheckoutLineInfo"],+ variant_stock_map: dict[+ tuple[+ VARIANT_ID,+ CHANNEL_SLUG,+ COUNTRY_CODE,+ ],+ Iterable[Stock],+ ],+ country_code: str,+) -> list[Tuple["CheckoutLineInfo", int]]:+ """Return checkout lines with insufficient stock."""+ variant_to_quantity_map: dict[int, int] = defaultdict(int)+ variant_to_available_quantity_map: dict[int, int] = defaultdict(int)+ for line_info in lines:+ variant_to_quantity_map[line_info.variant.id] += line_info.line.quantity+ variant_stocks = variant_stock_map.get(+ (line_info.variant.id, line_info.channel.slug, country_code), []+ )+ variant_to_available_quantity_map[line_info.variant.id] = sum(+ [+ stock.available_quantity # type: ignore[attr-defined]+ for stock in variant_stocks+ ]+ )+ insufficient_stocks = []+ for line_info in lines:+ if not line_info.variant.track_inventory:+ continue+ quantity = variant_to_quantity_map[line_info.variant.id]+ available_quantity = variant_to_available_quantity_map[line_info.variant.id]+ if available_quantity < quantity:+ insufficient_stocks.append((line_info, available_quantity))+ return insufficient_stocks+++def line_is_not_available(+ line: "CheckoutLineInfo",+ now: datetime.datetime,+ product_channel_listings_map: dict[+ tuple[+ PRODUCT_ID,+ CHANNEL_SLUG,+ ],+ ProductChannelListing,+ ],+) -> bool:+ product_channel_listing = product_channel_listings_map.get(+ (line.product.id, line.channel.slug), None+ )+ if not product_channel_listing:+ return True++ available_at = product_channel_listing.available_for_purchase_at+ if available_at is not None and available_at > now:+ return True++ if product_channel_listing.is_published is False:+ return True++ if not line.channel_listing:+ return True++ if line.channel_listing.price_amount is None:+ return True++ return False+++def get_not_available_lines(+ lines: Iterable["CheckoutLineInfo"],+ product_channel_listings_map: dict[+ tuple[+ PRODUCT_ID,+ CHANNEL_SLUG,+ ],+ ProductChannelListing,+ ],+):+ lines_not_available = []+ now = datetime.datetime.now(pytz.UTC)+ for line in lines:+ if line_is_not_available(line, now, product_channel_listings_map):+ lines_not_available.append(line)++ return lines_not_available+++def get_checkout_lines_problems(+ checkout_info: "CheckoutInfo",+ lines: Iterable["CheckoutLineInfo"],+ variant_stock_map: dict[+ tuple[+ VARIANT_ID,+ CHANNEL_SLUG,+ COUNTRY_CODE,+ ],+ Iterable[Stock],+ ],+ product_channel_listings_map: dict[+ tuple[+ PRODUCT_ID,+ CHANNEL_SLUG,+ ],+ ProductChannelListing,+ ],+) -> dict[CHECKOUT_LINE_PK_TYPE, list[CHECKOUT_LINE_PROBLEM_TYPE]]:+ """Return a list of all problems with the checkout lines.++ The stocks need to have annotated available_quantity field.+ """+ problems: dict[+ CHECKOUT_LINE_PK_TYPE, list[CHECKOUT_LINE_PROBLEM_TYPE]+ ] = defaultdict(list)++ not_available_lines = get_not_available_lines(lines, product_channel_listings_map)+ if not_available_lines:+ for line in not_available_lines:+ problems[str(line.line.pk)].append(+ CheckoutLineProblemVariantNotAvailable(line=line.line)+ )+ lines = [line for line in lines if line not in not_available_lines]++ insufficient_stock = get_insufficient_stock_lines(+ lines, variant_stock_map, checkout_info.checkout.country.code+ )+ if insufficient_stock:+ for line_info, available_quantity in insufficient_stock:+ problems[str(line_info.line.pk)].append(+ CheckoutLineProblemInsufficientStock(+ available_quantity=max(available_quantity, 0),+ line=line_info.line,+ variant=ChannelContext(+ node=line_info.variant, channel_slug=line_info.channel.slug+ ),+ )+ )+ return problems+++def get_checkout_problems(+ checkout_lines_problem: dict[+ CHECKOUT_LINE_PK_TYPE, list[CHECKOUT_LINE_PROBLEM_TYPE]+ ]+):+ """Return a list of all problems with the checkout.++ It accepts the list of the checkout line info with the list of the stocks available+ for the given line. It returns a list of the problems with the checkout.++ The stocks need to have annotated available_quantity field.+ """+ problems = []+ for line_problems in checkout_lines_problem.values():+ problems.extend(line_problems)+ return problemsdiff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.pyindex aafe6e6159..43e527496f 100644--- a/saleor/graphql/account/mutations/base.py+++ b/saleor/graphql/account/mutations/base.py@@ -423,7 +423,13 @@ class StaffDeleteMixin(UserDeleteMixin):abstract = True@classmethod- def check_permissions(cls, context: SaleorContext, permissions=None, **data):+ def check_permissions(+ cls,+ context: SaleorContext,+ permissions=None,+ require_all_permissions=False,+ **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.pyindex d28a10c01a..62454f7703 100644--- a/saleor/graphql/channel/mutations/channel_create.py+++ b/saleor/graphql/channel/mutations/channel_create.py@@ -16,10 +16,12 @@ from ...core.descriptions import (ADDED_IN_313,ADDED_IN_314,ADDED_IN_315,+ DEPRECATED_IN_3X_INPUT,PREVIEW_FEATURE,)from ...core.doc_category import (DOC_CATEGORY_CHANNELS,+ DOC_CATEGORY_CHECKOUT,DOC_CATEGORY_ORDERS,DOC_CATEGORY_PRODUCTS,)@@ -36,7 +38,7 @@ from ..enums import (TransactionFlowStrategyEnum,)from ..types import Channel-from .utils import clean_delete_expired_orders_after, clean_expire_orders_after+from .utils import clean_input_checkout_settings, clean_input_order_settingsclass StockSettingsInput(BaseInputObjectType):@@ -52,6 +54,26 @@ class StockSettingsInput(BaseInputObjectType):doc_category = DOC_CATEGORY_PRODUCTS+class CheckoutSettingsInput(BaseInputObjectType):+ use_legacy_error_flow = graphene.Boolean(+ description=(+ "Default `true`. Determines if the checkout mutations should use legacy "+ "error flow. In legacy flow, all mutations can raise an exception "+ "unrelated to the requested action - (e.g. out-of-stock exception when "+ "updating checkoutShippingAddress.) "+ "If `false`, the errors will be aggregated in `checkout.problems` field. "+ "Some of the `problems` can block the finalizing checkout process. "+ "The legacy flow will be removed in Saleor 4.0. "+ "The flow with `checkout.problems` will be the default one. "+ + ADDED_IN_315+ + DEPRECATED_IN_3X_INPUT+ )+ )++ class Meta:+ doc_category = DOC_CATEGORY_CHECKOUT++class OrderSettingsInput(BaseInputObjectType):automatically_confirm_all_new_orders = graphene.Boolean(required=False,@@ -146,6 +168,12 @@ class ChannelInput(BaseInputObjectType):required=False,)+ checkout_settings = graphene.Field(+ CheckoutSettingsInput,+ description="The channel checkout settings" + ADDED_IN_315 + PREVIEW_FEATURE,+ required=False,+ )+class Meta:doc_category = DOC_CATEGORY_CHANNELS@@ -204,48 +232,10 @@ class ChannelCreate(ModelMutation):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- if mark_as_paid_strategy := order_settings.get("mark_as_paid_strategy"):- cleaned_input["order_mark_as_paid_strategy"] = mark_as_paid_strategy-- if "expire_orders_after" in order_settings:- expire_orders_after = order_settings["expire_orders_after"]- cleaned_input["expire_orders_after"] = clean_expire_orders_after(- expire_orders_after- )-- if "delete_expired_orders_after" in order_settings:- delete_expired_orders_after = order_settings[- "delete_expired_orders_after"- ]- cleaned_input[- "delete_expired_orders_after"- ] = clean_delete_expired_orders_after(delete_expired_orders_after)-- if default_transaction_strategy := order_settings.get(- "default_transaction_flow_strategy"- ):- cleaned_input[- "default_transaction_flow_strategy"- ] = default_transaction_strategy+ clean_input_order_settings(order_settings, cleaned_input)- allow_unpaid_orders = order_settings.get("allow_unpaid_orders")- if allow_unpaid_orders is not None:- cleaned_input["allow_unpaid_orders"] = allow_unpaid_orders+ if checkout_settings := cleaned_input.get("checkout_settings"):+ clean_input_checkout_settings(checkout_settings, cleaned_input)return cleaned_inputdiff --git a/saleor/graphql/channel/mutations/channel_update.py b/saleor/graphql/channel/mutations/channel_update.pyindex 76600be8b6..5178e1e96b 100644--- a/saleor/graphql/channel/mutations/channel_update.py+++ b/saleor/graphql/channel/mutations/channel_update.py@@ -5,7 +5,11 @@ from django.utils.text import slugifyfrom ....channel import modelsfrom ....channel.error_codes import ChannelErrorCodefrom ....core.tracing import traced_atomic_transaction-from ....permission.enums import ChannelPermissions, OrderPermissions+from ....permission.enums import (+ ChannelPermissions,+ CheckoutPermissions,+ OrderPermissions,+)from ....shipping.tasks import (drop_invalid_shipping_methods_relations_for_given_channels,)@@ -22,7 +26,7 @@ from ...utils.validators import check_for_duplicatesfrom ..types import Channelfrom ..utils import delete_invalid_warehouse_to_shipping_zone_relationsfrom .channel_create import ChannelInput-from .utils import clean_delete_expired_orders_after, clean_expire_orders_after+from .utils import clean_input_checkout_settings, clean_input_order_settingsclass ChannelUpdateInput(ChannelInput):@@ -62,8 +66,11 @@ class ChannelUpdate(ModelMutation):"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: "+ "when updating only `orderSettings` field: ""MANAGE_CHANNELS, MANAGE_ORDERS."+ "Requires one of the following permissions "+ "when updating only `checkoutSettings` field: "+ "MANAGE_CHANNELS, MANAGE_CHECKOUTS.")auto_permission_message = Falsemodel = models.Channel@@ -110,64 +117,41 @@ class ChannelUpdate(ModelMutation):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-- if "expire_orders_after" in order_settings:- expire_orders_after = order_settings["expire_orders_after"]- cleaned_input["expire_orders_after"] = clean_expire_orders_after(- expire_orders_after- )-- if "delete_expired_orders_after" in order_settings:- delete_expired_orders_after = order_settings[- "delete_expired_orders_after"- ]- cleaned_input[- "delete_expired_orders_after"- ] = clean_delete_expired_orders_after(delete_expired_orders_after)+ clean_input_order_settings(order_settings, cleaned_input)- if mark_as_paid_strategy := order_settings.get("mark_as_paid_strategy"):- cleaned_input["order_mark_as_paid_strategy"] = mark_as_paid_strategy-- if default_transaction_strategy := order_settings.get(- "default_transaction_flow_strategy"- ):- cleaned_input[- "default_transaction_flow_strategy"- ] = default_transaction_strategy-- allow_unpaid_orders = order_settings.get("allow_unpaid_orders")- if allow_unpaid_orders is not None:- cleaned_input["allow_unpaid_orders"] = allow_unpaid_orders+ if checkout_settings := cleaned_input.get("checkout_settings"):+ clean_input_checkout_settings(checkout_settings, cleaned_input)return cleaned_input@classmethoddef check_permissions(cls, context, permissions=None, **data):permissions = [ChannelPermissions.MANAGE_CHANNELS]-+ all_perm_required = False# 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:++ if ["order_settings"] == list(input.keys()):permissions.append(OrderPermissions.MANAGE_ORDERS)- return super().check_permissions(context, permissions, **data)+ # Permission MANAGE_CHECKOUTS or MANAGE_CHANNELS is required to update+ # checkoutSettings.+ if ["checkout_settings"] == list(input.keys()):+ permissions.append(CheckoutPermissions.MANAGE_CHECKOUTS)++ if set(["order_settings", "checkout_settings"]) == set(input.keys()):+ permissions = [+ OrderPermissions.MANAGE_ORDERS,+ CheckoutPermissions.MANAGE_CHECKOUTS,+ ]+ all_perm_required = True++ return super().check_permissions(+ context, permissions, require_all_permissions=all_perm_required, **data+ )@classmethoddef _save_m2m(cls, info: ResolveInfo, instance, cleaned_data):diff --git a/saleor/graphql/channel/mutations/utils.py b/saleor/graphql/channel/mutations/utils.pyindex b320324d38..1e927c381d 100644--- a/saleor/graphql/channel/mutations/utils.py+++ b/saleor/graphql/channel/mutations/utils.py@@ -38,3 +38,53 @@ def clean_delete_expired_orders_after(delete_expired_orders_after: int) -> timed})return timedelta(days=delete_expired_orders_after)+++def clean_input_order_settings(order_settings: dict, cleaned_input: dict):+ 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+ if mark_as_paid_strategy := order_settings.get("mark_as_paid_strategy"):+ cleaned_input["order_mark_as_paid_strategy"] = mark_as_paid_strategy++ if "expire_orders_after" in order_settings:+ expire_orders_after = order_settings["expire_orders_after"]+ cleaned_input["expire_orders_after"] = clean_expire_orders_after(+ expire_orders_after+ )++ if "delete_expired_orders_after" in order_settings:+ delete_expired_orders_after = order_settings["delete_expired_orders_after"]+ cleaned_input[+ "delete_expired_orders_after"+ ] = clean_delete_expired_orders_after(delete_expired_orders_after)++ if default_transaction_strategy := order_settings.get(+ "default_transaction_flow_strategy"+ ):+ cleaned_input[+ "default_transaction_flow_strategy"+ ] = default_transaction_strategy++ allow_unpaid_orders = order_settings.get("allow_unpaid_orders")+ if allow_unpaid_orders is not None:+ cleaned_input["allow_unpaid_orders"] = allow_unpaid_orders+++def clean_input_checkout_settings(checkout_settings: dict, cleaned_input: dict):+ if "use_legacy_error_flow" in checkout_settings:+ cleaned_input["use_legacy_error_flow_for_checkout"] = checkout_settings[+ "use_legacy_error_flow"+ ]diff --git a/saleor/graphql/channel/tests/mutations/test_channel_create.py b/saleor/graphql/channel/tests/mutations/test_channel_create.pyindex 3d11c69176..298cd45342 100644--- a/saleor/graphql/channel/tests/mutations/test_channel_create.py+++ b/saleor/graphql/channel/tests/mutations/test_channel_create.py@@ -48,6 +48,9 @@ CHANNEL_CREATE_MUTATION = """deleteExpiredOrdersAfterallowUnpaidOrders}+ checkoutSettings {+ useLegacyErrorFlow+ }}errors{field@@ -81,6 +84,7 @@ def test_channel_create_mutation_as_staff_user("automaticallyFulfillNonShippableGiftCard": False,"expireOrdersAfter": 10,},+ "checkoutSettings": {"useLegacyErrorFlow": False},}}@@ -112,6 +116,7 @@ def test_channel_create_mutation_as_staff_user(is False)assert channel_data["orderSettings"]["expireOrdersAfter"] == 10+ assert channel_data["checkoutSettings"]["useLegacyErrorFlow"] is Falsedef test_channel_create_mutation_as_app(@@ -129,6 +134,7 @@ def test_channel_create_mutation_as_app("slug": slug,"currencyCode": currency_code,"defaultCountry": default_country,+ "checkoutSettings": {"useLegacyErrorFlow": False},}}@@ -163,6 +169,7 @@ def test_channel_create_mutation_as_app(is True)assert channel_data["orderSettings"]["expireOrdersAfter"] is None+ assert channel_data["checkoutSettings"]["useLegacyErrorFlow"] is Falsedef test_channel_create_mutation_as_customer(user_api_client):@@ -714,6 +721,42 @@ def test_channel_create_mutation_set_incorrect_delete_expired_orders_after(assert error["code"] == ChannelErrorCode.INVALID.name+def test_channel_create_set_checkout_use_legacy_error_flow(+ permission_manage_channels,+ staff_api_client,+):+ # given+ name = "testName"+ slug = "test_slug"+ currency_code = "USD"+ default_country = "US"+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ "checkoutSettings": {"useLegacyErrorFlow": False},+ }+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_CREATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelCreate"]+ assert not data["errors"]+ channel_data = data["channel"]+ channel = Channel.objects.get()+ assert channel_data["checkoutSettings"]["useLegacyErrorFlow"] is False+ assert channel.use_legacy_error_flow_for_checkout is False++@pytest.mark.parametrize("allowUnpaid", [True, False])def test_channel_create_set_allow_unpaid_orders(allowUnpaid,diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.pyindex 52e139f75b..9bd0dd9aff 100644--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py@@ -1137,3 +1137,213 @@ def test_channel_update_set_incorrect_delete_expired_orders_after(error = content["data"]["channelUpdate"]["errors"][0]assert error["field"] == "deleteExpiredOrdersAfter"assert error["code"] == ChannelErrorCode.INVALID.name+++CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS = """+ mutation UpdateChannel($id: ID!,$input: ChannelUpdateInput!){+ channelUpdate(id: $id, input: $input){+ channel{+ id+ name+ slug+ currencyCode+ checkoutSettings {+ useLegacyErrorFlow+ }+ }+ errors{+ field+ code+ message+ shippingZones+ warehouses+ }+ }+ }+"""+++def test_channel_update_set_checkout_use_legacy_error_flow(+ permission_manage_channels, staff_api_client, channel_USD+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": channel_id,+ "input": {+ "checkoutSettings": {"useLegacyErrorFlow": False},+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelUpdate"]+ assert not data["errors"]+ channel_data = data["channel"]+ channel_USD.refresh_from_db()+ assert channel_data["checkoutSettings"]["useLegacyErrorFlow"] is False+ assert channel_USD.use_legacy_error_flow_for_checkout is False+++def test_channel_update_set_checkout_use_legacy_error_flow_with_checkout_permission(+ permission_manage_checkouts, staff_api_client, channel_USD+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": channel_id,+ "input": {+ "checkoutSettings": {"useLegacyErrorFlow": False},+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=(permission_manage_checkouts,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelUpdate"]+ assert not data["errors"]+ channel_data = data["channel"]+ channel_USD.refresh_from_db()+ assert channel_data["checkoutSettings"]["useLegacyErrorFlow"] is False+ assert channel_USD.use_legacy_error_flow_for_checkout is False+++def test_channel_update_set_checkout_use_legacy_error_flow_without_permission(+ staff_api_client, channel_USD+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": channel_id,+ "input": {+ "checkoutSettings": {"useLegacyErrorFlow": False},+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ )++ # then+ assert_no_permission(response)+++def test_channel_update_checkout_and_order_settings_with_manage_orders(+ staff_api_client, channel_USD, permission_manage_orders+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": channel_id,+ "input": {+ "checkoutSettings": {"useLegacyErrorFlow": False},+ "orderSettings": {"automaticallyConfirmAllNewOrders": False},+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=[permission_manage_orders],+ )++ # then+ assert_no_permission(response)+++def test_channel_update_order_and_checkout_settings_with_manage_checkouts(+ staff_api_client, channel_USD, permission_manage_checkouts+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": channel_id,+ "input": {+ "orderSettings": {"automaticallyConfirmAllNewOrders": False},+ "checkoutSettings": {"useLegacyErrorFlow": False},+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=[permission_manage_checkouts],+ )++ # then+ assert_no_permission(response)+++def test_channel_update_with_order_and_checkout_settings(+ staff_api_client, channel_USD, permission_manage_checkouts, permission_manage_orders+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": channel_id,+ "input": {+ "orderSettings": {"automaticallyConfirmAllNewOrders": False},+ "checkoutSettings": {"useLegacyErrorFlow": False},+ },+ }+ query = """+ mutation UpdateChannel($id: ID!,$input: ChannelUpdateInput!){+ channelUpdate(id: $id, input: $input){+ channel{+ id+ name+ slug+ currencyCode+ checkoutSettings {+ useLegacyErrorFlow+ }+ orderSettings {+ automaticallyConfirmAllNewOrders+ }+ }+ errors{+ field+ code+ message+ shippingZones+ warehouses+ }+ }+ }+ """++ # when+ response = staff_api_client.post_graphql(+ query,+ variables=variables,+ permissions=[permission_manage_checkouts, permission_manage_orders],+ )++ # then+ content = get_graphql_content(response)++ data = content["data"]["channelUpdate"]+ assert not data["errors"]+ channel_data = data["channel"]+ channel_USD.refresh_from_db()+ assert channel_data["checkoutSettings"]["useLegacyErrorFlow"] is False+ assert channel_USD.use_legacy_error_flow_for_checkout is False+ assert channel_data["orderSettings"]["automaticallyConfirmAllNewOrders"] is False+ assert channel_USD.automatically_confirm_all_new_orders is Falsediff --git a/saleor/graphql/channel/tests/queries/test_channel.py b/saleor/graphql/channel/tests/queries/test_channel.pyindex 07a6b98d72..693381a626 100644--- a/saleor/graphql/channel/tests/queries/test_channel.py+++ b/saleor/graphql/channel/tests/queries/test_channel.py@@ -430,3 +430,128 @@ def test_query_channel_order_settings_as_app_no_permission(# thenassert_no_permission(response)+++QUERY_CHANNEL_CHECKOUT_SETTINGS = """+ query getChannel($id: ID){+ channel(id: $id){+ id+ checkoutSettings {+ useLegacyErrorFlow+ }+ }+ }+"""+++def test_query_channel_checkout_settings_as_staff_user(+ permission_manage_channels, staff_api_client, channel_USD+):+ # given+ channel_USD.use_legacy_error_flow_for_checkout = False+ channel_USD.save()+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {"id": channel_id}++ # when+ response = staff_api_client.post_graphql(+ QUERY_CHANNEL_CHECKOUT_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["checkoutSettings"]["useLegacyErrorFlow"]+ == channel_USD.use_legacy_error_flow_for_checkout+ )+++def test_query_channel_checkout_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_CHECKOUT_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["checkoutSettings"]["useLegacyErrorFlow"]+ == channel_USD.use_legacy_error_flow_for_checkout+ )+++def test_query_channel_checkout_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_CHECKOUT_SETTINGS,+ variables=variables,+ )++ # then+ assert_no_permission(response)+++def test_query_channel_checkout_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_CHECKOUT_SETTINGS,+ variables=variables,+ )++ # then+ assert_no_permission(response)+++def test_query_channel_checkout_settings_with_manage_checkouts(+ permission_manage_checkouts, staff_api_client, channel_USD+):+ # given+ channel_USD.use_legacy_error_flow_for_checkout = False+ channel_USD.save()+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {"id": channel_id}++ # when+ response = staff_api_client.post_graphql(+ QUERY_CHANNEL_CHECKOUT_SETTINGS,+ variables=variables,+ permissions=[permission_manage_checkouts],+ )+ content = get_graphql_content(response)++ # then+ channel_data = content["data"]["channel"]+ assert channel_data["id"] == channel_id+ assert (+ channel_data["checkoutSettings"]["useLegacyErrorFlow"]+ == channel_USD.use_legacy_error_flow_for_checkout+ )diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.pyindex f1789caa4d..2b6d6e0b14 100644--- a/saleor/graphql/channel/types.py+++ b/saleor/graphql/channel/types.py@@ -12,7 +12,11 @@ from promise import Promisefrom ...channel import modelsfrom ...core.models import ModelWithMetadatafrom ...permission.auth_filters import AuthorizationFilters-from ...permission.enums import ChannelPermissions, OrderPermissions+from ...permission.enums import (+ ChannelPermissions,+ CheckoutPermissions,+ OrderPermissions,+)from ..account.enums import CountryCodeEnumfrom ..core import ResolveInfofrom ..core.descriptions import (@@ -24,9 +28,14 @@ from ..core.descriptions import (ADDED_IN_313,ADDED_IN_314,ADDED_IN_315,+ DEPRECATED_IN_3X_FIELD,PREVIEW_FEATURE,)-from ..core.doc_category import DOC_CATEGORY_ORDERS, DOC_CATEGORY_PRODUCTS+from ..core.doc_category import (+ DOC_CATEGORY_CHECKOUT,+ DOC_CATEGORY_ORDERS,+ DOC_CATEGORY_PRODUCTS,+)from ..core.fields import PermissionsFieldfrom ..core.scalars import Day, Minutefrom ..core.types import BaseObjectType, CountryDisplay, ModelObjectType, NonNullList@@ -169,6 +178,32 @@ class StockSettings(BaseObjectType):doc_category = DOC_CATEGORY_PRODUCTS+class CheckoutSettings(ObjectType):+ use_legacy_error_flow = graphene.Boolean(+ required=True,+ description=(+ "Default `true`. Determines if the checkout mutations should use legacy "+ "error flow. In legacy flow, all mutations can raise an exception "+ "unrelated to the requested action - (e.g. out-of-stock exception when "+ "updating checkoutShippingAddress.) "+ "If `false`, the errors will be aggregated in `checkout.problems` field. "+ "Some of the `problems` can block the finalizing checkout process. "+ "The legacy flow will be removed in Saleor 4.0. "+ "The flow with `checkout.problems` will be the default one."+ + ADDED_IN_315+ + DEPRECATED_IN_3X_FIELD+ ),+ )++ class Meta:+ description = (+ "Represents the channel-specific checkout settings."+ + ADDED_IN_315+ + PREVIEW_FEATURE+ )+ doc_category = DOC_CATEGORY_CHECKOUT++class OrderSettings(ObjectType):automatically_confirm_all_new_orders = graphene.Boolean(required=True,@@ -329,6 +364,18 @@ class Channel(ModelObjectType):],)+ checkout_settings = PermissionsField(+ CheckoutSettings,+ description="Channel-specific checkout settings."+ + ADDED_IN_315+ + PREVIEW_FEATURE,+ required=True,+ permissions=[+ ChannelPermissions.MANAGE_CHANNELS,+ CheckoutPermissions.MANAGE_CHECKOUTS,+ ],+ )+class Meta:description = "Represents channel."model = models.Channel@@ -478,3 +525,9 @@ class Channel(ModelObjectType):delete_expired_orders_after=root.delete_expired_orders_after.days,allow_unpaid_orders=(root.allow_unpaid_orders),)++ @staticmethod+ def resolve_checkout_settings(root: models.Channel, _info):+ return CheckoutSettings(+ use_legacy_error_flow=root.use_legacy_error_flow_for_checkout+ )diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.pyindex 24c53b076a..1debe1051b 100644--- a/saleor/graphql/checkout/dataloaders.py+++ b/saleor/graphql/checkout/dataloaders.py@@ -12,8 +12,20 @@ from ...checkout.fetch import (update_delivery_method_lists_for_checkout_info,)from ...checkout.models import Checkout, CheckoutLine, CheckoutMetadata+from ...checkout.problems import (+ CHANNEL_SLUG,+ CHECKOUT_LINE_PROBLEM_TYPE,+ CHECKOUT_PROBLEM_TYPE,+ COUNTRY_CODE,+ PRODUCT_ID,+ VARIANT_ID,+ get_checkout_lines_problems,+ get_checkout_problems,+)from ...discount import VoucherTypefrom ...payment.models import TransactionItem+from ...product.models import ProductChannelListing+from ...warehouse.models import Stockfrom ..account.dataloaders import AddressByIdLoader, UserByUserIdLoaderfrom ..channel.dataloaders import ChannelByIdLoaderfrom ..core.dataloaders import DataLoader@@ -26,6 +38,7 @@ from ..plugins.dataloaders import get_plugin_manager_promisefrom ..product.dataloaders import (CollectionsByVariantIdLoader,ProductByVariantIdLoader,+ ProductChannelListingByProductIdAndChannelSlugLoader,ProductTypeByVariantIdLoader,ProductVariantByIdLoader,VariantChannelListingByVariantIdAndChannelIdLoader,@@ -35,7 +48,10 @@ from ..shipping.dataloaders import (ShippingMethodChannelListingByChannelSlugLoader,)from ..tax.dataloaders import TaxClassByVariantIdLoader, TaxConfigurationByChannelId-from ..warehouse.dataloaders import WarehouseByIdLoader+from ..warehouse.dataloaders import (+ StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader,+ WarehouseByIdLoader,+)class CheckoutByTokenLoader(DataLoader[str, Checkout]):@@ -459,3 +475,138 @@ class ChannelByCheckoutLineIDLoader(DataLoader):return (CheckoutLineByIdLoader(self.context).load_many(keys).then(channel_by_lines))+++class CheckoutLinesProblemsByCheckoutIdLoader(+ DataLoader[str, dict[str, list[CHECKOUT_LINE_PROBLEM_TYPE]]]+):+ context_key = "checkout_lines_problems_by_checkout_id"++ def batch_load(self, keys):+ stock_dataloader = (+ StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(+ self.context+ )+ )++ def _resolve_problems(data):+ checkout_infos, checkout_lines = data+ variant_data_set: set[+ tuple[+ VARIANT_ID,+ CHANNEL_SLUG,+ COUNTRY_CODE,+ ]+ ] = set()+ product_data_set: set[+ tuple[+ PRODUCT_ID,+ CHANNEL_SLUG,+ ]+ ] = set()+ checkout_infos_map = {+ checkout_info.checkout.pk: checkout_info+ for checkout_info in checkout_infos+ }+ for lines in checkout_lines:+ for line in lines:+ variant_data_set.add(+ (+ line.variant.id,+ line.channel.slug,+ checkout_infos_map[line.line.checkout_id].checkout.country,+ )+ )+ product_data_set.add(+ (+ line.product.id,+ line.channel.slug,+ )+ )+ variant_data_list = list(variant_data_set)+ product_data_list = list(product_data_set)++ def _prepare_problems(data):+ (+ variant_stocks,+ product_channel_listings,+ ) = data+ variant_stock_map: dict[+ tuple[+ VARIANT_ID,+ CHANNEL_SLUG,+ COUNTRY_CODE,+ ],+ Iterable[Stock],+ ] = dict(zip(variant_data_list, variant_stocks))+ product_channel_listings_map: dict[+ tuple[+ PRODUCT_ID,+ CHANNEL_SLUG,+ ],+ ProductChannelListing,+ ] = dict(zip(product_data_set, product_channel_listings))++ problems = {}++ for checkout_info, lines in zip(checkout_infos, checkout_lines):+ checkout_id = checkout_info.checkout.pk+ problems[checkout_id] = get_checkout_lines_problems(+ checkout_info,+ lines,+ variant_stock_map,+ product_channel_listings_map,+ )+ return [problems.get(key, []) for key in keys]++ variant_stocks = stock_dataloader.load_many(+ [+ (variant_id, country_code, channel_slug)+ for variant_id, channel_slug, country_code in variant_data_list+ ]+ )+ product_channel_listings = (+ ProductChannelListingByProductIdAndChannelSlugLoader(+ self.context+ ).load_many(+ [+ (+ product_id,+ channel_slug,+ )+ for product_id, channel_slug in product_data_list+ ]+ )+ )++ return Promise.all([variant_stocks, product_channel_listings]).then(+ _prepare_problems+ )++ checkout_infos = CheckoutInfoByCheckoutTokenLoader(self.context).load_many(keys)+ lines = CheckoutLinesInfoByCheckoutTokenLoader(self.context).load_many(keys)+ return Promise.all([checkout_infos, lines]).then(_resolve_problems)+++class CheckoutProblemsByCheckoutIdDataloader(+ DataLoader[str, dict[str, list[CHECKOUT_PROBLEM_TYPE]]]+):+ context_key = "checkout_problems_by_checkout_id"++ def batch_load(self, keys):+ line_problems_dataloader = CheckoutLinesProblemsByCheckoutIdLoader(self.context)++ def _resolve_problems(+ checkouts_lines_problems: list[dict[str, list[CHECKOUT_LINE_PROBLEM_TYPE]]]+ ):+ checkout_problems = defaultdict(list)+ for checkout_pk, checkout_lines_problems in zip(+ keys, checkouts_lines_problems+ ):+ checkout_problems[checkout_pk] = get_checkout_problems(+ checkout_lines_problems+ )++ return [checkout_problems.get(key, []) for key in keys]++ return line_problems_dataloader.load_many(keys).then(_resolve_problems)diff --git a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py b/saleor/graphql/checkout/mutations/checkout_add_promo_code.pyindex c32906a4cb..e0bff6eeb6 100644--- a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py+++ b/saleor/graphql/checkout/mutations/checkout_add_promo_code.py@@ -74,7 +74,10 @@ class CheckoutAddPromoCode(BaseMutation):manager = get_plugin_manager_promise(info.context).get()lines, unavailable_variant_pks = fetch_checkout_lines(checkout)- if unavailable_variant_pks:+ if (+ unavailable_variant_pks+ and checkout.channel.use_legacy_error_flow_for_checkout+ ):not_available_variants_ids = {graphene.Node.to_global_id("ProductVariant", pk)for pk in unavailable_variant_pksdiff --git a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.pyindex 099e960ea4..aa9585a801 100644--- a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py+++ b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py@@ -292,9 +292,13 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):):checkout = get_checkout(cls, info, checkout_id=None, token=token, id=id)+ use_legacy_error_flow_for_checkout = (+ checkout.channel.use_legacy_error_flow_for_checkout+ )+manager = get_plugin_manager_promise(info.context).get()lines, unavailable_variant_pks = fetch_checkout_lines(checkout)- if unavailable_variant_pks:+ if use_legacy_error_flow_for_checkout and unavailable_variant_pks:not_available_variants_ids = {graphene.Node.to_global_id("ProductVariant", pk)for pk in unavailable_variant_pks@@ -309,7 +313,7 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):})- if not is_shipping_required(lines):+ if use_legacy_error_flow_for_checkout and not is_shipping_required(lines):raise ValidationError({"delivery_method": ValidationError(diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.pyindex 8cbe122df9..422a4d8bf0 100644--- a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py+++ b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py@@ -135,9 +135,15 @@ class CheckoutShippingAddressUpdate(AddressMetadataMixin, BaseMutation, I18nMixi"lines__variant__product__product_type"),)+ use_legacy_error_flow_for_checkout = (+ checkout.channel.use_legacy_error_flow_for_checkout+ )++ lines, _ = fetch_checkout_lines(+ checkout,+ )- lines, _ = fetch_checkout_lines(checkout)- if not is_shipping_required(lines):+ if use_legacy_error_flow_for_checkout and not is_shipping_required(lines):raise ValidationError({"shipping_address": ValidationError(@@ -168,7 +174,7 @@ class CheckoutShippingAddressUpdate(AddressMetadataMixin, BaseMutation, I18nMixicheckout.set_country(country, commit=True)# Resolve and process the lines, validating variants quantities- if lines:+ if lines and use_legacy_error_flow_for_checkout:cls.process_checkout_lines(info,lines,diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.pyindex 549b35b511..3c00d80eb5 100644--- a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py+++ b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py@@ -106,10 +106,14 @@ class CheckoutShippingMethodUpdate(BaseMutation):):checkout = get_checkout(cls, info, checkout_id=checkout_id, token=token, id=id)+ use_legacy_error_flow_for_checkout = (+ checkout.channel.use_legacy_error_flow_for_checkout+ )+manager = get_plugin_manager_promise(info.context).get()lines, unavailable_variant_pks = fetch_checkout_lines(checkout)- if unavailable_variant_pks:+ if use_legacy_error_flow_for_checkout and unavailable_variant_pks:not_available_variants_ids = {graphene.Node.to_global_id("ProductVariant", pk)for pk in unavailable_variant_pks@@ -124,7 +128,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):})checkout_info = fetch_checkout_info(checkout, lines, manager)- if not is_shipping_required(lines):+ if use_legacy_error_flow_for_checkout and not is_shipping_required(lines):raise ValidationError({"shipping_method": ValidationError(diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.pyindex 254e12ec43..3d8634ffea 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py@@ -1181,3 +1181,29 @@ def test_checkout_add_voucher_code_invalidates_price(assert data["checkout"]["voucherCode"] == voucher.codeassert data["checkout"]["subtotalPrice"]["gross"]["amount"] == expected_totalassert data["checkout"]["totalPrice"]["gross"]["amount"] == expected_total+++def test_with_active_problems_flow(+ api_client,+ checkout_with_problems,+ voucher,+):+ # given+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ variables = {+ "id": to_global_id_or_none(checkout_with_problems),+ "promoCode": voucher.code,+ }++ # when+ response = api_client.post_graphql(+ MUTATION_CHECKOUT_ADD_PROMO_CODE,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutAddPromoCode"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.pyindex e429eba70f..f5745953f6 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py@@ -556,3 +556,29 @@ def test_checkout_billing_address_update_with_disabled_fields_normalization(assert billing_address.country_area == address_data["countryArea"]assert billing_address.postal_code == address_data["postalCode"]assert billing_address.street_address_1 == address_data["streetAddress1"]+++def test_with_active_problems_flow(+ api_client,+ checkout_with_problems,+ graphql_address_data,+):+ # given+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ new_address = graphql_address_data+ variables = {+ "id": to_global_id_or_none(checkout_with_problems),+ "billingAddress": new_address,+ }++ # when+ response = api_client.post_graphql(+ MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE, variables+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutBillingAddressUpdate"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.pyindex a984784314..7311fa04d2 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py@@ -208,3 +208,22 @@ def test_checkout_customer_attach_user_to_checkout_with_user(variables = {"id": checkout_id, "customerId": customer_id}response = user_api_client.post_graphql(query, variables)assert_no_permission(response)+++def test_with_active_problems_flow(user_api_client, checkout_with_problems):+ # given+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ variables = {"id": to_global_id_or_none(checkout_with_problems), "customerId": None}++ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CUSTOMER_ATTACH,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutCustomerAttach"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.pyindex d785c8a6b5..54747e7bfc 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py@@ -86,3 +86,22 @@ def test_checkout_customer_detach_by_app_without_permissions(assert_no_permission(response)checkout.refresh_from_db()assert checkout.last_change == previous_last_change+++def test_with_active_problems_flow(user_api_client, checkout_with_problems):+ # given+ checkout_with_problems.user = user_api_client.user+ checkout_with_problems.save(update_fields=["user"])+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ variables = {"id": to_global_id_or_none(checkout_with_problems)}++ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CUSTOMER_DETACH, variables+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutCustomerDetach"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.pyindex 120bb6b033..bab605d811 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py@@ -589,3 +589,29 @@ def test_checkout_delivery_method_update_with_not_valid_address_data()assert checkout.shipping_method is Noneassert checkout.collection_point is None+++def test_with_active_problems_flow(+ api_client,+ checkout_with_problems,+ shipping_method,+):+ # given+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ # when+ response = api_client.post_graphql(+ MUTATION_UPDATE_DELIVERY_METHOD,+ {+ "id": to_global_id_or_none(checkout_with_problems),+ "deliveryMethodId": method_id,+ },+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutDeliveryMethodUpdate"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.pyindex fb2face4f1..58f1dad8ec 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py@@ -56,3 +56,25 @@ def test_checkout_email_update_validation(user_api_client, checkout_with_item):checkout_errors = content["data"]["checkoutEmailUpdate"]["errors"]assert checkout_errors[0]["code"] == CheckoutErrorCode.REQUIRED.nameassert checkout_with_item.last_change == previous_last_change+++def test_with_active_problems_flow(api_client, checkout_with_problems):+ # given+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ variables = {+ "id": to_global_id_or_none(checkout_with_problems),+ "email": "[email protected]",+ }++ # when+ response = api_client.post_graphql(+ CHECKOUT_EMAIL_UPDATE_MUTATION,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutEmailUpdate"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.pyindex d2d2b87a0f..c02660be27 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py@@ -39,3 +39,25 @@ def test_checkout_update_language_code(checkout.refresh_from_db()assert checkout.language_code == language_code.lower()assert checkout.last_change != previous_last_change+++def test_with_active_problems_flow(api_client, checkout_with_problems):+ # given+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ variables = {+ "id": to_global_id_or_none(checkout_with_problems),+ "languageCode": "PL",+ }++ # when+ response = api_client.post_graphql(+ MUTATION_CHECKOUT_UPDATE_LANGUAGE_CODE,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutLanguageCodeUpdate"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.pyindex 291a954201..671e8fc112 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py@@ -138,3 +138,36 @@ def test_checkout_line_delete_remove_shipping_if_removed_product_with_shipping(checkout.refresh_from_db()assert checkout.lines.count() == 1assert not checkout.shipping_method+++def test_with_active_problems_flow(+ api_client, checkout_with_problems, product_with_single_variant+):+ # given+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ variant = product_with_single_variant.variants.first()++ checkout_info = fetch_checkout_info(+ checkout_with_problems, [], get_plugins_manager()+ )+ add_variant_to_checkout(checkout_info, variant, 1)++ line = checkout_info.checkout.lines.last()++ variables = {+ "id": to_global_id_or_none(checkout_with_problems),+ "lineId": to_global_id_or_none(line),+ }++ # when+ response = api_client.post_graphql(+ MUTATION_CHECKOUT_LINE_DELETE,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutLineDelete"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.pyindex fda38c3938..f883895caf 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py@@ -1038,3 +1038,29 @@ def test_checkout_lines_invalid_variant_id(user_api_client, checkout, stock):)assert data["errors"][0]["message"] == error_msgassert data["errors"][0]["field"] == "variantId"+++def test_with_active_problems_flow(+ api_client, checkout_with_problems, product_with_single_variant+):+ # given+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ variant = product_with_single_variant.variants.first()++ variables = {+ "id": to_global_id_or_none(checkout_with_problems),+ "lines": [{"variantId": to_global_id_or_none(variant), "quantity": 1}],+ }++ # when+ response = api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_ADD,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutLinesAdd"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.pyindex efa1226ace..0fe50c1ab5 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py@@ -115,3 +115,28 @@ def tests_checkout_lines_delete_invalid_lines_ids(user_api_client, checkout_witherrors = content["errors"][0]assert errors["extensions"]["exception"]["code"] == "GraphQLError"assert checkout.last_change == previous_last_change+++def test_with_active_problems_flow(api_client, checkout_with_problems):+ # given+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ line = checkout_with_problems.lines.first()+ first_line_id = to_global_id_or_none(line)++ variables = {+ "id": to_global_id_or_none(checkout_with_problems),+ "linesIds": [first_line_id],+ }++ # when+ response = api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_DELETE,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutLinesDelete"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.pyindex 3882831629..6eae750c1a 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py@@ -1131,3 +1131,34 @@ def test_checkout_lines_update_remove_shipping_if_removed_product_with_shipping(checkout.refresh_from_db()assert checkout.lines.count() == 1assert not checkout.shipping_method+++def test_with_active_problems_flow(+ api_client, checkout_with_problems, product_with_single_variant+):+ # given+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ variant = product_with_single_variant.variants.first()++ checkout_info = fetch_checkout_info(+ checkout_with_problems, [], get_plugins_manager()+ )+ add_variant_to_checkout(checkout_info, variant, 1)++ variables = {+ "id": to_global_id_or_none(checkout_with_problems),+ "lines": [{"variantId": to_global_id_or_none(variant), "quantity": 3}],+ }++ # when+ response = api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_UPDATE,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutLinesUpdate"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.pyindex 23eb4173c9..2379ffbee5 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py@@ -295,3 +295,36 @@ def test_checkout_remove_voucher_code_invalidates_price(assert not data["errors"]assert data["checkout"]["subtotalPrice"]["gross"]["amount"] == subtotal.amountassert data["checkout"]["totalPrice"]["gross"]["amount"] == expected_total+++def test_with_active_problems_flow(+ api_client,+ checkout_with_problems,+ voucher,+):+ # given+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ checkout_with_problems.voucher_code = voucher.code+ checkout_with_problems.save(+ update_fields=[+ "voucher_code",+ ]+ )++ variables = {+ "id": to_global_id_or_none(checkout_with_problems),+ "promoCode": voucher.code,+ }++ # when+ response = api_client.post_graphql(+ MUTATION_CHECKOUT_REMOVE_PROMO_CODE,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutRemovePromoCode"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.pyindex 63b4da4a21..1cbbee900b 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py@@ -952,3 +952,29 @@ def test_checkout_shipping_address_update_with_not_applicable_voucher(assert checkout_with_item.shipping_address.country == new_address["country"]assert checkout_with_item.voucher_code is None+++def test_with_active_problems_flow(+ api_client,+ checkout_with_problems,+ graphql_address_data,+):+ # given+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ new_address = graphql_address_data+ variables = {+ "id": to_global_id_or_none(checkout_with_problems),+ "shippingAddress": new_address,+ }++ # when+ response = api_client.post_graphql(+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutShippingAddressUpdate"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.pyindex cdcf8fa834..fc14c1fc20 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py@@ -456,3 +456,29 @@ def test_checkout_update_shipping_method_with_digital(# Ensure the shipping method was unchangedcheckout.refresh_from_db(fields=["shipping_method"])assert checkout.shipping_method is None+++def test_with_active_problems_flow(+ api_client,+ checkout_with_problems,+ shipping_method,+):+ # given+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ # when+ response = api_client.post_graphql(+ MUTATION_UPDATE_SHIPPING_METHOD,+ {+ "id": to_global_id_or_none(checkout_with_problems),+ "shippingMethodId": method_id,+ },+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutShippingMethodUpdate"]["errors"]diff --git a/saleor/graphql/checkout/tests/test_checkout_line_problems.py b/saleor/graphql/checkout/tests/test_checkout_line_problems.pynew file mode 100644index 0000000000..e4625cf2cf--- /dev/null+++ b/saleor/graphql/checkout/tests/test_checkout_line_problems.py@@ -0,0 +1,485 @@+import datetime++import pytz++from ....product.models import ProductChannelListing, ProductVariantChannelListing+from ...core.utils import to_global_id_or_none+from ...tests.utils import get_graphql_content++QUERY_CHECKOUT_WITH_PROBLEMS = """+query checkout($id: ID) {+ checkout(id: $id){+ id+ problems{+ __typename+ ... on CheckoutLineProblemInsufficientStock{+ availableQuantity+ variant{+ id+ }+ line{+ id+ }+ }+ ... on CheckoutLineProblemVariantNotAvailable{+ line{+ id+ }+ }+ }+ lines{+ id+ problems{+ __typename+ ... on CheckoutLineProblemInsufficientStock{+ availableQuantity+ variant{+ id+ }+ line{+ id+ }+ }+ ... on CheckoutLineProblemVariantNotAvailable{+ line{+ id+ }+ }+ }+ }+ }+}+"""+++def test_line_without_any_problem(api_client, checkout_with_items_and_shipping):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_id = to_global_id_or_none(checkout)+ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert content["data"]["checkout"]["problems"] == []+ for line_data in content["data"]["checkout"]["lines"]:+ assert line_data["problems"] == []+++def test_line_variant_without_stock(api_client, checkout_with_items_and_shipping):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_id = to_global_id_or_none(checkout)++ checkout_line = checkout.lines.first()+ checkout_line.variant.stocks.all().delete()+ checkout_line_id = to_global_id_or_none(checkout_line)++ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemInsufficientStock"+ )+ assert content["data"]["checkout"]["problems"][0]["availableQuantity"] == 0+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)+ assert content["data"]["checkout"]["problems"][0]["variant"][+ "id"+ ] == to_global_id_or_none(checkout_line.variant)++ line_without_stock = [+ line+ for line in content["data"]["checkout"]["lines"]+ if line["id"] == checkout_line_id+ ][0]+ assert len(line_without_stock["problems"]) == 1+ assert (+ line_without_stock["problems"][0]["__typename"]+ == "CheckoutLineProblemInsufficientStock"+ )+ assert line_without_stock["problems"][0]["availableQuantity"] == 0+ assert line_without_stock["problems"][0]["line"]["id"] == checkout_line_id+ assert line_without_stock["problems"][0]["variant"]["id"] == to_global_id_or_none(+ checkout_line.variant+ )+++def test_line_variant_with_insufficient_stock(+ api_client, checkout_with_items_and_shipping+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_id = to_global_id_or_none(checkout)++ checkout_line = checkout.lines.first()+ stocks = checkout_line.variant.stocks.all()+ stocks.update(quantity=0)+ stock = stocks.first()+ stock.quantity = checkout_line.quantity - 1+ stock.save(update_fields=["quantity"])+ checkout_line_id = to_global_id_or_none(checkout_line)++ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemInsufficientStock"+ )+ assert content["data"]["checkout"]["problems"][0]["availableQuantity"] == 0+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)+ assert content["data"]["checkout"]["problems"][0]["variant"][+ "id"+ ] == to_global_id_or_none(checkout_line.variant)++ line_without_stock = [+ line+ for line in content["data"]["checkout"]["lines"]+ if line["id"] == checkout_line_id+ ][0]+ assert len(line_without_stock["problems"]) == 1+ assert (+ line_without_stock["problems"][0]["__typename"]+ == "CheckoutLineProblemInsufficientStock"+ )+ assert line_without_stock["problems"][0]["availableQuantity"] == 0+ assert line_without_stock["problems"][0]["line"]["id"] == checkout_line_id+ assert line_without_stock["problems"][0]["variant"]["id"] == to_global_id_or_none(+ checkout_line.variant+ )+++def test_line_variant_without_tracking_inventory(+ api_client, checkout_with_items_and_shipping+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_id = to_global_id_or_none(checkout)++ checkout_line = checkout.lines.first()+ stocks = checkout_line.variant.stocks.all()+ stocks.update(quantity=0)+ stock = stocks.first()+ stock.quantity = checkout_line.quantity - 1+ stock.save(update_fields=["quantity"])+ checkout_line.variant.track_inventory = False+ checkout_line.variant.save(update_fields=["track_inventory"])++ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)++ assert content["data"]["checkout"]["id"] == checkout_id+ assert content["data"]["checkout"]["problems"] == []+ for line_data in content["data"]["checkout"]["lines"]:+ assert line_data["problems"] == []+++def test_lines_with_same_variant(api_client, checkout_with_items_and_shipping):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_id = to_global_id_or_none(checkout)++ checkout_line = checkout.lines.first()++ stocks = checkout_line.variant.stocks.all()+ stocks.update(quantity=0)+ stock = stocks.first()+ stock.quantity = checkout_line.quantity - 1+ stock.save(update_fields=["quantity"])+ available_quantity = stock.quantity++ second_checkout_line = checkout_line+ second_checkout_line.pk = None+ second_checkout_line.save()+ second_checkout_line_id = to_global_id_or_none(second_checkout_line)+ checkout_line_id = to_global_id_or_none(checkout_line)++ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 2+ problems = content["data"]["checkout"]["problems"]+ assert all(+ [problem["availableQuantity"] == available_quantity for problem in problems]+ )+ problem_line_ids = [problem["line"]["id"] for problem in problems]+ problem_variant_ids = [problem["variant"]["id"] for problem in problems]+ assert to_global_id_or_none(checkout_line) in problem_line_ids+ assert to_global_id_or_none(second_checkout_line) in problem_line_ids+ assert to_global_id_or_none(checkout_line.variant) in problem_variant_ids++ first_line_without_stock = [+ line+ for line in content["data"]["checkout"]["lines"]+ if line["id"] == checkout_line_id+ ][0]+ assert len(first_line_without_stock["problems"]) == 1+ assert (+ first_line_without_stock["problems"][0]["__typename"]+ == "CheckoutLineProblemInsufficientStock"+ )+ assert (+ first_line_without_stock["problems"][0]["availableQuantity"]+ == available_quantity+ )++ second_line_without_stock = [+ line+ for line in content["data"]["checkout"]["lines"]+ if line["id"] == second_checkout_line_id+ ][0]+ assert len(second_line_without_stock["problems"]) == 1+ assert (+ second_line_without_stock["problems"][0]["__typename"]+ == "CheckoutLineProblemInsufficientStock"+ )+ assert (+ second_line_without_stock["problems"][0]["availableQuantity"]+ == available_quantity+ )+++def test_product_is_not_published(checkout_with_items_and_shipping, api_client):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_line = checkout.lines.first()++ product = checkout_line.variant.product+ product.channel_listings.update(is_published=False)++ checkout_line_id = to_global_id_or_none(checkout_line)++ checkout_id = to_global_id_or_none(checkout)+ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)++ line_without_stock = [+ line+ for line in content["data"]["checkout"]["lines"]+ if line["id"] == checkout_line_id+ ][0]+ assert len(line_without_stock["problems"]) == 1+ assert (+ line_without_stock["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert line_without_stock["problems"][0]["line"]["id"] == checkout_line_id+++def test_product_doesnt_have_channel_listing(+ checkout_with_items_and_shipping, api_client+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_line = checkout.lines.first()++ available_at = datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=5)+ product = checkout_line.variant.product+ product.channel_listings.update(available_for_purchase_at=available_at)++ checkout_line_id = to_global_id_or_none(checkout_line)++ checkout_id = to_global_id_or_none(checkout)+ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)++ line_without_stock = [+ line+ for line in content["data"]["checkout"]["lines"]+ if line["id"] == checkout_line_id+ ][0]+ assert len(line_without_stock["problems"]) == 1+ assert (+ line_without_stock["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert line_without_stock["problems"][0]["line"]["id"] == checkout_line_id+++def test_product_is_not_available_to_purchase(+ checkout_with_items_and_shipping, api_client+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_line = checkout.lines.first()++ product = checkout_line.variant.product+ ProductChannelListing.objects.filter(product=product).delete()++ checkout_line_id = to_global_id_or_none(checkout_line)++ checkout_id = to_global_id_or_none(checkout)+ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)++ line_without_stock = [+ line+ for line in content["data"]["checkout"]["lines"]+ if line["id"] == checkout_line_id+ ][0]+ assert len(line_without_stock["problems"]) == 1+ assert (+ line_without_stock["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert line_without_stock["problems"][0]["line"]["id"] == checkout_line_id+++def test_product_variant_doesnt_have_channel_listing(+ checkout_with_items_and_shipping, api_client+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_line = checkout.lines.first()++ variant = checkout_line.variant+ ProductVariantChannelListing.objects.filter(variant=variant).delete()++ checkout_line_id = to_global_id_or_none(checkout_line)++ checkout_id = to_global_id_or_none(checkout)+ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)++ line_without_stock = [+ line+ for line in content["data"]["checkout"]["lines"]+ if line["id"] == checkout_line_id+ ][0]+ assert len(line_without_stock["problems"]) == 1+ assert (+ line_without_stock["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert line_without_stock["problems"][0]["line"]["id"] == checkout_line_id+++def test_product_variant_channel_listing_doesnt_have_price_amount(+ checkout_with_items_and_shipping, api_client+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_line = checkout.lines.first()++ variant = checkout_line.variant+ ProductVariantChannelListing.objects.filter(variant=variant).update(+ price_amount=None+ )++ checkout_line_id = to_global_id_or_none(checkout_line)++ checkout_id = to_global_id_or_none(checkout)+ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)++ line_without_stock = [+ line+ for line in content["data"]["checkout"]["lines"]+ if line["id"] == checkout_line_id+ ][0]+ assert len(line_without_stock["problems"]) == 1+ assert (+ line_without_stock["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert line_without_stock["problems"][0]["line"]["id"] == checkout_line_iddiff --git a/saleor/graphql/checkout/tests/test_checkout_problems.py b/saleor/graphql/checkout/tests/test_checkout_problems.pynew file mode 100644index 0000000000..14c19d52a9--- /dev/null+++ b/saleor/graphql/checkout/tests/test_checkout_problems.py@@ -0,0 +1,425 @@+import datetime+from datetime import timedelta++import pytz+from django.utils import timezone++from ....product.models import ProductChannelListing, ProductVariantChannelListing+from ....warehouse.models import Allocation, Reservation+from ...core.utils import to_global_id_or_none+from ...tests.utils import get_graphql_content++QUERY_CHECKOUT_WITH_PROBLEMS = """+query checkout($id: ID) {+ checkout(id: $id){+ id+ problems{+ __typename+ ... on CheckoutLineProblemInsufficientStock{+ availableQuantity+ variant{+ id+ }+ line{+ id+ }+ }+ ... on CheckoutLineProblemVariantNotAvailable{+ line{+ id+ }+ }+ }+ }+}+"""+++def test_checkout_without_problems(api_client, checkout_with_items_and_shipping):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_id = to_global_id_or_none(checkout)+ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert content["data"]["checkout"]["problems"] == []+++def test_checkout_without_shipping(api_client, checkout_with_items):+ # given+ checkout = checkout_with_items+ checkout_id = to_global_id_or_none(checkout)++ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert content["data"]["checkout"]["problems"] == []+++def test_checkout_with_out_of_stock_when_stocks_dont_exist(+ api_client, checkout_with_items_and_shipping+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_id = to_global_id_or_none(checkout)++ checkout_line = checkout.lines.first()+ checkout_line.variant.stocks.all().delete()++ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemInsufficientStock"+ )+ assert content["data"]["checkout"]["problems"][0]["availableQuantity"] == 0+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)+ assert content["data"]["checkout"]["problems"][0]["variant"][+ "id"+ ] == to_global_id_or_none(checkout_line.variant)+++def test_checkout_problem_out_of_stock_without_available_quantity(+ api_client, checkout_with_items_and_shipping+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_id = to_global_id_or_none(checkout)++ checkout_line = checkout.lines.first()+ stocks = checkout_line.variant.stocks.all()+ stocks.update(quantity=0)+ stock = stocks.first()+ stock.quantity = checkout_line.quantity - 1+ stock.save(update_fields=["quantity"])++ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemInsufficientStock"+ )+ assert content["data"]["checkout"]["problems"][0]["availableQuantity"] == 0+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)+ assert content["data"]["checkout"]["problems"][0]["variant"][+ "id"+ ] == to_global_id_or_none(checkout_line.variant)+++def test_checkout_problems_with_reservation(api_client, checkout_with_items):+ # given+ checkout = checkout_with_items+ checkout_id = to_global_id_or_none(checkout)++ checkout_line = checkout.lines.first()+ stocks = checkout_line.variant.stocks.all()+ stocks.update(quantity=0)+ stock = stocks.first()+ stock.quantity = checkout_line.quantity+ stock.save(update_fields=["quantity"])++ reserved_until = timezone.now() + timedelta(minutes=5)+ Reservation.objects.create(+ checkout_line=checkout_line,+ stock=stock,+ quantity_reserved=checkout_line.quantity,+ reserved_until=reserved_until,+ )++ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert content["data"]["checkout"]["problems"] == []+++def test_checkout_with_out_of_stock_with_allocations_and_not_enough_items(+ api_client, checkout_with_items_and_shipping, order_line+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_id = to_global_id_or_none(checkout)++ line_quantity = 5+ checkout_line = checkout.lines.first()+ checkout_line.quantity = line_quantity+ checkout_line.save(update_fields=["quantity"])++ free_quantity = 2+ stocks = checkout_line.variant.stocks.all()+ stocks.update(quantity=0)+ stock = stocks.first()+ stock.quantity = line_quantity + free_quantity+ stock.save(update_fields=["quantity"])++ order_line.variant = checkout_line.variant+ order_line.save(update_fields=["variant"])+ Allocation.objects.create(+ order_line=order_line, stock=stock, quantity_allocated=line_quantity+ )++ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemInsufficientStock"+ )+ assert (+ content["data"]["checkout"]["problems"][0]["availableQuantity"] == free_quantity+ )+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)+ assert content["data"]["checkout"]["problems"][0]["variant"][+ "id"+ ] == to_global_id_or_none(checkout_line.variant)+++def test_checkout_out_of_stock_without_tracking_inventory(+ api_client, checkout_with_items_and_shipping+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_id = to_global_id_or_none(checkout)++ checkout_line = checkout.lines.first()+ checkout_line.variant.stocks.all().delete()+ checkout_line.variant.track_inventory = False+ checkout_line.variant.save(update_fields=["track_inventory"])++ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 0+++def test_checkout_with_multiple_same_variant_and_out_of_stock(+ api_client, checkout_with_items_and_shipping+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_id = to_global_id_or_none(checkout)++ checkout_line = checkout.lines.first()+ stocks = checkout_line.variant.stocks.all()+ stocks.update(quantity=0)+ stock = stocks.first()+ stock.quantity = checkout_line.quantity+ stock.save(update_fields=["quantity"])+ available_quantity = stock.quantity++ second_checkout_line = checkout_line+ second_checkout_line.quantity = 1+ second_checkout_line.pk = None+ second_checkout_line.save()++ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 2+ problems = content["data"]["checkout"]["problems"]+ assert all(+ [problem["availableQuantity"] == available_quantity for problem in problems]+ )+ problem_line_ids = [problem["line"]["id"] for problem in problems]+ problem_variant_ids = [problem["variant"]["id"] for problem in problems]+ assert to_global_id_or_none(checkout_line) in problem_line_ids+ assert to_global_id_or_none(second_checkout_line) in problem_line_ids+ assert to_global_id_or_none(checkout_line.variant) in problem_variant_ids+++def test_checkout_problems_when_product_is_not_published(+ checkout_with_items_and_shipping, api_client+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_line = checkout.lines.first()++ product = checkout_line.variant.product+ product.channel_listings.update(is_published=False)++ checkout_id = to_global_id_or_none(checkout)+ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)+++def test_checkout_problems_when_product_doesnt_have_channel_listing(+ checkout_with_items_and_shipping, api_client+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_line = checkout.lines.first()++ available_at = datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=5)+ product = checkout_line.variant.product+ product.channel_listings.update(available_for_purchase_at=available_at)++ checkout_id = to_global_id_or_none(checkout)+ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)+++def test_checkout_problems_when_product_is_not_available_to_purchase(+ checkout_with_items_and_shipping, api_client+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_line = checkout.lines.first()++ product = checkout_line.variant.product+ ProductChannelListing.objects.filter(product=product).delete()++ checkout_id = to_global_id_or_none(checkout)+ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)+++def test_checkout_problems_when_product_variant_doesnt_have_channel_listing(+ checkout_with_items_and_shipping, api_client+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_line = checkout.lines.first()++ variant = checkout_line.variant+ ProductVariantChannelListing.objects.filter(variant=variant).delete()++ checkout_id = to_global_id_or_none(checkout)+ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)+++def test_checkout_problems_when_variant_channel_listing_doesnt_have_price_amount(+ checkout_with_items_and_shipping, api_client+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_line = checkout.lines.first()++ variant = checkout_line.variant+ ProductVariantChannelListing.objects.filter(variant=variant).update(+ price_amount=None+ )++ checkout_id = to_global_id_or_none(checkout)+ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert len(content["data"]["checkout"]["problems"]) == 1+ assert (+ content["data"]["checkout"]["problems"][0]["__typename"]+ == "CheckoutLineProblemVariantNotAvailable"+ )+ assert content["data"]["checkout"]["problems"][0]["line"][+ "id"+ ] == to_global_id_or_none(checkout_line)diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex c80e5cf0c3..1cfae81b26 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -3,7 +3,7 @@ from typing import TYPE_CHECKING, Optionalimport graphenefrom promise import Promise-from ...checkout import calculations, models+from ...checkout import calculations, models, problemsfrom ...checkout.base_calculations import (calculate_undiscounted_base_line_total_price,calculate_undiscounted_base_line_unit_price,@@ -25,8 +25,13 @@ from ...webhook.event_types import WebhookEventSyncTypefrom ..account.dataloaders import AddressByIdLoaderfrom ..account.utils import check_is_owner_or_has_one_of_permsfrom ..channel import ChannelContext+from ..channel.dataloaders import ChannelByIdLoaderfrom ..channel.types import Channel-from ..checkout.dataloaders import ChannelByCheckoutLineIDLoader, ChannelByIdLoader+from ..checkout.dataloaders import (+ ChannelByCheckoutLineIDLoader,+ CheckoutLinesProblemsByCheckoutIdLoader,+ CheckoutProblemsByCheckoutIdDataloader,+)from ..core import ResolveInfofrom ..core.connection import CountableConnectionfrom ..core.descriptions import (@@ -36,6 +41,7 @@ from ..core.descriptions import (ADDED_IN_38,ADDED_IN_39,ADDED_IN_313,+ ADDED_IN_315,DEPRECATED_IN_3X_FIELD,PREVIEW_FEATURE,)@@ -103,6 +109,93 @@ def get_dataloaders_for_fetching_checkout_data(return address, lines, checkout_info, manager+class CheckoutLineProblemInsufficientStock(+ BaseObjectType,+):+ available_quantity = graphene.Int(description="Available quantity of a variant.")+ line = graphene.Field(+ "saleor.graphql.checkout.types.CheckoutLine",+ description="The line that has variant with insufficient stock.",+ required=True,+ )+ variant = graphene.Field(+ "saleor.graphql.product.types.ProductVariant",+ description="The variant with insufficient stock.",+ required=True,+ )++ class Meta:+ description = (+ (+ "Indicates insufficient stock for a given checkout line."+ "Placing the order will not be possible until solving this problem."+ )+ + ADDED_IN_315+ + PREVIEW_FEATURE+ )+ doc_category = DOC_CATEGORY_CHECKOUT+++class CheckoutLineProblemVariantNotAvailable(BaseObjectType):+ line = graphene.Field(+ "saleor.graphql.checkout.types.CheckoutLine",+ description="The line that has variant that is not available.",+ required=True,+ )++ class Meta:+ description = (+ (+ "The variant assigned to the checkout line is not available."+ "Placing the order will not be possible until solving this problem."+ )+ + ADDED_IN_315+ + PREVIEW_FEATURE+ )+ doc_category = DOC_CATEGORY_CHECKOUT+++class CheckoutLineProblem(graphene.Union):+ class Meta:+ types = (+ CheckoutLineProblemInsufficientStock,+ CheckoutLineProblemVariantNotAvailable,+ )+ description = (+ "Represents an problem in the checkout line."+ + ADDED_IN_315+ + PREVIEW_FEATURE+ )+ doc_category = DOC_CATEGORY_CHECKOUT++ @classmethod+ def resolve_type(cls, instance: problems.CHECKOUT_PROBLEM_TYPE, info: ResolveInfo):+ if isinstance(instance, problems.CheckoutLineProblemInsufficientStock):+ return CheckoutLineProblemInsufficientStock+ if isinstance(instance, problems.CheckoutLineProblemVariantNotAvailable):+ return CheckoutLineProblemVariantNotAvailable+ return super(CheckoutLineProblem, cls).resolve_type(instance, info)+++class CheckoutProblem(graphene.Union):+ class Meta:+ types = [] + list(CheckoutLineProblem._meta.types)+ description = (+ "Represents an problem in the checkout." + ADDED_IN_315 + PREVIEW_FEATURE+ )+ doc_category = DOC_CATEGORY_CHECKOUT++ @classmethod+ def resolve_type(+ cls, instance: problems.CHECKOUT_LINE_PROBLEM_TYPE, info: ResolveInfo+ ):+ if isinstance(instance, problems.CheckoutLineProblemInsufficientStock):+ return CheckoutLineProblemInsufficientStock+ if isinstance(instance, problems.CheckoutLineProblemVariantNotAvailable):+ return CheckoutLineProblemVariantNotAvailable+ return super(CheckoutProblem, cls).resolve_type(instance, info)++class GatewayConfigLine(BaseObjectType):field = graphene.String(required=True, description="Gateway config key.")value = graphene.String(description="Gateway config value for key.")@@ -181,6 +274,12 @@ class CheckoutLine(ModelObjectType[models.CheckoutLine]):description="Indicates whether the item need to be delivered.",required=True,)+ problems = NonNullList(+ CheckoutLineProblem,+ description="List of problems with the checkout line."+ + ADDED_IN_315+ + PREVIEW_FEATURE,+ )class Meta:description = "Represents an item in the checkout."@@ -354,6 +453,18 @@ class CheckoutLine(ModelObjectType[models.CheckoutLine]):.then(is_shipping_required))+ @staticmethod+ @traced_resolver+ def resolve_problems(root: models.CheckoutLine, info: ResolveInfo):+ problems_dataloader = CheckoutLinesProblemsByCheckoutIdLoader(+ info.context+ ).load(root.checkout_id)++ def get_problem_for_line(problems):+ return problems.get(str(root.pk), [])++ return problems_dataloader.then(get_problem_for_line)+class CheckoutLineCountableConnection(CountableConnection):class Meta:@@ -667,6 +778,13 @@ class Checkout(ModelObjectType[models.Checkout]):],)+ problems = NonNullList(+ CheckoutProblem,+ description=(+ "List of problems with the checkout." + ADDED_IN_315 + PREVIEW_FEATURE+ ),+ )+class Meta:description = "Checkout object."model = models.Checkout@@ -1087,6 +1205,14 @@ class Checkout(ModelObjectType[models.Checkout]):)return Promise.all(dataloaders).then(_calculate_total_balance_for_transactions)+ @staticmethod+ @traced_resolver+ def resolve_problems(root: models.Checkout, info):+ checkout_problems_dataloader = CheckoutProblemsByCheckoutIdDataloader(+ info.context+ )+ return checkout_problems_dataloader.load(root.pk)+class CheckoutCountableConnection(CountableConnection):class Meta:diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex 6d845c44c7..79ee726489 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -38,6 +38,7 @@ from ...core.utils.events import call_eventfrom ...permission.auth_filters import AuthorizationFiltersfrom ...permission.enums import BasePermissionEnumfrom ...permission.utils import (+ all_permissions_required,message_one_of_permissions_required,one_of_permissions_or_auth_filter_required,)@@ -503,7 +504,9 @@ class BaseMutation(graphene.Mutation):return instance@classmethod- def check_permissions(cls, context, permissions=None, **data):+ def check_permissions(+ cls, context, permissions=None, require_all_permissions=False, **data+ ):"""Determine whether user or app has rights to perform this mutation.Default implementation assumes that account is allowed to perform any@@ -515,7 +518,8 @@ class BaseMutation(graphene.Mutation):all_permissions = permissions or cls._meta.permissionsif not all_permissions:return True-+ if require_all_permissions:+ return all_permissions_required(context, all_permissions)return one_of_permissions_or_auth_filter_required(context, all_permissions)@classmethoddiff --git a/saleor/graphql/payment/mutations/payment/checkout_payment_create.py b/saleor/graphql/payment/mutations/payment/checkout_payment_create.pyindex 86bed93ed7..4cb67669cb 100644--- a/saleor/graphql/payment/mutations/payment/checkout_payment_create.py+++ b/saleor/graphql/payment/mutations/payment/checkout_payment_create.py@@ -213,6 +213,10 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):):checkout = get_checkout(cls, info, checkout_id=checkout_id, token=token, id=id)+ use_legacy_error_flow_for_checkout = (+ checkout.channel.use_legacy_error_flow_for_checkout+ )+cls.validate_checkout_email(checkout)gateway = input["gateway"]@@ -222,7 +226,7 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):cls.validate_return_url(input)lines, unavailable_variant_pks = fetch_checkout_lines(checkout)- if unavailable_variant_pks:+ if use_legacy_error_flow_for_checkout and unavailable_variant_pks:not_available_variants_ids = {graphene.Node.to_global_id("ProductVariant", pk)for pk in unavailable_variant_pksdiff --git a/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py b/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.pyindex de95321b63..af32914bca 100644--- a/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py+++ b/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py@@ -776,3 +776,34 @@ def test_checkout_add_payment_run_multiple_times(payments = Payment.objects.filter(checkout=checkout)assert payments.count() == 2assert payments.filter(is_active=True).count() == 1+++def test_with_active_problems_flow(+ api_client,+ checkout_with_problems,+ shipping_method,+):+ # given+ channel = checkout_with_problems.channel+ channel.use_legacy_error_flow_for_checkout = False+ channel.save(update_fields=["use_legacy_error_flow_for_checkout"])++ return_url = "https://www.example.com"+ variables = {+ "id": to_global_id_or_none(checkout_with_problems),+ "input": {+ "gateway": DUMMY_GATEWAY,+ "token": "sample-token",+ "returnUrl": return_url,+ },+ }++ # when+ response = api_client.post_graphql(+ CREATE_PAYMENT_MUTATION,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["checkoutPaymentCreate"]["errors"]diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex fe1b6f159d..320c530544 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -4952,6 +4952,17 @@ type Channel implements Node & ObjectWithMetadata @doc(category: "Channels") {Requires one of the following permissions: MANAGE_CHANNELS, MANAGE_ORDERS."""orderSettings: OrderSettings!++ """+ Channel-specific checkout settings.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.++ Requires one of the following permissions: MANAGE_CHANNELS, MANAGE_CHECKOUTS.+ """+ checkoutSettings: CheckoutSettings!}"""@@ -5441,6 +5452,22 @@ enum TransactionFlowStrategyEnum @doc(category: "Payments") {"""The `Day` scalar type represents number of days by integer value."""scalar Day+"""+Represents the channel-specific checkout settings.++Added in Saleor 3.15.++Note: this API is currently in Feature Preview and can be subject to changes at later point.+"""+type CheckoutSettings {+ """+ Default `true`. Determines if the checkout mutations should use legacy error flow. In legacy flow, all mutations can raise an exception unrelated to the requested action - (e.g. out-of-stock exception when updating checkoutShippingAddress.) If `false`, the errors will be aggregated in `checkout.problems` field. Some of the `problems` can block the finalizing checkout process. The legacy flow will be removed in Saleor 4.0. The flow with `checkout.problems` will be the default one.++ Added in Saleor 3.15.This field will be removed in Saleor 4.0.+ """+ useLegacyErrorFlow: Boolean!+}+"""Represents shipping method postal code rule."""type ShippingMethodPostalCodeRule implements Node @doc(category: "Shipping") {"""The ID of the object."""@@ -10279,6 +10306,15 @@ type Checkout implements Node & ObjectWithMetadata @doc(category: "Checkout") {- CHECKOUT_CALCULATE_TAXES (sync): Optionally triggered when checkout prices are expired."""chargeStatus: CheckoutChargeStatusEnum! @webhookEventsInfo(asyncEvents: [], syncEvents: [CHECKOUT_CALCULATE_TAXES])++ """+ List of problems with the checkout.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ problems: [CheckoutProblem!]}"""@@ -10604,6 +10640,54 @@ type CheckoutLine implements Node & ObjectWithMetadata @doc(category: "Checkout""""Indicates whether the item need to be delivered."""requiresShipping: Boolean!++ """+ List of problems with the checkout line.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ problems: [CheckoutLineProblem!]+}++"""+Represents an problem in the checkout line.++Added in Saleor 3.15.++Note: this API is currently in Feature Preview and can be subject to changes at later point.+"""+union CheckoutLineProblem = CheckoutLineProblemInsufficientStock | CheckoutLineProblemVariantNotAvailable++"""+Indicates insufficient stock for a given checkout line.Placing the order will not be possible until solving this problem.++Added in Saleor 3.15.++Note: this API is currently in Feature Preview and can be subject to changes at later point.+"""+type CheckoutLineProblemInsufficientStock @doc(category: "Checkout") {+ """Available quantity of a variant."""+ availableQuantity: Int++ """The line that has variant with insufficient stock."""+ line: CheckoutLine!++ """The variant with insufficient stock."""+ variant: ProductVariant!+}++"""+The variant assigned to the checkout line is not available.Placing the order will not be possible until solving this problem.++Added in Saleor 3.15.++Note: this API is currently in Feature Preview and can be subject to changes at later point.+"""+type CheckoutLineProblemVariantNotAvailable @doc(category: "Checkout") {+ """The line that has variant that is not available."""+ line: CheckoutLine!}"""@@ -12281,6 +12365,15 @@ enum CheckoutChargeStatusEnum @doc(category: "Checkout") {OVERCHARGED}+"""+Represents an problem in the checkout.++Added in Saleor 3.15.++Note: this API is currently in Feature Preview and can be subject to changes at later point.+"""+union CheckoutProblem = CheckoutLineProblemInsufficientStock | CheckoutLineProblemVariantNotAvailable+type CheckoutCountableConnection @doc(category: "Checkout") {"""Pagination data for this connection."""pageInfo: PageInfo!@@ -17417,7 +17510,7 @@ type Mutation {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.+ Requires one of the following permissions when updating only `orderSettings` field: MANAGE_CHANNELS, MANAGE_ORDERS.Requires one of the following permissions when updating only `checkoutSettings` field: MANAGE_CHANNELS, MANAGE_CHECKOUTS.Triggers the following webhook events:- CHANNEL_UPDATED (async): A channel was updated.@@ -26749,6 +26842,15 @@ input ChannelCreateInput @doc(category: "Channels") {"""privateMetadata: [MetadataInput!]+ """+ The channel checkout settings++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ checkoutSettings: CheckoutSettingsInput+"""Name of the channel."""name: String!@@ -26832,11 +26934,22 @@ input OrderSettingsInput @doc(category: "Orders") {allowUnpaidOrders: Boolean}+input CheckoutSettingsInput @doc(category: "Checkout") {+ """+ Default `true`. Determines if the checkout mutations should use legacy error flow. In legacy flow, all mutations can raise an exception unrelated to the requested action - (e.g. out-of-stock exception when updating checkoutShippingAddress.) If `false`, the errors will be aggregated in `checkout.problems` field. Some of the `problems` can block the finalizing checkout process. The legacy flow will be removed in Saleor 4.0. The flow with `checkout.problems` will be the default one.++ Added in Saleor 3.15.++ DEPRECATED: this field will be removed in Saleor 4.0.+ """+ useLegacyErrorFlow: Boolean+}+"""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.+Requires one of the following permissions when updating only `orderSettings` field: MANAGE_CHANNELS, MANAGE_ORDERS.Requires one of the following permissions when updating only `checkoutSettings` field: MANAGE_CHANNELS, MANAGE_CHECKOUTS.Triggers the following webhook events:- CHANNEL_UPDATED (async): A channel was updated.@@ -26890,6 +27003,15 @@ input ChannelUpdateInput @doc(category: "Channels") {"""privateMetadata: [MetadataInput!]+ """+ The channel checkout settings++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ checkoutSettings: CheckoutSettingsInput+"""Name of the channel."""name: Stringdiff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.pyindex fbbbbd82d1..a26c0e8356 100644--- a/saleor/graphql/warehouse/dataloaders.py+++ b/saleor/graphql/warehouse/dataloaders.py@@ -421,10 +421,12 @@ class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(channel_slug: Optional[str],variant_ids: Iterable[int],) -> Iterable[Tuple[int, List[Stock]]]:+ # convert to set to not return the same stocks for the same variant twice+ variant_ids_set = set(variant_ids)stocks = (Stock.objects.all().using(self.database_connection_name)- .filter(product_variant_id__in=variant_ids)+ .filter(product_variant_id__in=variant_ids_set))if country_code:stocks = stocks.filter(@@ -457,7 +459,7 @@ class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(variant_id,stocks_by_variant_id_map[variant_id],)- for variant_id in variant_ids+ for variant_id in variant_ids_set]diff --git a/saleor/permission/tests/__init__.py b/saleor/permission/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/permission/tests/test_all_permissions_required.py b/saleor/permission/tests/test_all_permissions_required.pynew file mode 100644index 0000000000..57420b0b3f--- /dev/null+++ b/saleor/permission/tests/test_all_permissions_required.py@@ -0,0 +1,207 @@+import pytest+from mock import Mock++from ..auth_filters import AuthorizationFilters+from ..enums import CheckoutPermissions+from ..utils import one_of_permissions_or_auth_filter_required+++ "permissions, expected_result",+ [+ (None, True),+ ([], True),+ ([CheckoutPermissions.MANAGE_CHECKOUTS], True),+ ([CheckoutPermissions.MANAGE_TAXES], False),+ (+ [CheckoutPermissions.MANAGE_CHECKOUTS, CheckoutPermissions.MANAGE_TAXES],+ True,+ ),+ ([AuthorizationFilters.AUTHENTICATED_APP], True),+ ([AuthorizationFilters.AUTHENTICATED_USER], False),+ (+ [+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_USER,+ ],+ True,+ ),+ ([AuthorizationFilters.AUTHENTICATED_STAFF_USER], False),+ (+ [+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ True,+ ),+ (+ [+ AuthorizationFilters.AUTHENTICATED_USER,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ False,+ ),+ (+ [CheckoutPermissions.MANAGE_TAXES, AuthorizationFilters.AUTHENTICATED_APP],+ True,+ ),+ (+ [+ CheckoutPermissions.MANAGE_TAXES,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ False,+ ),+ (+ [CheckoutPermissions.MANAGE_TAXES, AuthorizationFilters.AUTHENTICATED_USER],+ False,+ ),+ ],+)+def test_permissions_for_app(+ permissions, expected_result, app, permission_manage_checkouts+):+ # given+ app.permissions.set([permission_manage_checkouts])+ context = Mock()+ context.app = app+ context.user = None++ # when+ result = one_of_permissions_or_auth_filter_required(context, permissions)++ # then+ assert result == expected_result+++ "permissions, expected_result",+ [+ (None, True),+ ([], True),+ ([CheckoutPermissions.MANAGE_CHECKOUTS], True),+ ([CheckoutPermissions.MANAGE_TAXES], False),+ (+ [CheckoutPermissions.MANAGE_CHECKOUTS, CheckoutPermissions.MANAGE_TAXES],+ True,+ ),+ ([AuthorizationFilters.AUTHENTICATED_APP], False),+ ([AuthorizationFilters.AUTHENTICATED_USER], True),+ (+ [+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_USER,+ ],+ True,+ ),+ ([AuthorizationFilters.AUTHENTICATED_STAFF_USER], True),+ (+ [+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ True,+ ),+ (+ [+ AuthorizationFilters.AUTHENTICATED_USER,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ True,+ ),+ (+ [CheckoutPermissions.MANAGE_TAXES, AuthorizationFilters.AUTHENTICATED_APP],+ False,+ ),+ (+ [+ CheckoutPermissions.MANAGE_TAXES,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ True,+ ),+ (+ [CheckoutPermissions.MANAGE_TAXES, AuthorizationFilters.AUTHENTICATED_USER],+ True,+ ),+ ],+)+def test_permissions_for_staff_user(+ permissions, expected_result, staff_user, permission_manage_checkouts+):+ # given+ staff_user.user_permissions.set([permission_manage_checkouts])+ context = Mock()+ context.app = None+ context.user = staff_user++ # when+ result = one_of_permissions_or_auth_filter_required(context, permissions)++ # then+ assert result is expected_result+++ "permissions, expected_result",+ [+ (None, True),+ ([], True),+ ([CheckoutPermissions.MANAGE_CHECKOUTS], False),+ ([CheckoutPermissions.MANAGE_TAXES], False),+ (+ [CheckoutPermissions.MANAGE_CHECKOUTS, CheckoutPermissions.MANAGE_TAXES],+ False,+ ),+ ([AuthorizationFilters.AUTHENTICATED_APP], False),+ ([AuthorizationFilters.AUTHENTICATED_USER], True),+ (+ [+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_USER,+ ],+ True,+ ),+ ([AuthorizationFilters.AUTHENTICATED_STAFF_USER], False),+ (+ [+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ False,+ ),+ (+ [+ AuthorizationFilters.AUTHENTICATED_USER,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ True,+ ),+ (+ [CheckoutPermissions.MANAGE_TAXES, AuthorizationFilters.AUTHENTICATED_APP],+ False,+ ),+ (+ [+ CheckoutPermissions.MANAGE_TAXES,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ False,+ ),+ (+ [CheckoutPermissions.MANAGE_TAXES, AuthorizationFilters.AUTHENTICATED_USER],+ True,+ ),+ ],+)+def test_permissions_for_customer(permissions, expected_result, customer_user):+ # given+ context = Mock()+ context.app = None+ context.user = customer_user++ # when+ result = one_of_permissions_or_auth_filter_required(context, permissions)++ # then+ assert result is expected_resultdiff --git a/saleor/permission/tests/test_one_of_permissions_or_auth_filter_required.py b/saleor/permission/tests/test_one_of_permissions_or_auth_filter_required.pynew file mode 100644index 0000000000..6941e5be43--- /dev/null+++ b/saleor/permission/tests/test_one_of_permissions_or_auth_filter_required.py@@ -0,0 +1,287 @@+import pytest+from mock import Mock++from ..auth_filters import AuthorizationFilters+from ..enums import CheckoutPermissions, OrderPermissions+from ..utils import all_permissions_required+++ "permissions, expected_result",+ [+ (None, True),+ ([], True),+ ([CheckoutPermissions.MANAGE_CHECKOUTS], True),+ ([CheckoutPermissions.MANAGE_TAXES], False),+ (+ [CheckoutPermissions.MANAGE_CHECKOUTS, CheckoutPermissions.MANAGE_TAXES],+ False,+ ),+ ([AuthorizationFilters.AUTHENTICATED_APP], True),+ ([AuthorizationFilters.AUTHENTICATED_USER], False),+ (+ [+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_USER,+ ],+ True,+ ),+ ([AuthorizationFilters.AUTHENTICATED_STAFF_USER], False),+ (+ [+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ True,+ ),+ (+ [+ AuthorizationFilters.AUTHENTICATED_USER,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ False,+ ),+ (+ [CheckoutPermissions.MANAGE_TAXES, AuthorizationFilters.AUTHENTICATED_APP],+ False,+ ),+ (+ [+ CheckoutPermissions.MANAGE_TAXES,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ False,+ ),+ (+ [CheckoutPermissions.MANAGE_TAXES, AuthorizationFilters.AUTHENTICATED_USER],+ False,+ ),+ ([CheckoutPermissions.MANAGE_CHECKOUTS, OrderPermissions.MANAGE_ORDERS], True),+ (+ [+ CheckoutPermissions.MANAGE_CHECKOUTS,+ OrderPermissions.MANAGE_ORDERS,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ AuthorizationFilters.AUTHENTICATED_APP,+ ],+ True,+ ),+ (+ [+ CheckoutPermissions.MANAGE_CHECKOUTS,+ OrderPermissions.MANAGE_ORDERS,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ False,+ ),+ ],+)+def test_permissions_for_app(+ permissions,+ expected_result,+ app,+ permission_manage_checkouts,+ permission_manage_orders,+):+ # given+ app.permissions.set([permission_manage_checkouts, permission_manage_orders])+ context = Mock()+ context.app = app+ context.user = None++ # when+ result = all_permissions_required(context, permissions)++ # then+ assert result == expected_result+++ "permissions, expected_result",+ [+ (None, True),+ ([], True),+ ([CheckoutPermissions.MANAGE_CHECKOUTS], True),+ ([CheckoutPermissions.MANAGE_TAXES], False),+ (+ [CheckoutPermissions.MANAGE_CHECKOUTS, CheckoutPermissions.MANAGE_TAXES],+ False,+ ),+ ([AuthorizationFilters.AUTHENTICATED_APP], False),+ ([AuthorizationFilters.AUTHENTICATED_USER], True),+ (+ [+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_USER,+ ],+ True,+ ),+ ([AuthorizationFilters.AUTHENTICATED_STAFF_USER], True),+ (+ [+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ True,+ ),+ (+ [+ AuthorizationFilters.AUTHENTICATED_USER,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ True,+ ),+ (+ [CheckoutPermissions.MANAGE_TAXES, AuthorizationFilters.AUTHENTICATED_APP],+ False,+ ),+ (+ [+ CheckoutPermissions.MANAGE_TAXES,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ False,+ ),+ (+ [CheckoutPermissions.MANAGE_TAXES, AuthorizationFilters.AUTHENTICATED_USER],+ False,+ ),+ ([CheckoutPermissions.MANAGE_CHECKOUTS, OrderPermissions.MANAGE_ORDERS], True),+ (+ [+ CheckoutPermissions.MANAGE_CHECKOUTS,+ OrderPermissions.MANAGE_ORDERS,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ AuthorizationFilters.AUTHENTICATED_APP,+ ],+ True,+ ),+ (+ [+ CheckoutPermissions.MANAGE_CHECKOUTS,+ OrderPermissions.MANAGE_ORDERS,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ True,+ ),+ (+ [+ CheckoutPermissions.MANAGE_CHECKOUTS,+ OrderPermissions.MANAGE_ORDERS,+ AuthorizationFilters.AUTHENTICATED_USER,+ ],+ True,+ ),+ ],+)+def test_permissions_for_staff_user(+ permissions,+ expected_result,+ staff_user,+ permission_manage_checkouts,+ permission_manage_orders,+):+ # given+ staff_user.user_permissions.set(+ [permission_manage_checkouts, permission_manage_orders]+ )+ context = Mock()+ context.app = None+ context.user = staff_user++ # when+ result = all_permissions_required(context, permissions)++ # then+ assert result is expected_result+++ "permissions, expected_result",+ [+ (None, True),+ ([], True),+ ([CheckoutPermissions.MANAGE_CHECKOUTS], False),+ ([CheckoutPermissions.MANAGE_TAXES], False),+ (+ [CheckoutPermissions.MANAGE_CHECKOUTS, CheckoutPermissions.MANAGE_TAXES],+ False,+ ),+ ([AuthorizationFilters.AUTHENTICATED_APP], False),+ ([AuthorizationFilters.AUTHENTICATED_USER], True),+ (+ [+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_USER,+ ],+ True,+ ),+ ([AuthorizationFilters.AUTHENTICATED_STAFF_USER], False),+ (+ [+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ False,+ ),+ (+ [+ AuthorizationFilters.AUTHENTICATED_USER,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ True,+ ),+ (+ [CheckoutPermissions.MANAGE_TAXES, AuthorizationFilters.AUTHENTICATED_APP],+ False,+ ),+ (+ [+ CheckoutPermissions.MANAGE_TAXES,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ False,+ ),+ (+ [CheckoutPermissions.MANAGE_TAXES, AuthorizationFilters.AUTHENTICATED_USER],+ False,+ ),+ ([CheckoutPermissions.MANAGE_CHECKOUTS, OrderPermissions.MANAGE_ORDERS], False),+ (+ [+ CheckoutPermissions.MANAGE_CHECKOUTS,+ OrderPermissions.MANAGE_ORDERS,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ AuthorizationFilters.AUTHENTICATED_APP,+ ],+ False,+ ),+ (+ [+ CheckoutPermissions.MANAGE_CHECKOUTS,+ OrderPermissions.MANAGE_ORDERS,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ False,+ ),+ (+ [+ CheckoutPermissions.MANAGE_CHECKOUTS,+ OrderPermissions.MANAGE_ORDERS,+ AuthorizationFilters.AUTHENTICATED_USER,+ ],+ False,+ ),+ ],+)+def test_permissions_for_customer(permissions, expected_result, customer_user):+ # given+ context = Mock()+ context.app = None+ context.user = customer_user++ # when+ result = all_permissions_required(context, permissions)++ # then+ assert result is expected_resultdiff --git a/saleor/permission/utils.py b/saleor/permission/utils.pyindex 3432b5c44b..64c8d19081 100644--- a/saleor/permission/utils.py+++ b/saleor/permission/utils.py@@ -8,6 +8,26 @@ if TYPE_CHECKING:from ..app.models import App+def all_permissions_required(context, permissions: Iterable[BasePermissionEnum]):+ """Determine whether user or app has rights to perform an action.++ The `context` parameter is the Context instance associated with the request.++ All required Saleor's permissions must be fulfilled.+ If authorization filter provided, at least one of them must be fulfilled.+ """+ if not permissions:+ return True++ perm_results = _get_result_of_permissions_checks(context, permissions)+ auth_filters_results = _get_result_of_authorization_filters_checks(+ context, permissions+ )+ if auth_filters_results:+ return all(perm_results) and any(auth_filters_results)+ return all(perm_results)++def one_of_permissions_or_auth_filter_required(context, permissions: Iterable[BasePermissionEnum]) -> bool:@@ -18,33 +38,44 @@ def one_of_permissions_or_auth_filter_required(if not permissions:return True- authorization_filters = [- p for p in permissions if isinstance(p, AuthorizationFilters)- ]- permissions = [p for p in permissions if not isinstance(p, AuthorizationFilters)]+ perm_results = _get_result_of_permissions_checks(context, permissions)+ auth_filters_results = _get_result_of_authorization_filters_checks(+ context, permissions+ )+ return any(perm_results) or any(auth_filters_results)- granted_by_permissions = False- granted_by_authorization_filters = False++def _get_result_of_permissions_checks(+ context, permissions: Iterable[BasePermissionEnum]+) -> Iterable[bool]:+ permissions = [p for p in permissions if not isinstance(p, AuthorizationFilters)]# TODO: move this function from graphql to corefrom saleor.graphql.utils import get_user_or_app_from_contextrequestor = get_user_or_app_from_context(context)+ perm_checks_results = []if requestor and permissions:perm_checks_results = [requestor.has_perm(perm) for perm in permissions]- granted_by_permissions = any(perm_checks_results)+ return perm_checks_results++def _get_result_of_authorization_filters_checks(+ context, permissions: Iterable[BasePermissionEnum]+) -> Iterable[bool]:+ authorization_filters = [+ p for p in permissions if isinstance(p, AuthorizationFilters)+ ]+ auth_filters_results = []if authorization_filters:- auth_filters_results = []for p in authorization_filters:perm_fn = resolve_authorization_filter_fn(p)if perm_fn:res = perm_fn(context)auth_filters_results.append(bool(res))- granted_by_authorization_filters = any(auth_filters_results)- return granted_by_permissions or granted_by_authorization_filters+ return auth_filters_resultsdef permission_required(diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 883cbfdc85..8e529f7347 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -763,6 +763,45 @@ def checkout_with_item_and_preorder_item(return checkout_with_item+def checkout_with_problems(+ checkout_with_items,+ product_type,+ address,+ shipping_method,+ category,+ default_tax_class,+ channel_USD,+ warehouse,+):+ checkout_with_items.shipping_address = address+ checkout_with_items.billing_address = address+ checkout_with_items.shipping_method = shipping_method+ checkout_with_items.save(+ update_fields=["shipping_address", "shipping_method", "billing_address"]+ )++ first_line = checkout_with_items.lines.first()+ first_line.variant.track_inventory = True+ first_line.variant.save(update_fields=["track_inventory"])++ product_type = first_line.variant.product.product_type+ product_type.is_shipping_required = True+ product_type.save(update_fields=["is_shipping_required"])++ first_line.variant.stocks.all().delete()++ second_line = checkout_with_items.lines.last()++ available_at = datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=5)+ product = second_line.variant.product+ product.channel_listings.update(+ available_for_purchase_at=available_at, is_published=False+ )++ return checkout_with_items++@pytest.fixturedef address(db): # pylint: disable=W0613return Address.objects.create(