Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
App dataloader (#10181)
Dominik Kozaczkoaa5b860b6f8e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cb296b2746..a7eda13420 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,9 +5,12 @@ All notable, unreleased changes to this project will be documented in this file.# 3.7.0 [Unreleased]### Other changes+- Fix situation when Payment Gateway try to save to long error message - #10402 by @fowczarek+- Replaced `context.app` lazy object with a dataloader.- Add support for bcrypt password hashes - #10346 by @pkucmus+# 3.6.0### Breaking changesdiff --git a/saleor/app/models.py b/saleor/app/models.pyindex 58b7230d0d..1f8091c8ce 100644--- a/saleor/app/models.py+++ b/saleor/app/models.py@@ -1,4 +1,4 @@-from typing import Collection, Set, Union+from typing import Collection, Set, Tuple, Unionfrom django.contrib.auth.hashers import make_passwordfrom django.contrib.auth.models import Permission@@ -117,6 +117,11 @@ class AppTokenManager(models.Manager):app_token.save()return app_token, auth_token+ def create_with_token(self, *args, **kwargs) -> Tuple["AppToken", str]:+ # As `create` is waiting to be fixed, I'm using this proper method from future+ # to get both AppToken and auth_token.+ return self.create(*args, **kwargs)+class AppToken(models.Model):app = models.ForeignKey(App, on_delete=models.CASCADE, related_name="tokens")diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.pyindex 263c41b8fc..9aaa0c9669 100644--- a/saleor/graphql/account/mutations/base.py+++ b/saleor/graphql/account/mutations/base.py@@ -22,6 +22,7 @@ from ....graphql.utils import get_user_or_app_from_contextfrom ....order.utils import match_orders_with_new_userfrom ...account.i18n import I18nMixinfrom ...account.types import Address, AddressInput, User+from ...app.dataloaders import load_appfrom ...channel.utils import clean_channel, validate_channelfrom ...core.enums import LanguageCodeEnumfrom ...core.mutations import (@@ -49,7 +50,8 @@ def check_can_edit_address(context, address):requester = get_user_or_app_from_context(context)if requester.has_perm(AccountPermissions.MANAGE_USERS):return True- if not context.app and not context.user.is_anonymous:+ app = load_app(context)+ if not app and not context.user.is_anonymous:is_owner = requester.addresses.filter(pk=address.pk).exists()if is_owner:return Truediff --git a/saleor/graphql/account/mutations/permission_group.py b/saleor/graphql/account/mutations/permission_group.pyindex 4b448cf0cc..66bed007f5 100644--- a/saleor/graphql/account/mutations/permission_group.py+++ b/saleor/graphql/account/mutations/permission_group.py@@ -17,6 +17,7 @@ from ...account.utils import (get_out_of_scope_permissions,get_out_of_scope_users,)+from ...app.dataloaders import load_appfrom ...core.enums import PermissionEnumfrom ...core.mutations import ModelDeleteMutation, ModelMutationfrom ...core.types import NonNullList, PermissionGroupError@@ -109,7 +110,8 @@ class PermissionGroupCreate(ModelMutation):@classmethoddef check_permissions(cls, context, permissions=None):- if context.app:+ app = load_app(context)+ if app:raise PermissionDenied(message="Apps are not allowed to perform this mutation.")@@ -456,7 +458,8 @@ class PermissionGroupDelete(ModelDeleteMutation):@classmethoddef check_permissions(cls, context, permissions=None):- if context.app:+ app = load_app(context)+ if app:raise PermissionDenied(message="Apps are not allowed to perform this mutation.")diff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.pyindex defc82ac30..7dda34c71b 100644--- a/saleor/graphql/account/mutations/staff.py+++ b/saleor/graphql/account/mutations/staff.py@@ -24,6 +24,7 @@ from ....order.utils import match_orders_with_new_userfrom ....thumbnail import models as thumbnail_modelsfrom ...account.enums import AddressTypeEnumfrom ...account.types import Address, AddressInput, User+from ...app.dataloaders import load_appfrom ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ...core.types import AccountError, NonNullList, StaffError, Uploadfrom ...core.utils import add_hash_to_file_name, validate_image_file@@ -105,7 +106,7 @@ class CustomerUpdate(CustomerCreate):):# Retrieve the event base datastaff_user = info.context.user- app = info.context.app+ app = load_app(info.context)new_email = new_instance.emailnew_fullname = new_instance.get_full_name()@@ -129,13 +130,13 @@ class CustomerUpdate(CustomerCreate):if was_activated:account_events.customer_account_activated_event(staff_user=info.context.user,- app=info.context.app,+ app=app,account_id=old_instance.id,)if was_deactivated:account_events.customer_account_deactivated_event(staff_user=info.context.user,- app=info.context.app,+ app=app,account_id=old_instance.id,)@@ -214,7 +215,8 @@ class StaffCreate(ModelMutation):@classmethoddef check_permissions(cls, context, permissions=None):- if context.app:+ app = load_app(context)+ if app:raise PermissionDenied(message="Apps are not allowed to perform this mutation.")diff --git a/saleor/graphql/account/resolvers.py b/saleor/graphql/account/resolvers.pyindex 10cb4aaf5e..05ee4e26b5 100644--- a/saleor/graphql/account/resolvers.py+++ b/saleor/graphql/account/resolvers.py@@ -16,6 +16,7 @@ from ...core.permissions import (from ...core.tracing import traced_resolverfrom ...payment import gatewayfrom ...payment.utils import fetch_customer_id+from ..app.dataloaders import load_appfrom ..core.utils import from_global_id_or_errorfrom ..meta.resolvers import resolve_metadatafrom ..utils import format_permissions_for_display, get_user_or_app_from_context@@ -201,7 +202,7 @@ def prepare_graphql_payment_sources_type(payment_sources):@traced_resolverdef resolve_address(info, id):user = info.context.user- app = info.context.app+ app = load_app(info.context)_, address_pk = from_global_id_or_error(id, Address)if app and app.has_perm(AccountPermissions.MANAGE_USERS):return models.Address.objects.filter(pk=address_pk).first()@@ -214,7 +215,7 @@ def resolve_address(info, id):def resolve_addresses(info, ids):user = info.context.user- app = info.context.app+ app = load_app(info.context)ids = [from_global_id_or_error(address_id, Address, raise_error=True)[1]for address_id in idsdiff --git a/saleor/graphql/account/utils.py b/saleor/graphql/account/utils.pyindex 08a667fd44..1a55f1030d 100644--- a/saleor/graphql/account/utils.py+++ b/saleor/graphql/account/utils.py@@ -17,6 +17,7 @@ from ...core.permissions import (AuthorizationFilters,has_one_of_permissions,)+from ..app.dataloaders import load_appif TYPE_CHECKING:from django.db.models import QuerySet@@ -71,9 +72,10 @@ class CustomerDeleteMixin(UserDeleteMixin):@classmethoddef post_process(cls, info, deleted_count=1):+ app = load_app(info.context)account_events.customer_deleted_event(staff_user=info.context.user,- app=info.context.app,+ app=app,deleted_count=deleted_count,)@@ -84,7 +86,7 @@ class StaffDeleteMixin(UserDeleteMixin):@classmethoddef check_permissions(cls, context, permissions=None):- if context.app:+ if load_app(context):raise PermissionDenied(message="Apps are not allowed to perform this mutation.")diff --git a/saleor/graphql/app/dataloaders.py b/saleor/graphql/app/dataloaders.pyindex edddc24572..fa65401f16 100644--- a/saleor/graphql/app/dataloaders.py+++ b/saleor/graphql/app/dataloaders.py@@ -1,6 +1,9 @@from collections import defaultdict-from ...app.models import App, AppExtension+from django.contrib.auth.hashers import check_password++from ...app.models import App, AppExtension, AppToken+from ...core.auth import get_token_from_requestfrom ..core.dataloaders import DataLoader@@ -35,3 +38,43 @@ class AppExtensionByAppIdLoader(DataLoader):extensions_map[extension.app_id].append(extension)app_extension_loader.prime(extension.id, extension)return [extensions_map.get(app_id, []) for app_id in keys]+++class AppByTokenLoader(DataLoader):+ context_key = "app_by_token"++ def batch_load(self, keys):+ last_4s_to_raw_token_map = defaultdict(list)+ for raw_token in keys:+ last_4s_to_raw_token_map[raw_token[-4:]].append(raw_token)++ tokens = (+ AppToken.objects.using(self.database_connection_name)+ .filter(token_last_4__in=last_4s_to_raw_token_map.keys())+ .values_list("auth_token", "token_last_4", "app_id")+ )+ authed_apps = {}+ for auth_token, token_last_4, app_id in tokens:+ for raw_token in last_4s_to_raw_token_map[token_last_4]:+ if check_password(raw_token, auth_token):+ authed_apps[raw_token] = app_id++ apps = (+ App.objects.using(self.database_connection_name)+ .filter(id__in=authed_apps.values(), is_active=True)+ .in_bulk()+ )++ return [apps.get(authed_apps.get(key)) for key in keys]+++def promise_app(context):+ auth_token = get_token_from_request(context)+ if not auth_token or len(auth_token) != 30:+ return None+ return AppByTokenLoader(context).load(auth_token)+++def load_app(context):+ promise = promise_app(context)+ return None if promise is None else promise.get()diff --git a/saleor/graphql/app/schema.py b/saleor/graphql/app/schema.pyindex 4657569dab..9436dba291 100644--- a/saleor/graphql/app/schema.py+++ b/saleor/graphql/app/schema.py@@ -7,7 +7,7 @@ from ..core.descriptions import ADDED_IN_31, PREVIEW_FEATUREfrom ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.types import FilterInputObjectType, NonNullListfrom ..core.utils import from_global_id_or_error-from .dataloaders import AppByIdLoader, AppExtensionByIdLoader+from .dataloaders import AppByIdLoader, AppExtensionByIdLoader, load_appfrom .filters import AppExtensionFilter, AppFilterfrom .mutations import (AppActivate,@@ -120,7 +120,7 @@ class AppQueries(graphene.ObjectType):@staticmethoddef resolve_app(_root, info, *, id=None):- if app := info.context.app:+ if app := load_app(info.context):if not id:return app_, app_id = from_global_id_or_error(id, only_type="App")diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.pyindex e87c8fb730..edce2a08f5 100644--- a/saleor/graphql/app/types.py+++ b/saleor/graphql/app/types.py@@ -26,7 +26,7 @@ from ..meta.types import ObjectWithMetadatafrom ..utils import format_permissions_for_display, get_user_or_app_from_contextfrom ..webhook.enums import WebhookEventTypeAsyncEnum, WebhookEventTypeSyncEnumfrom ..webhook.types import Webhook-from .dataloaders import AppByIdLoader, AppExtensionByAppIdLoader+from .dataloaders import AppByIdLoader, AppExtensionByAppIdLoader, load_appfrom .enums import AppExtensionMountEnum, AppExtensionTargetEnum, AppTypeEnumfrom .resolvers import (resolve_access_token_for_app,@@ -56,7 +56,8 @@ def has_access_to_app_public_meta(root, info) -> bool:if auth_token.get("type") == JWT_THIRDPARTY_ACCESS_TYPE:_, app_id = from_global_id_or_error(auth_token["app"], "App")else:- app_id = info.context.app.id if info.context.app else None+ app = load_app(info.context)+ app_id = app.id if app else Noneif app_id is not None and int(app_id) == root.id:return Truerequester = get_user_or_app_from_context(info.context)@@ -125,7 +126,7 @@ class AppExtension(AppManifestExtension, ModelObjectType):@staticmethoddef resolve_app(root, info):app_id = None- app = info.context.app+ app = load_app(info.context)if app and app.id == root.app_id:app_id = root.app_idelse:diff --git a/saleor/graphql/checkout/mutations/checkout_complete.py b/saleor/graphql/checkout/mutations/checkout_complete.pyindex 5c50990f45..bbb9a31b3d 100644--- a/saleor/graphql/checkout/mutations/checkout_complete.py+++ b/saleor/graphql/checkout/mutations/checkout_complete.py@@ -19,6 +19,7 @@ from ....core.permissions import AccountPermissionsfrom ....core.transactions import transaction_with_commit_on_errorsfrom ....order import models as order_modelsfrom ...account.i18n import I18nMixin+from ...app.dataloaders import load_appfrom ...core.descriptions import ADDED_IN_34, DEPRECATED_IN_3X_INPUTfrom ...core.fields import JSONStringfrom ...core.mutations import BaseMutation@@ -255,7 +256,7 @@ class CheckoutComplete(BaseMutation, I18nMixin):store_source=store_source,discounts=info.context.discounts,user=customer,- app=info.context.app,+ app=load_app(info.context),site_settings=info.context.site.settings,tracking_code=tracking_code,redirect_url=data.get("redirect_url"),diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.pyindex 1db8ba9bb8..918386e44c 100644--- a/saleor/graphql/checkout/mutations/checkout_create.py+++ b/saleor/graphql/checkout/mutations/checkout_create.py@@ -11,6 +11,7 @@ from ....product import models as product_modelsfrom ....warehouse.reservations import get_reservation_length, is_reservation_enabledfrom ...account.i18n import I18nMixinfrom ...account.types import AddressInput+from ...app.dataloaders import load_appfrom ...channel.utils import clean_channelfrom ...core.descriptions import (ADDED_IN_31,@@ -168,7 +169,8 @@ class CheckoutCreate(ModelMutation, I18nMixin):def clean_checkout_lines(cls, info, lines, country, channel) -> Tuple[List[product_models.ProductVariant], List["CheckoutLineData"]]:- check_permissions_for_custom_prices(info.context.app, lines)+ app = load_app(info.context)+ check_permissions_for_custom_prices(app, lines)variant_ids = [line["variant_id"] for line in lines]variants = cls.get_nodes_or_error(variant_ids,diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.pyindex ea0cf3914e..7412b8a5b6 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py@@ -10,6 +10,7 @@ from ....checkout.fetch import ()from ....checkout.utils import add_variants_to_checkout, invalidate_checkout_pricesfrom ....warehouse.reservations import get_reservation_length, is_reservation_enabled+from ...app.dataloaders import load_appfrom ...core.descriptions import ADDED_IN_34, DEPRECATED_IN_3X_INPUTfrom ...core.mutations import BaseMutationfrom ...core.scalars import UUID@@ -164,7 +165,8 @@ class CheckoutLinesAdd(BaseMutation):def perform_mutation(cls, _root, info, lines, checkout_id=None, token=None, id=None, replace=False):- check_permissions_for_custom_prices(info.context.app, lines)+ app = load_app(info.context)+ check_permissions_for_custom_prices(app, lines)checkout = get_checkout(cls,diff --git a/saleor/graphql/checkout/mutations/checkout_lines_update.py b/saleor/graphql/checkout/mutations/checkout_lines_update.pyindex aa1f354a22..adce6e76d0 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_update.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_update.py@@ -5,6 +5,7 @@ from django.forms import ValidationErrorfrom ....checkout.error_codes import CheckoutErrorCodefrom ....warehouse.reservations import is_reservation_enabled+from ...app.dataloaders import load_appfrom ...checkout.types import CheckoutLinefrom ...core.descriptions import (ADDED_IN_31,@@ -129,8 +130,9 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):discounts,replace,):+ app = load_app(info.context)# if the requestor is not app, the quantity is required for all lines- if not info.context.app:+ if not app:if any([line_data.quantity_to_update is Falsediff --git a/saleor/graphql/checkout/mutations/order_create_from_checkout.py b/saleor/graphql/checkout/mutations/order_create_from_checkout.pyindex 1e043b3ad6..da66bf0861 100644--- a/saleor/graphql/checkout/mutations/order_create_from_checkout.py+++ b/saleor/graphql/checkout/mutations/order_create_from_checkout.py@@ -8,6 +8,7 @@ from ....core import analyticsfrom ....core.exceptions import GiftCardNotApplicable, InsufficientStockfrom ....core.permissions import CheckoutPermissionsfrom ....discount.models import NotApplicable+from ...app.dataloaders import load_appfrom ...core.descriptions import ADDED_IN_32, PREVIEW_FEATUREfrom ...core.mutations import BaseMutationfrom ...core.types import Error@@ -96,7 +97,7 @@ class OrderCreateFromCheckout(BaseMutation):discounts=discounts,manager=manager,)-+ app = load_app(info.context)try:order = create_order_from_checkout(checkout_info=checkout_info,@@ -104,7 +105,7 @@ class OrderCreateFromCheckout(BaseMutation):discounts=info.context.discounts,manager=info.context.plugins,user=info.context.user,- app=info.context.app,+ app=app,tracking_code=tracking_code,delete_checkout=data["remove_checkout"],)diff --git a/saleor/graphql/context.py b/saleor/graphql/context.pyindex cf4119a44b..a4cdd241e6 100644--- a/saleor/graphql/context.py+++ b/saleor/graphql/context.py@@ -1,16 +1,16 @@from typing import Optional, Protocol, Union, castfrom django.contrib.auth import authenticate-from django.contrib.auth.hashers import check_passwordfrom django.contrib.auth.models import AnonymousUser-from django.db.models import Exists, OuterReffrom django.utils.functional import SimpleLazyObject+from promise import Promisefrom ..account.models import User-from ..app.models import App, AppToken+from ..app.models import Appfrom ..core.auth import get_token_from_requestfrom ..core.jwt import jwt_decode_with_exception_handlerfrom .api import API_PATH+from .app.dataloaders import load_appdef get_context_value(request):@@ -26,33 +26,18 @@ UserType = Union[User, AnonymousUser]class RequestWithUser(Protocol):_cached_user: UserTypeapp: Optional[App]- user: Union[UserType, SimpleLazyObject]---def get_app(raw_auth_token) -> Optional[App]:- tokens = AppToken.objects.filter(token_last_4=raw_auth_token[-4:]).values_list(- "id", "auth_token"- )- token_ids = [- id for id, auth_token in tokens if check_password(raw_auth_token, auth_token)- ]- return App.objects.filter(- Exists(tokens.filter(id__in=token_ids, app_id=OuterRef("pk"))), is_active=True- ).first()+ user: Union[UserType, SimpleLazyObject, Promise]def set_decoded_auth_token(request):- token = get_token_from_request(request)- decoded_auth_token = jwt_decode_with_exception_handler(token)+ auth_token = get_token_from_request(request)+ decoded_auth_token = jwt_decode_with_exception_handler(auth_token)request.decoded_auth_token = decoded_auth_tokendef set_app_on_context(request):if request.path == API_PATH and not hasattr(request, "app"):- request.app = None- auth_token = get_token_from_request(request)- if auth_token and len(auth_token) == 30:- request.app = SimpleLazyObject(lambda: get_app(auth_token))+ request.app = load_app(request)def get_user(request: RequestWithUser) -> Optional[UserType]:diff --git a/saleor/graphql/core/dataloaders.py b/saleor/graphql/core/dataloaders.pyindex 954b499daf..9bab7f9342 100644--- a/saleor/graphql/core/dataloaders.py+++ b/saleor/graphql/core/dataloaders.py@@ -33,7 +33,7 @@ class DataLoader(BaseLoader, Generic[K, R]):def __init__(self, context):if self.context != context:self.context = context- self.user = context.user+ self.user = getattr(context, "user", None)super().__init__()def batch_load_fn(self, keys: Iterable[K]) -> Promise[List[R]]:diff --git a/saleor/graphql/core/tests/test_base_mutation.py b/saleor/graphql/core/tests/test_base_mutation.pyindex 43e0d0d03f..dc1f22e058 100644--- a/saleor/graphql/core/tests/test_base_mutation.py+++ b/saleor/graphql/core/tests/test_base_mutation.py@@ -31,7 +31,7 @@ class Mutation(BaseMutation):@classmethoddef perform_mutation(cls, _root, info, product_id, channel):# Need to mock `app_middleware`- info.context.app = None+ info.context.auth_token = Noneproduct = cls.get_node_or_error(info, product_id, field="product_id", only_type=product_types.Product@@ -73,7 +73,7 @@ class OrderMutation(BaseMutation):@classmethoddef perform_mutation(cls, _root, info, id, channel):# Need to mock `app_middleware`- info.context.app = None+ info.context.auth_token = Noneorder = cls.get_node_or_error(info, id, only_type=order_types.Order)return OrderMutation(number=order.number)@@ -371,29 +371,24 @@ def test_mutation_calls_plugin_perform_mutation_after_permission_checks(assert result.errors[0].message == "My Custom Error"-def test_base_mutation_get_node_by_pk_with_order_qs_and_old_int_id(staff_user, order):+def test_base_mutation_get_node_by_pk_with_order_qs_and_old_int_id(order):# givenorder.use_old_id = Trueorder.save(update_fields=["use_old_id"])- info = mock.Mock(context=mock.Mock(user=staff_user))-# whennode = BaseMutation._get_node_by_pk(- info, order_types.Order, order.number, qs=Order.objects.all()+ None, order_types.Order, order.number, qs=Order.objects.all())# thenassert node.id == order.id-def test_base_mutation_get_node_by_pk_with_order_qs_and_new_uuid_id(staff_user, order):- # given- info = mock.Mock(context=mock.Mock(user=staff_user))-+def test_base_mutation_get_node_by_pk_with_order_qs_and_new_uuid_id(order):# whennode = BaseMutation._get_node_by_pk(- info, order_types.Order, order.pk, qs=Order.objects.all()+ None, order_types.Order, order.pk, qs=Order.objects.all())# then@@ -401,30 +396,25 @@ def test_base_mutation_get_node_by_pk_with_order_qs_and_new_uuid_id(staff_user,def test_base_mutation_get_node_by_pk_with_order_qs_and_int_id_use_old_id_set_to_false(- staff_user, order+ order,):# givenorder.use_old_id = Falseorder.save(update_fields=["use_old_id"])- info = mock.Mock(context=mock.Mock(user=staff_user))-# whennode = BaseMutation._get_node_by_pk(- info, order_types.Order, order.number, qs=Order.objects.all()+ None, order_types.Order, order.number, qs=Order.objects.all())# thenassert node is None-def test_base_mutation_get_node_by_pk_with_qs_for_product(staff_user, product):- # given- info = mock.Mock(context=mock.Mock(user=staff_user))-+def test_base_mutation_get_node_by_pk_with_qs_for_product(product):# whennode = BaseMutation._get_node_by_pk(- info, product_types.Product, product.pk, qs=Product.objects.all()+ None, product_types.Product, product.pk, qs=Product.objects.all())# thendiff --git a/saleor/graphql/csv/mutations.py b/saleor/graphql/csv/mutations.pyindex 46e3e050bf..1bb4119e96 100644--- a/saleor/graphql/csv/mutations.py+++ b/saleor/graphql/csv/mutations.py@@ -7,6 +7,7 @@ from ...core.permissions import GiftcardPermissions, ProductPermissionsfrom ...csv import models as csv_modelsfrom ...csv.events import export_started_eventfrom ...csv.tasks import export_gift_cards_task, export_products_task+from ..app.dataloaders import load_appfrom ..attribute.types import Attributefrom ..channel.types import Channelfrom ..core.descriptions import ADDED_IN_31, PREVIEW_FEATURE@@ -129,7 +130,7 @@ class ExportProducts(BaseExportMutation):export_info = cls.get_export_info(input["export_info"])file_type = input["file_type"]- app = info.context.app+ app = load_app(info.context)kwargs = {"app": app} if app else {"user": info.context.user}export_file = csv_models.ExportFile.objects.create(**kwargs)@@ -198,7 +199,7 @@ class ExportGiftCards(BaseExportMutation):scope = cls.get_scope(input, GiftCard)file_type = input["file_type"]- app = info.context.app+ app = load_app(info.context)kwargs = {"app": app} if app else {"user": info.context.user}export_file = csv_models.ExportFile.objects.create(**kwargs)diff --git a/saleor/graphql/giftcard/bulk_mutations.py b/saleor/graphql/giftcard/bulk_mutations.pyindex 6baec15bbd..d9fda9ac3f 100644--- a/saleor/graphql/giftcard/bulk_mutations.py+++ b/saleor/graphql/giftcard/bulk_mutations.py@@ -11,6 +11,7 @@ from ...core.utils.validators import is_date_in_futurefrom ...giftcard import events, modelsfrom ...giftcard.error_codes import GiftCardErrorCodefrom ...giftcard.utils import is_gift_card_expired+from ..app.dataloaders import load_appfrom ..core.descriptions import ADDED_IN_31, PREVIEW_FEATUREfrom ..core.mutations import BaseBulkMutation, BaseMutation, ModelBulkDeleteMutationfrom ..core.types import GiftCardError, NonNullList, PriceInput@@ -128,15 +129,14 @@ class GiftCardBulkCreate(BaseMutation):def create_instances(cleaned_input, info):count = cleaned_input.pop("count")balance = cleaned_input.pop("balance")+ app = load_app(info.context)gift_cards = models.GiftCard.objects.bulk_create([models.GiftCard(code=generate_promo_code(), **cleaned_input)for _ in range(count)])- events.gift_cards_issued_event(- gift_cards, info.context.user, info.context.app, balance- )+ events.gift_cards_issued_event(gift_cards, info.context.user, app, balance)return gift_cards@staticmethod@@ -205,9 +205,10 @@ class GiftCardBulkActivate(BaseBulkMutation):def bulk_action(cls, info, queryset):queryset = queryset.filter(is_active=False)gift_card_ids = [gift_card.id for gift_card in queryset]+ app = load_app(info.context)queryset.update(is_active=True)events.gift_cards_activated_event(- gift_card_ids, user=info.context.user, app=info.context.app+ gift_card_ids, user=info.context.user, app=app)for card in models.GiftCard.objects.filter(id__in=gift_card_ids):info.context.plugins.gift_card_status_changed(card)@@ -231,11 +232,12 @@ class GiftCardBulkDeactivate(BaseBulkMutation):@classmethod@traced_atomic_transaction()def bulk_action(cls, info, queryset):+ app = load_app(info.context)queryset = queryset.filter(is_active=True)gift_card_ids = [gift_card.id for gift_card in queryset]queryset.update(is_active=False)events.gift_cards_deactivated_event(- gift_card_ids, user=info.context.user, app=info.context.app+ gift_card_ids, user=info.context.user, app=app)for card in models.GiftCard.objects.filter(id__in=gift_card_ids):info.context.plugins.gift_card_status_changed(card)diff --git a/saleor/graphql/giftcard/mutations.py b/saleor/graphql/giftcard/mutations.pyindex 607b97b7c6..b706f20df6 100644--- a/saleor/graphql/giftcard/mutations.py+++ b/saleor/graphql/giftcard/mutations.py@@ -18,6 +18,7 @@ from ...giftcard.utils import (deactivate_gift_card,is_gift_card_expired,)+from ..app.dataloaders import load_appfrom ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_INPUT, PREVIEW_FEATUREfrom ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ..core.scalars import PositiveDecimal@@ -167,7 +168,7 @@ class GiftCardCreate(ModelMutation):if user_is_valid(user):cleaned_input["created_by"] = usercleaned_input["created_by_email"] = user.email- cleaned_input["app"] = info.context.app+ cleaned_input["app"] = load_app(info.context)@classmethoddef clean_expiry_date(cls, cleaned_input, instance):@@ -219,7 +220,7 @@ class GiftCardCreate(ModelMutation):@classmethoddef post_save_action(cls, info, instance, cleaned_input):user = info.context.user- app = info.context.app+ app = load_app(info.context)events.gift_card_issued_event(gift_card=instance,user=user,@@ -329,7 +330,7 @@ class GiftCardUpdate(GiftCardCreate):cls._save_m2m(info, instance, cleaned_input)user = info.context.user- app = info.context.app+ app = load_app(info.context)if "initial_balance_amount" in cleaned_input:events.gift_card_balance_reset_event(instance, old_instance, user, app)if "expiry_date" in cleaned_input:@@ -402,8 +403,11 @@ class GiftCardDeactivate(BaseMutation):create_event = gift_card.is_activedeactivate_gift_card(gift_card)if create_event:+ app = load_app(info.context)events.gift_card_deactivated_event(- gift_card=gift_card, user=info.context.user, app=info.context.app+ gift_card=gift_card,+ user=info.context.user,+ app=app,)info.context.plugins.gift_card_status_changed(gift_card)return GiftCardDeactivate(gift_card=gift_card)@@ -432,8 +436,11 @@ class GiftCardActivate(BaseMutation):create_event = not gift_card.is_activeactivate_gift_card(gift_card)if create_event:+ app = load_app(info.context)events.gift_card_activated_event(- gift_card=gift_card, user=info.context.user, app=info.context.app+ gift_card=gift_card,+ user=info.context.user,+ app=app,)info.context.plugins.gift_card_status_changed(gift_card)return GiftCardActivate(gift_card=gift_card)@@ -504,9 +511,10 @@ class GiftCardResend(BaseMutation):user = info.context.userif not user_is_valid(user):user = None+ app = load_app(info.context)send_gift_card_notification(user,- info.context.app,+ app,customer_user,target_email,gift_card,@@ -558,10 +566,11 @@ class GiftCardAddNote(BaseMutation):def perform_mutation(cls, _root, info, **data):gift_card = cls.get_node_or_error(info, data.get("id"), only_type=GiftCard)cleaned_input = cls.clean_input(info, gift_card, data)+ app = load_app(info.context)event = events.gift_card_note_added_event(gift_card=gift_card,user=info.context.user,- app=info.context.app,+ app=app,message=cleaned_input["message"],)info.context.plugins.gift_card_updated(gift_card)diff --git a/saleor/graphql/invoice/mutations.py b/saleor/graphql/invoice/mutations.pyindex d7e443a475..c92de55cbb 100644--- a/saleor/graphql/invoice/mutations.py+++ b/saleor/graphql/invoice/mutations.py@@ -7,6 +7,7 @@ from ...invoice import events, modelsfrom ...invoice.error_codes import InvoiceErrorCodefrom ...invoice.notifications import send_invoicefrom ...order import events as order_events+from ..app.dataloaders import load_appfrom ..core.mutations import ModelDeleteMutation, ModelMutationfrom ..core.types import InvoiceErrorfrom ..order.types import Order@@ -83,22 +84,22 @@ class InvoiceRequest(ModelMutation):invoice = info.context.plugins.invoice_request(order=order, invoice=shallow_invoice, number=data.get("number"))-+ app = load_app(info.context)if invoice and invoice.status == JobStatus.SUCCESS:order_events.invoice_generated_event(order=order,user=info.context.user,- app=info.context.app,+ app=app,invoice_number=invoice.number,)else:order_events.invoice_requested_event(- user=info.context.user, app=info.context.app, order=order+ user=info.context.user, app=app, order=order)events.invoice_requested_event(user=info.context.user,- app=info.context.app,+ app=app,order=order,number=data.get("number"),)@@ -173,9 +174,10 @@ class InvoiceCreate(ModelMutation):invoice.order = orderinvoice.status = JobStatus.SUCCESSinvoice.save()+ app = load_app(info.context)events.invoice_created_event(user=info.context.user,- app=info.context.app,+ app=app,invoice=invoice,number=cleaned_input["number"],url=cleaned_input["url"],@@ -183,7 +185,7 @@ class InvoiceCreate(ModelMutation):order_events.invoice_generated_event(order=order,user=info.context.user,- app=info.context.app,+ app=app,invoice_number=cleaned_input["number"],)return InvoiceCreate(invoice=invoice)@@ -209,8 +211,9 @@ class InvoiceRequestDelete(ModelMutation):invoice.status = JobStatus.PENDINGinvoice.save(update_fields=["status", "updated_at"])info.context.plugins.invoice_delete(invoice)+ app = load_app(info.context)events.invoice_requested_deletion_event(- user=info.context.user, app=info.context.app, invoice=invoice+ user=info.context.user, app=app, invoice=invoice)return InvoiceRequestDelete(invoice=invoice)@@ -231,8 +234,9 @@ class InvoiceDelete(ModelDeleteMutation):def perform_mutation(cls, _root, info, **data):invoice = cls.get_instance(info, **data)response = super().perform_mutation(_root, info, **data)+ app = load_app(info.context)events.invoice_deleted_event(- user=info.context.user, app=info.context.app, invoice_id=invoice.pk+ user=info.context.user, app=app, invoice_id=invoice.pk)return response@@ -288,10 +292,11 @@ class InvoiceUpdate(ModelMutation):)instance.status = JobStatus.SUCCESSinstance.save(update_fields=["external_url", "number", "updated_at", "status"])+ app = load_app(info.context)order_events.invoice_updated_event(order=instance.order,user=info.context.user,- app=info.context.app,+ app=app,invoice_number=instance.number,url=instance.url,status=instance.status,@@ -342,7 +347,11 @@ class InvoiceSendNotification(ModelMutation):def perform_mutation(cls, _root, info, **data):instance = cls.get_instance(info, **data)cls.clean_instance(info, instance)+ app = load_app(info.context)send_invoice(- instance, info.context.user, info.context.app, info.context.plugins+ invoice=instance,+ staff_user=info.context.user,+ app=app,+ manager=info.context.plugins,)return InvoiceSendNotification(invoice=instance)diff --git a/saleor/graphql/meta/permissions.py b/saleor/graphql/meta/permissions.pyindex 04a8619fd7..70449b271c 100644--- a/saleor/graphql/meta/permissions.py+++ b/saleor/graphql/meta/permissions.py@@ -25,6 +25,7 @@ from ...core.permissions import (ShippingPermissions,)from ...payment.utils import payment_owned_by_user+from ..app.dataloaders import load_appfrom ..core.utils import from_global_id_or_error@@ -86,17 +87,18 @@ def menu_permissions(_info, _object_pk: Any) -> List[BasePermissionEnum]:def app_permissions(info, object_pk: str) -> List[BasePermissionEnum]:auth_token = info.context.decoded_auth_token or {}+ app = load_app(info.context)if auth_token.get("type") == JWT_THIRDPARTY_ACCESS_TYPE:_, app_id = from_global_id_or_error(auth_token["app"], "App")else:- app_id = info.context.app.id if info.context.app else None+ app_id = app.id if app else Noneif app_id is not None and int(app_id) == int(object_pk):return []return [AppPermission.MANAGE_APPS]def private_app_permssions(info, object_pk: str) -> List[BasePermissionEnum]:- app = info.context.app+ app = load_app(info.context)if app and app.pk == int(object_pk):return []return [AppPermission.MANAGE_APPS]@@ -132,7 +134,8 @@ def discount_permissions(_info, _object_pk: Any) -> List[BasePermissionEnum]:def public_payment_permissions(info, payment_pk: int) -> List[BasePermissionEnum]:context_user = info.context.user- if info.context.app is not None or context_user.is_staff:+ app = load_app(info.context)+ if app is not None or context_user.is_staff:return [PaymentPermissions.HANDLE_PAYMENTS]if payment_owned_by_user(payment_pk, context_user):return []@@ -140,7 +143,8 @@ def public_payment_permissions(info, payment_pk: int) -> List[BasePermissionEnumdef private_payment_permissions(info, _object_pk: Any) -> List[BasePermissionEnum]:- if info.context.app is not None or info.context.user.is_staff:+ app = load_app(info.context)+ if app is not None or info.context.user.is_staff:return [PaymentPermissions.HANDLE_PAYMENTS]raise PermissionDenied(permissions=[PaymentPermissions.HANDLE_PAYMENTS])diff --git a/saleor/graphql/order/bulk_mutations/orders.py b/saleor/graphql/order/bulk_mutations/orders.pyindex 0e2a3e2377..aac0ee87ce 100644--- a/saleor/graphql/order/bulk_mutations/orders.py+++ b/saleor/graphql/order/bulk_mutations/orders.py@@ -3,6 +3,7 @@ import graphenefrom ....core.permissions import OrderPermissionsfrom ....order import modelsfrom ....order.actions import cancel_order+from ...app.dataloaders import load_appfrom ...core.mutations import BaseBulkMutationfrom ...core.types import NonNullList, OrderErrorfrom ..mutations.order_cancel import clean_order_cancel@@ -33,6 +34,6 @@ class OrderBulkCancel(BaseBulkMutation):cancel_order(order=order,user=info.context.user,- app=info.context.app,+ app=load_app(info.context),manager=info.context.plugins,)diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.pyindex 4861fbf0a9..8ee3a4fc34 100644--- a/saleor/graphql/order/mutations/draft_order_complete.py+++ b/saleor/graphql/order/mutations/draft_order_complete.py@@ -17,6 +17,7 @@ from ....order.search import prepare_order_search_vector_valuefrom ....order.utils import get_order_countryfrom ....warehouse.management import allocate_preorders, allocate_stocksfrom ....warehouse.reservations import is_reservation_enabled+from ...app.dataloaders import load_appfrom ...core.mutations import BaseMutationfrom ...core.types import OrderErrorfrom ..types import Order@@ -129,14 +130,14 @@ class DraftOrderComplete(BaseMutation):payment=order.get_last_payment(),lines_data=order_lines_info,)+ app = load_app(info.context)transaction.on_commit(lambda: order_created(order_info=order_info,user=info.context.user,- app=info.context.app,+ app=app,manager=info.context.plugins,from_draft=True,))-return DraftOrderComplete(order=order)diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.pyindex 836223796e..36833f3098 100644--- a/saleor/graphql/order/mutations/draft_order_create.py+++ b/saleor/graphql/order/mutations/draft_order_create.py@@ -22,6 +22,7 @@ from ....order.utils import ()from ...account.i18n import I18nMixinfrom ...account.types import AddressInput+from ...app.dataloaders import load_appfrom ...channel.types import Channelfrom ...core.descriptions import ADDED_IN_36, PREVIEW_FEATUREfrom ...core.mutations import ModelMutation@@ -289,10 +290,11 @@ class DraftOrderCreate(ModelMutation, I18nMixin):lines.append(new_line)# New event+ app = load_app(info.context)events.order_added_products_event(order=instance,user=info.context.user,- app=info.context.app,+ app=app,order_lines=lines,)@@ -302,8 +304,9 @@ class DraftOrderCreate(ModelMutation, I18nMixin):# Create draft created event if the instance is from scratchif is_new_instance:+ app = load_app(info.context)events.draft_order_created_event(- order=instance, user=info.context.user, app=info.context.app+ order=instance, user=info.context.user, app=app)instance.save(diff --git a/saleor/graphql/order/mutations/fulfillment_approve.py b/saleor/graphql/order/mutations/fulfillment_approve.pyindex 77c1ba937f..2209d2db56 100644--- a/saleor/graphql/order/mutations/fulfillment_approve.py+++ b/saleor/graphql/order/mutations/fulfillment_approve.py@@ -6,6 +6,7 @@ from ....core.permissions import OrderPermissionsfrom ....order import FulfillmentStatusfrom ....order.actions import approve_fulfillmentfrom ....order.error_codes import OrderErrorCode+from ...app.dataloaders import load_appfrom ...core.descriptions import ADDED_IN_31from ...core.mutations import BaseMutationfrom ...core.types import OrderError@@ -61,10 +62,11 @@ class FulfillmentApprove(BaseMutation):order = fulfillment.ordertry:+ app = load_app(info.context)fulfillment = approve_fulfillment(fulfillment,info.context.user,- info.context.app,+ app,info.context.plugins,info.context.site.settings,notify_customer=data["notify_customer"],diff --git a/saleor/graphql/order/mutations/fulfillment_cancel.py b/saleor/graphql/order/mutations/fulfillment_cancel.pyindex 0bbf79ea83..20b6f8b2fb 100644--- a/saleor/graphql/order/mutations/fulfillment_cancel.py+++ b/saleor/graphql/order/mutations/fulfillment_cancel.py@@ -6,6 +6,7 @@ from ....giftcard.utils import order_has_gift_card_linesfrom ....order import FulfillmentStatusfrom ....order.actions import cancel_fulfillment, cancel_waiting_fulfillmentfrom ....order.error_codes import OrderErrorCode+from ...app.dataloaders import load_appfrom ...core.mutations import BaseMutationfrom ...core.types import OrderErrorfrom ..types import Fulfillment, Order@@ -89,18 +90,19 @@ class FulfillmentCancel(BaseMutation):cls.validate_fulfillment(fulfillment, warehouse)+ app = load_app(info.context)if fulfillment.status == FulfillmentStatus.WAITING_FOR_APPROVAL:fulfillment = cancel_waiting_fulfillment(fulfillment,info.context.user,- info.context.app,+ app,info.context.plugins,)else:fulfillment = cancel_fulfillment(fulfillment,info.context.user,- info.context.app,+ app,warehouse,info.context.plugins,)diff --git a/saleor/graphql/order/mutations/fulfillment_refund_products.py b/saleor/graphql/order/mutations/fulfillment_refund_products.pyindex 89dda6edff..14184b2f1f 100644--- a/saleor/graphql/order/mutations/fulfillment_refund_products.py+++ b/saleor/graphql/order/mutations/fulfillment_refund_products.py@@ -5,6 +5,7 @@ from ....order import FulfillmentStatusfrom ....order import models as order_modelsfrom ....order.actions import create_refund_fulfillmentfrom ....payment import PaymentError+from ...app.dataloaders import load_appfrom ...core.scalars import PositiveDecimalfrom ...core.types import NonNullList, OrderErrorfrom ..types import Fulfillment, Order@@ -133,9 +134,10 @@ class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):order = cleaned_input["order"]try:+ app = load_app(info.context)refund_fulfillment = create_refund_fulfillment(info.context.user,- info.context.app,+ app,order,cleaned_input["payment"],cleaned_input["transactions"],diff --git a/saleor/graphql/order/mutations/fulfillment_return_products.py b/saleor/graphql/order/mutations/fulfillment_return_products.pyindex d832f72b52..2e19cdaf68 100644--- a/saleor/graphql/order/mutations/fulfillment_return_products.py+++ b/saleor/graphql/order/mutations/fulfillment_return_products.py@@ -5,6 +5,7 @@ from ....order import FulfillmentStatusfrom ....order import models as order_modelsfrom ....order.actions import create_fulfillments_for_returned_productsfrom ....payment import PaymentError+from ...app.dataloaders import load_appfrom ...core.scalars import PositiveDecimalfrom ...core.types import NonNullList, OrderErrorfrom ..types import Fulfillment, Order@@ -155,9 +156,10 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):cleaned_input = cls.clean_input(info, data.get("order"), data.get("input"))order = cleaned_input["order"]try:+ app = load_app(info.context)response = create_fulfillments_for_returned_products(info.context.user,- info.context.app,+ app,order,cleaned_input.get("payment"),cleaned_input.get("transactions"),diff --git a/saleor/graphql/order/mutations/fulfillment_update_tracking.py b/saleor/graphql/order/mutations/fulfillment_update_tracking.pyindex 1680af3c03..dea0b52d52 100644--- a/saleor/graphql/order/mutations/fulfillment_update_tracking.py+++ b/saleor/graphql/order/mutations/fulfillment_update_tracking.py@@ -3,6 +3,7 @@ import graphenefrom ....core.permissions import OrderPermissionsfrom ....order.actions import fulfillment_tracking_updatedfrom ....order.notifications import send_fulfillment_update+from ...app.dataloaders import load_appfrom ...core.mutations import BaseMutationfrom ...core.types import OrderErrorfrom ..types import Fulfillment, Order@@ -36,10 +37,11 @@ class FulfillmentUpdateTracking(BaseMutation):fulfillment.tracking_number = tracking_numberfulfillment.save()order = fulfillment.order+ app = load_app(info.context)fulfillment_tracking_updated(fulfillment,info.context.user,- info.context.app,+ app,tracking_number,info.context.plugins,)diff --git a/saleor/graphql/order/mutations/order_add_note.py b/saleor/graphql/order/mutations/order_add_note.pyindex 34a7e1208e..86ba3c1a30 100644--- a/saleor/graphql/order/mutations/order_add_note.py+++ b/saleor/graphql/order/mutations/order_add_note.py@@ -6,6 +6,7 @@ from ....core.permissions import OrderPermissionsfrom ....core.tracing import traced_atomic_transactionfrom ....order import eventsfrom ....order.error_codes import OrderErrorCode+from ...app.dataloaders import load_appfrom ...core.mutations import BaseMutationfrom ...core.types import OrderErrorfrom ...core.utils import validate_required_string_field@@ -59,10 +60,11 @@ class OrderAddNote(BaseMutation):def perform_mutation(cls, _root, info, **data):order = cls.get_node_or_error(info, data.get("id"), only_type=Order)cleaned_input = cls.clean_input(info, order, data)+ app = load_app(info.context)event = events.order_note_added_event(order=order,user=info.context.user,- app=info.context.app,+ app=app,message=cleaned_input["message"],)func = get_webhook_handler_by_order_status(order.status, info)diff --git a/saleor/graphql/order/mutations/order_cancel.py b/saleor/graphql/order/mutations/order_cancel.pyindex 97554a33e2..e49b45389a 100644--- a/saleor/graphql/order/mutations/order_cancel.py+++ b/saleor/graphql/order/mutations/order_cancel.py@@ -6,6 +6,7 @@ from ....core.tracing import traced_atomic_transactionfrom ....giftcard.utils import deactivate_order_gift_cardsfrom ....order.actions import cancel_orderfrom ....order.error_codes import OrderErrorCode+from ...app.dataloaders import load_appfrom ...core.mutations import BaseMutationfrom ...core.types import OrderErrorfrom ..types import Order@@ -41,7 +42,7 @@ class OrderCancel(BaseMutation):order = cls.get_node_or_error(info, data.get("id"), only_type=Order)clean_order_cancel(order)user = info.context.user- app = info.context.app+ app = load_app(info.context)cancel_order(order=order,user=user,diff --git a/saleor/graphql/order/mutations/order_capture.py b/saleor/graphql/order/mutations/order_capture.pyindex 9a1c35ead0..0141f6e2be 100644--- a/saleor/graphql/order/mutations/order_capture.py+++ b/saleor/graphql/order/mutations/order_capture.py@@ -7,6 +7,7 @@ from ....order.error_codes import OrderErrorCodefrom ....order.fetch import fetch_order_infofrom ....payment import PaymentError, TransactionKind, gatewayfrom ....payment.gateway import request_charge_action+from ...app.dataloaders import load_appfrom ...core.mutations import BaseMutationfrom ...core.scalars import PositiveDecimalfrom ...core.types import OrderError@@ -56,6 +57,7 @@ class OrderCapture(BaseMutation):order = cls.get_node_or_error(info, data.get("id"), only_type=Order)+ app = load_app(info.context)if payment_transactions := list(order.payment_transactions.all()):try:# We use the last transaction as we don't have a possibility to@@ -67,7 +69,7 @@ class OrderCapture(BaseMutation):charge_value=amount,channel_slug=order.channel.slug,user=info.context.user,- app=info.context.app,+ app=app,)except PaymentError as e:raise ValidationError(@@ -81,7 +83,7 @@ class OrderCapture(BaseMutation):transaction = try_payment_action(order,info.context.user,- info.context.app,+ app,payment,gateway.capture,payment,@@ -96,7 +98,7 @@ class OrderCapture(BaseMutation):order_captured(order_info,info.context.user,- info.context.app,+ app,amount,payment,info.context.plugins,diff --git a/saleor/graphql/order/mutations/order_confirm.py b/saleor/graphql/order/mutations/order_confirm.pyindex f546c28cea..ecd643e677 100644--- a/saleor/graphql/order/mutations/order_confirm.py+++ b/saleor/graphql/order/mutations/order_confirm.py@@ -10,6 +10,7 @@ from ....order.error_codes import OrderErrorCodefrom ....order.fetch import fetch_order_infofrom ....payment import PaymentError, gatewayfrom ....payment.gateway import request_charge_action+from ...app.dataloaders import load_appfrom ...core.mutations import ModelMutationfrom ...core.types import OrderErrorfrom ..types import Order@@ -62,6 +63,8 @@ class OrderConfirm(ModelMutation):order_info = fetch_order_info(order)payment = order_info.paymentmanager = info.context.plugins+ app = load_app(info.context)+if payment_transactions := list(order.payment_transactions.all()):try:# We use the last transaction as we don't have a possibility to@@ -73,7 +76,7 @@ class OrderConfirm(ModelMutation):charge_value=payment_transaction.authorized_value,channel_slug=order.channel.slug,user=info.context.user,- app=info.context.app,+ app=app,)except PaymentError as e:raise ValidationError(@@ -88,7 +91,7 @@ class OrderConfirm(ModelMutation):lambda: order_captured(order_info,info.context.user,- info.context.app,+ app,payment.total,payment,manager,@@ -99,7 +102,7 @@ class OrderConfirm(ModelMutation):lambda: order_confirmed(order,info.context.user,- info.context.app,+ app,manager,send_confirmation_email=True,)diff --git a/saleor/graphql/order/mutations/order_discount_add.py b/saleor/graphql/order/mutations/order_discount_add.pyindex 6fbcd83645..a5bb8b4aaa 100644--- a/saleor/graphql/order/mutations/order_discount_add.py+++ b/saleor/graphql/order/mutations/order_discount_add.py@@ -7,6 +7,7 @@ from ....order import eventsfrom ....order.calculations import fetch_order_prices_if_expiredfrom ....order.error_codes import OrderErrorCodefrom ....order.utils import create_order_discount_for_order, get_order_discounts+from ...app.dataloaders import load_appfrom ...core.types import OrderErrorfrom ..types import Orderfrom .order_discount_common import OrderDiscountCommon, OrderDiscountCommonInput@@ -63,8 +64,9 @@ class OrderDiscountAdd(OrderDiscountCommon):order_discount = create_order_discount_for_order(order, reason, value_type, value)+ app = load_app(info.context)- # Calling refreshing prices because it's set proper discount amount on+ # Calling refreshing prices because it's set proper discount amount# on OrderDiscount.order, _ = fetch_order_prices_if_expired(order, manager, force_update=True)order_discount.refresh_from_db()@@ -72,7 +74,7 @@ class OrderDiscountAdd(OrderDiscountCommon):events.order_discount_added_event(order=order,user=info.context.user,- app=info.context.app,+ app=app,order_discount=order_discount,)return OrderDiscountAdd(order=order)diff --git a/saleor/graphql/order/mutations/order_discount_delete.py b/saleor/graphql/order/mutations/order_discount_delete.pyindex ee5723402e..570bb7a578 100644--- a/saleor/graphql/order/mutations/order_discount_delete.py+++ b/saleor/graphql/order/mutations/order_discount_delete.py@@ -5,6 +5,7 @@ from ....core.tracing import traced_atomic_transactionfrom ....order import eventsfrom ....order.search import update_order_search_vectorfrom ....order.utils import invalidate_order_prices, remove_order_discount_from_order+from ...app.dataloaders import load_appfrom ...core.types import OrderErrorfrom ..types import Orderfrom .order_discount_common import OrderDiscountCommon@@ -31,13 +32,15 @@ class OrderDiscountDelete(OrderDiscountCommon):info, data.get("discount_id"), only_type="OrderDiscount")order = order_discount.order+ app = load_app(info.context)+cls.validate_order(info, order)remove_order_discount_from_order(order, order_discount)events.order_discount_deleted_event(order=order,user=info.context.user,- app=info.context.app,+ app=app,order_discount=order_discount,)diff --git a/saleor/graphql/order/mutations/order_discount_update.py b/saleor/graphql/order/mutations/order_discount_update.pyindex ff35846029..d6cf99800e 100644--- a/saleor/graphql/order/mutations/order_discount_update.py+++ b/saleor/graphql/order/mutations/order_discount_update.py@@ -6,6 +6,7 @@ from ....core.permissions import OrderPermissionsfrom ....core.tracing import traced_atomic_transactionfrom ....order import eventsfrom ....order.calculations import fetch_order_prices_if_expired+from ...app.dataloaders import load_appfrom ...core.types import OrderErrorfrom ..types import Orderfrom .order_discount_common import OrderDiscountCommon, OrderDiscountCommonInput@@ -63,14 +64,15 @@ class OrderDiscountUpdate(OrderDiscountCommon):or order_discount_before_update.value != value):# call update event only when we changed the type or value of the discount- # Calling refreshing prices because it's set proper discount amount on+ # Calling refreshing prices because it's set proper discount amount# on OrderDiscount.fetch_order_prices_if_expired(order, manager, force_update=True)order_discount.refresh_from_db()+ app = load_app(info.context)events.order_discount_updated_event(order=order,user=info.context.user,- app=info.context.app,+ app=app,order_discount=order_discount,old_order_discount=order_discount_before_update,)diff --git a/saleor/graphql/order/mutations/order_fulfill.py b/saleor/graphql/order/mutations/order_fulfill.pyindex 4487e4bcff..af4a4138f9 100644--- a/saleor/graphql/order/mutations/order_fulfill.py+++ b/saleor/graphql/order/mutations/order_fulfill.py@@ -10,6 +10,7 @@ from ....core.tracing import traced_atomic_transactionfrom ....order import models as order_modelsfrom ....order.actions import create_fulfillmentsfrom ....order.error_codes import OrderErrorCode+from ...app.dataloaders import load_appfrom ...core.descriptions import ADDED_IN_36from ...core.mutations import BaseMutationfrom ...core.types import NonNullList, OrderError@@ -245,7 +246,7 @@ class OrderFulfill(BaseMutation):context = info.contextuser = context.user if not context.user.is_anonymous else None- app = context.app+ app = load_app(info.context)manager = context.pluginslines_for_warehouses = cleaned_input["lines_for_warehouses"]notify_customer = cleaned_input.get("notify_customer", True)diff --git a/saleor/graphql/order/mutations/order_line_delete.py b/saleor/graphql/order/mutations/order_line_delete.pyindex c460a68ab5..17c6bd7c98 100644--- a/saleor/graphql/order/mutations/order_line_delete.py+++ b/saleor/graphql/order/mutations/order_line_delete.py@@ -12,6 +12,7 @@ from ....order.utils import (invalidate_order_prices,recalculate_order_weight,)+from ...app.dataloaders import load_appfrom ...core.mutations import BaseMutationfrom ...core.types import OrderErrorfrom ..types import Order, OrderLine@@ -74,10 +75,11 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):"updated_at",]# Create the removal event+ app = load_app(info.context)events.order_removed_products_event(order=order,user=info.context.user,- app=info.context.app,+ app=app,order_lines=[line],)diff --git a/saleor/graphql/order/mutations/order_line_discount_remove.py b/saleor/graphql/order/mutations/order_line_discount_remove.pyindex 3cea998705..234ad0231f 100644--- a/saleor/graphql/order/mutations/order_line_discount_remove.py+++ b/saleor/graphql/order/mutations/order_line_discount_remove.py@@ -4,6 +4,7 @@ from ....core.permissions import OrderPermissionsfrom ....core.tracing import traced_atomic_transactionfrom ....order import eventsfrom ....order.utils import invalidate_order_prices, remove_discount_from_order_line+from ...app.dataloaders import load_appfrom ...core.types import OrderErrorfrom ..types import Order, OrderLinefrom .order_discount_common import OrderDiscountCommon@@ -45,11 +46,11 @@ class OrderLineDiscountRemove(OrderDiscountCommon):remove_discount_from_order_line(order_line, order, manager=info.context.plugins, tax_included=tax_included)-+ app = load_app(info.context)events.order_line_discount_removed_event(order=order,user=info.context.user,- app=info.context.app,+ app=app,line=order_line,)diff --git a/saleor/graphql/order/mutations/order_line_discount_update.py b/saleor/graphql/order/mutations/order_line_discount_update.pyindex 2a8a1f8fe9..94dd006a2e 100644--- a/saleor/graphql/order/mutations/order_line_discount_update.py+++ b/saleor/graphql/order/mutations/order_line_discount_update.py@@ -6,6 +6,7 @@ from ....core.permissions import OrderPermissionsfrom ....core.tracing import traced_atomic_transactionfrom ....order import eventsfrom ....order.utils import invalidate_order_prices, update_discount_for_order_line+from ...app.dataloaders import load_appfrom ...core.types import OrderErrorfrom ..types import Order, OrderLinefrom .order_discount_common import OrderDiscountCommon, OrderDiscountCommonInput@@ -75,10 +76,11 @@ class OrderLineDiscountUpdate(OrderDiscountCommon):or order_line_before_update.unit_discount_type != value_type):# Create event only when we change type or value of the discount+ app = load_app(info.context)events.order_line_discount_updated_event(order=order,user=info.context.user,- app=info.context.app,+ app=app,line=order_line,line_before_update=order_line_before_update,)diff --git a/saleor/graphql/order/mutations/order_line_update.py b/saleor/graphql/order/mutations/order_line_update.pyindex 308800236f..acd24088f6 100644--- a/saleor/graphql/order/mutations/order_line_update.py+++ b/saleor/graphql/order/mutations/order_line_update.py@@ -13,6 +13,7 @@ from ....order.utils import (invalidate_order_prices,recalculate_order_weight,)+from ...app.dataloaders import load_appfrom ...core.mutations import ModelMutationfrom ...core.types import OrderErrorfrom ..types import Order, OrderLine@@ -70,10 +71,11 @@ class OrderLineUpdate(EditableOrderValidationMixin, ModelMutation):variant=instance.variant,warehouse_pk=warehouse_pk,)+ app = load_app(info.context)try:change_order_line_quantity(info.context.user,- info.context.app,+ app,line_info,instance.old_quantity,instance.quantity,diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.pyindex 6d097c9f71..2183406ae1 100644--- a/saleor/graphql/order/mutations/order_lines_create.py+++ b/saleor/graphql/order/mutations/order_lines_create.py@@ -17,6 +17,7 @@ from ....order.utils import (invalidate_order_prices,recalculate_order_weight,)+from ...app.dataloaders import load_appfrom ...core.mutations import BaseMutationfrom ...core.types import NonNullList, OrderErrorfrom ...product.types import ProductVariant@@ -151,12 +152,13 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):lines_to_add = cls.validate_lines(info, data, existing_lines_info)variants = [line.variant for line in lines_to_add]cls.validate_variants(order, variants)+ app = load_app(info.context)added_lines = cls.add_lines_to_order(order,lines_to_add,info.context.user,- info.context.app,+ app,info.context.plugins,info.context.site.settings,info.context.discounts,@@ -166,7 +168,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):events.order_added_products_event(order=order,user=info.context.user,- app=info.context.app,+ app=app,order_lines=added_lines,)diff --git a/saleor/graphql/order/mutations/order_mark_as_paid.py b/saleor/graphql/order/mutations/order_mark_as_paid.pyindex 4e594c8f60..0cec34d798 100644--- a/saleor/graphql/order/mutations/order_mark_as_paid.py+++ b/saleor/graphql/order/mutations/order_mark_as_paid.py@@ -6,6 +6,7 @@ from ....order.actions import clean_mark_order_as_paid, mark_order_as_paidfrom ....order.calculations import fetch_order_prices_if_expiredfrom ....order.error_codes import OrderErrorCodefrom ....order.search import update_order_search_vector+from ...app.dataloaders import load_appfrom ...core.mutations import BaseMutationfrom ...core.types import OrderErrorfrom ..types import Order@@ -43,7 +44,7 @@ class OrderMarkAsPaid(BaseMutation):transaction_reference = data.get("transaction_reference")cls.clean_billing_address(order)user = info.context.user- app = info.context.app+ app = load_app(info.context)try_payment_action(order, user, app, None, clean_mark_order_as_paid, order)mark_order_as_paid(diff --git a/saleor/graphql/order/mutations/order_refund.py b/saleor/graphql/order/mutations/order_refund.pyindex e009fd5cbe..ca32091941 100644--- a/saleor/graphql/order/mutations/order_refund.py+++ b/saleor/graphql/order/mutations/order_refund.py@@ -8,6 +8,7 @@ from ....order.actions import order_refundedfrom ....order.error_codes import OrderErrorCodefrom ....payment import PaymentError, TransactionKind, gatewayfrom ....payment.gateway import request_refund_action+from ...app.dataloaders import load_appfrom ...core.mutations import BaseMutationfrom ...core.scalars import PositiveDecimalfrom ...core.types import OrderError@@ -69,6 +70,7 @@ class OrderRefund(BaseMutation):order = cls.get_node_or_error(info, data.get("id"), only_type=Order)clean_order_refund(order)+ app = load_app(info.context)if payment_transactions := list(order.payment_transactions.all()):# We use the last transaction as we don't have a possibility to@@ -80,7 +82,7 @@ class OrderRefund(BaseMutation):refund_value=amount,channel_slug=order.channel.slug,user=info.context.user,- app=info.context.app,+ app=app,)except PaymentError as e:raise ValidationError(@@ -94,7 +96,7 @@ class OrderRefund(BaseMutation):transaction = try_payment_action(order,info.context.user,- info.context.app,+ app,payment,gateway.refund,payment,@@ -108,7 +110,7 @@ class OrderRefund(BaseMutation):order_refunded(order,info.context.user,- info.context.app,+ app,amount,payment,info.context.plugins,diff --git a/saleor/graphql/order/mutations/order_void.py b/saleor/graphql/order/mutations/order_void.pyindex 38a907cb8d..efb09ddfde 100644--- a/saleor/graphql/order/mutations/order_void.py+++ b/saleor/graphql/order/mutations/order_void.py@@ -6,6 +6,7 @@ from ....order.actions import order_voidedfrom ....order.error_codes import OrderErrorCodefrom ....payment import PaymentError, TransactionKind, gatewayfrom ....payment.gateway import request_void_action+from ...app.dataloaders import load_appfrom ...core.mutations import BaseMutationfrom ...core.types import OrderErrorfrom ..types import Order@@ -41,6 +42,7 @@ class OrderVoid(BaseMutation):@classmethoddef perform_mutation(cls, _root, info, **data):order = cls.get_node_or_error(info, data.get("id"), only_type=Order)+ app = load_app(info.context)if payment_transactions := list(order.payment_transactions.all()):# We use the last transaction as we don't have a possibility to@@ -51,7 +53,7 @@ class OrderVoid(BaseMutation):info.context.plugins,channel_slug=order.channel.slug,user=info.context.user,- app=info.context.app,+ app=app,)except PaymentError as e:raise ValidationError(@@ -64,7 +66,7 @@ class OrderVoid(BaseMutation):transaction = try_payment_action(order,info.context.user,- info.context.app,+ app,payment,gateway.void,payment,@@ -77,7 +79,7 @@ class OrderVoid(BaseMutation):order_voided(order,info.context.user,- info.context.app,+ app,payment,info.context.plugins,)diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex 3171334a91..1a5a12a790 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -34,6 +34,7 @@ from ...payment.gateway import ()from ...payment.utils import create_payment, is_currency_supportedfrom ..account.i18n import I18nMixin+from ..app.dataloaders import load_appfrom ..channel.utils import validate_channelfrom ..checkout.mutations.utils import get_checkoutfrom ..checkout.types import Checkout@@ -810,10 +811,11 @@ class TransactionCreate(BaseMutation):else:transaction_data["order_id"] = order_or_checkout_instance.pkif transaction_event_data:+ app = load_app(info.context)transaction_event(order=order_or_checkout_instance,user=info.context.user,- app=info.context.app,+ app=app,reference=transaction_event_data.get("reference", ""),status=transaction_event_data["status"],name=transaction_event_data.get("name", ""),@@ -921,10 +923,11 @@ class TransactionUpdate(TransactionCreate):if transaction_event_data := data.get("transaction_event"):cls.create_transaction_event(transaction_event_data, instance)if instance.order_id:+ app = load_app(info.context)transaction_event(order=instance.order,user=info.context.user,- app=info.context.app,+ app=app,reference=transaction_event_data.get("reference", ""),status=transaction_event_data["status"],name=transaction_event_data.get("name", ""),@@ -1001,10 +1004,11 @@ class TransactionRequestAction(BaseMutation):if transaction.order_idelse transaction.checkout.channel.slug)+ app = load_app(info.context)action_kwargs = {"channel_slug": channel_slug,"user": info.context.user,- "app": info.context.app,+ "app": app,"transaction": transaction,"manager": info.context.plugins,}diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.pyindex c2cf6079e1..d072e03f40 100644--- a/saleor/graphql/product/bulk_mutations/products.py+++ b/saleor/graphql/product/bulk_mutations/products.py@@ -28,6 +28,7 @@ from ....product.utils import delete_categoriesfrom ....product.utils.variants import generate_and_set_variant_namefrom ....warehouse import models as warehouse_modelsfrom ....warehouse.error_codes import StockErrorCode+from ...app.dataloaders import load_appfrom ...channel import ChannelContextfrom ...channel.types import Channelfrom ...core.mutations import BaseMutation, ModelBulkDeleteMutation, ModelMutation@@ -163,10 +164,11 @@ class ProductBulkDelete(ModelBulkDeleteMutation):pk__in=draft_order_lines_data.line_pks).delete()+ app = load_app(info.context)# run order event for deleted linesfor order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():order_events.order_line_product_removed_event(- order, info.context.user, info.context.app, order_lines+ order, info.context.user, app, order_lines)order_pks = draft_order_lines_data.order_pks@@ -627,10 +629,11 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):pk__in=draft_order_lines_data.line_pks).delete()+ app = load_app(info.context)# run order event for deleted linesfor order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():order_events.order_line_variant_removed_event(- order, info.context.user, info.context.app, order_lines+ order, info.context.user, app, order_lines)order_pks = draft_order_lines_data.order_pksdiff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex d59d4ed4f5..4596130d97 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -33,6 +33,7 @@ from ....product.utils import delete_categories, get_products_ids_without_varianfrom ....product.utils.variants import generate_and_set_variant_namefrom ....thumbnail import models as thumbnail_modelsfrom ....warehouse.management import deactivate_preorder_for_variant+from ...app.dataloaders import load_appfrom ...attribute.types import AttributeValueInputfrom ...attribute.utils import AttributeAssignmentMixin, AttrValuesInputfrom ...channel import ChannelContext@@ -764,10 +765,11 @@ class ProductDelete(ModelDeleteMutation):pk__in=draft_order_lines_data.line_pks).delete()+ app = load_app(info.context)# run order event for deleted linesfor order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():order_events.order_line_product_removed_event(- order, info.context.user, info.context.app, order_lines+ order, info.context.user, app, order_lines)order_pks = draft_order_lines_data.order_pks@@ -1180,9 +1182,10 @@ class ProductVariantDelete(ModelDeleteMutation):).delete()# run order event for deleted lines+ app = load_app(info.context)for order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():order_events.order_line_variant_removed_event(- order, info.context.user, info.context.app, order_lines+ order, info.context.user, app, order_lines)order_pks = draft_order_lines_data.order_pksdiff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex 801202858d..77b8870f3e 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -11909,7 +11909,6 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_success(settings,variant,warehouses,- info,):Stock.objects.bulk_create(@@ -11920,14 +11919,14 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_success()settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- info.context.plugins = get_plugins_manager()+ plugins = get_plugins_manager()stocks_data = [{"quantity": 10, "warehouse": "123"},]assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 0ProductVariantStocksUpdate.update_or_create_variant_stocks(- variant, stocks_data, warehouses, info.context.plugins+ variant, stocks_data, warehouses, plugins)assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 10@@ -11947,7 +11946,6 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_failed(settings,variant,warehouses,- info,):Stock.objects.bulk_create(@@ -11958,14 +11956,14 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_failed()settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- info.context.plugins = get_plugins_manager()+ plugins = get_plugins_manager()stocks_data = [{"quantity": 0, "warehouse": "123"},]assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 0ProductVariantStocksUpdate.update_or_create_variant_stocks(- variant, stocks_data, warehouses, info.context.plugins+ variant, stocks_data, warehouses, plugins)assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 0@@ -11985,7 +11983,6 @@ def test_update_or_create_variant_stocks_with_out_of_stock_webhook_only(settings,variant,warehouses,- info,):Stock.objects.bulk_create(@@ -11997,7 +11994,7 @@ def test_update_or_create_variant_stocks_with_out_of_stock_webhook_only(settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- info.context.plugins = get_plugins_manager()+ plugins = get_plugins_manager()stocks_data = [{"quantity": 0, "warehouse": "123"},@@ -12007,7 +12004,7 @@ def test_update_or_create_variant_stocks_with_out_of_stock_webhook_only(assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 10ProductVariantStocksUpdate.update_or_create_variant_stocks(- variant, stocks_data, warehouses, info.context.plugins+ variant, stocks_data, warehouses, plugins)assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 2diff --git a/saleor/graphql/tests/fixtures.py b/saleor/graphql/tests/fixtures.pyindex 13ae98187b..ae8dbab1cb 100644--- a/saleor/graphql/tests/fixtures.py+++ b/saleor/graphql/tests/fixtures.py@@ -152,7 +152,12 @@ def api_client():@pytest.fixturedef schema_context():- params = {"user": AnonymousUser(), "app": None, "plugins": get_plugins_manager()}+ params = {+ "user": AnonymousUser(),+ "app": None,+ "plugins": get_plugins_manager(),+ "auth_token": "",+ }return graphene.types.Context(**params)@@ -161,6 +166,16 @@ def info(schema_context):return Mock(context=schema_context)+def anonymous_user():+ return AnonymousUser()+++def anonymous_plugins():+ return get_plugins_manager()++class LoggingHandler(logging.Handler):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)diff --git a/saleor/graphql/webhook/mutations.py b/saleor/graphql/webhook/mutations.pyindex a62255b24c..ff569c3a99 100644--- a/saleor/graphql/webhook/mutations.py+++ b/saleor/graphql/webhook/mutations.py@@ -4,6 +4,7 @@ from django.core.exceptions import ValidationErrorfrom ...core.permissions import AppPermission, AuthorizationFiltersfrom ...webhook import modelsfrom ...webhook.error_codes import WebhookErrorCode+from ..app.dataloaders import load_appfrom ..core.descriptions import ADDED_IN_32, DEPRECATED_IN_3X_INPUT, PREVIEW_FEATUREfrom ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ..core.types import NonNullList, WebhookError@@ -110,7 +111,7 @@ class WebhookCreate(ModelMutation):@classmethoddef get_instance(cls, info, **data):instance = super().get_instance(info, **data)- app = info.context.app+ app = load_app(info.context)instance.app = appreturn instance@@ -245,7 +246,7 @@ class WebhookDelete(ModelDeleteMutation):node_id = data["id"]object_id = cls.get_global_id_or_error(node_id)- app = info.context.app+ app = load_app(info.context)if app:if not app.is_active:raise ValidationError(diff --git a/saleor/graphql/webhook/resolvers.py b/saleor/graphql/webhook/resolvers.pyindex 589c0d35fc..c5b50b6c5c 100644--- a/saleor/graphql/webhook/resolvers.py+++ b/saleor/graphql/webhook/resolvers.py@@ -9,12 +9,13 @@ from ...core.tracing import traced_resolverfrom ...webhook import models, payloadsfrom ...webhook.deprecated_event_types import WebhookEventTypefrom ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType+from ..app.dataloaders import load_appfrom ..core.utils import from_global_id_or_errorfrom .types import Webhook, WebhookEventdef resolve_webhook(info, id):- app = info.context.app+ app = load_app(info.context)_, id = from_global_id_or_error(id, Webhook)if app:return app.webhooks.filter(id=id).first()@@ -33,7 +34,7 @@ def resolve_webhook_events():@traced_resolverdef resolve_sample_payload(info, event_name):- app = info.context.app+ app = load_app(info.context)required_permission = WebhookEventAsyncType.PERMISSIONS.get(event_name, WebhookEventSyncType.PERMISSIONS.get(event_name))diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.pyindex 326fcf3a7c..7d272e5176 100644--- a/saleor/order/tests/test_notifications.py+++ b/saleor/order/tests/test_notifications.py@@ -385,7 +385,8 @@ def test_send_email_order_confirmation_for_cc(def test_send_confirmation_emails_without_addresses_for_payment(mocked_notify,site_settings,- info,+ anonymous_user,+ anonymous_plugins,digital_content,payment_dummy,):@@ -397,11 +398,11 @@ def test_send_confirmation_emails_without_addresses_for_payment()line = add_variant_to_order(- order,- line_data,- user=info.context.user,- app=info.context.app,- manager=info.context.plugins,+ order=order,+ line_data=line_data,+ user=anonymous_user,+ app=None,+ manager=anonymous_plugins,site_settings=site_settings,)DigitalContentUrl.objects.create(content=digital_content, line=line)@@ -412,7 +413,7 @@ def test_send_confirmation_emails_without_addresses_for_payment(order.save(update_fields=["shipping_address", "shipping_method", "billing_address"])order_info = fetch_order_info(order)- notifications.send_payment_confirmation(order_info, info.context.plugins)+ notifications.send_payment_confirmation(order_info, anonymous_plugins)expected_payload = {"order": get_default_order_payload(order),@@ -437,7 +438,12 @@ def test_send_confirmation_emails_without_addresses_for_payment(@mock.patch("saleor.plugins.manager.PluginsManager.notify")def test_send_confirmation_emails_without_addresses_for_order(- mocked_notify, order, site_settings, digital_content, info+ mocked_notify,+ order,+ site_settings,+ digital_content,+ anonymous_user,+ anonymous_plugins,):assert not order.lines.count()@@ -448,11 +454,11 @@ def test_send_confirmation_emails_without_addresses_for_order()line = add_variant_to_order(- order,- line_data,- user=info.context.user,- app=info.context.app,- manager=info.context.plugins,+ order=order,+ line_data=line_data,+ user=anonymous_user,+ app=None,+ manager=anonymous_plugins,site_settings=site_settings,)DigitalContentUrl.objects.create(content=digital_content, line=line)@@ -465,9 +471,7 @@ def test_send_confirmation_emails_without_addresses_for_order(redirect_url = "https://www.example.com"- notifications.send_order_confirmation(- order_info, redirect_url, info.context.plugins- )+ notifications.send_order_confirmation(order_info, redirect_url, anonymous_plugins)expected_payload = {"order": get_default_order_payload(order, redirect_url),diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.pyindex 7b20634c3c..2b61048dcf 100644--- a/saleor/order/tests/test_order.py+++ b/saleor/order/tests/test_order.py@@ -90,7 +90,13 @@ def test_recalculate_order_keeps_weight_unit(order_with_lines):def test_add_variant_to_order_adds_line_for_new_variant(- order_with_lines, product, product_translation_fr, settings, info, site_settings+ order_with_lines,+ product,+ product_translation_fr,+ settings,+ anonymous_user,+ anonymous_plugins,+ site_settings,):order = order_with_linesvariant = product.variants.get()@@ -99,12 +105,12 @@ def test_add_variant_to_order_adds_line_for_new_variant(line_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=1)add_variant_to_order(- order,- line_data,- info.context.user,- info.context.app,- info.context.plugins,- site_settings,+ order=order,+ line_data=line_data,+ user=anonymous_user,+ app=None,+ manager=anonymous_plugins,+ site_settings=site_settings,)line = order.lines.last()@@ -128,7 +134,8 @@ def test_add_variant_to_order_adds_line_for_new_variant_on_sale(sale,discount_info,settings,- info,+ anonymous_user,+ anonymous_plugins,site_settings,):order = order_with_lines@@ -140,13 +147,13 @@ def test_add_variant_to_order_adds_line_for_new_variant_on_sale(line_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=1)add_variant_to_order(- order,- line_data,- info.context.user,- info.context.app,- info.context.plugins,- site_settings,- [discount_info],+ order=order,+ line_data=line_data,+ user=anonymous_user,+ app=None,+ manager=anonymous_plugins,+ site_settings=site_settings,+ discounts=[discount_info],)line = order.lines.last()@@ -171,7 +178,13 @@ def test_add_variant_to_order_adds_line_for_new_variant_on_sale(def test_add_variant_to_draft_order_adds_line_for_variant_with_price_0(- order_with_lines, product, product_translation_fr, settings, info, site_settings+ order_with_lines,+ product,+ product_translation_fr,+ settings,+ anonymous_user,+ anonymous_plugins,+ site_settings,):order = order_with_linesvariant = product.variants.get()@@ -184,12 +197,12 @@ def test_add_variant_to_draft_order_adds_line_for_variant_with_price_0(line_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=1)add_variant_to_order(- order,- line_data,- info.context.user,- info.context.app,- info.context.plugins,- site_settings,+ order=order,+ line_data=line_data,+ user=anonymous_user,+ app=None,+ manager=anonymous_plugins,+ site_settings=site_settings,)line = order.lines.last()@@ -203,7 +216,11 @@ def test_add_variant_to_draft_order_adds_line_for_variant_with_price_0(def test_add_variant_to_order_not_allocates_stock_for_new_variant(- order_with_lines, product, info, site_settings+ order_with_lines,+ product,+ anonymous_user,+ anonymous_plugins,+ site_settings,):variant = product.variants.get()stock = Stock.objects.get(product_variant=variant)@@ -212,12 +229,12 @@ def test_add_variant_to_order_not_allocates_stock_for_new_variant(line_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=1)add_variant_to_order(- order_with_lines,- line_data,- info.context.user,- info.context.app,- info.context.plugins,- site_settings,+ order=order_with_lines,+ line_data=line_data,+ user=anonymous_user,+ app=None,+ manager=anonymous_plugins,+ site_settings=site_settings,)stock.refresh_from_db()@@ -225,7 +242,7 @@ def test_add_variant_to_order_not_allocates_stock_for_new_variant(def test_add_variant_to_order_edits_line_for_existing_variant(- order_with_lines, info, site_settings+ order_with_lines, anonymous_user, anonymous_plugins, site_settings):existing_line = order_with_lines.lines.first()variant = existing_line.variant@@ -236,12 +253,12 @@ def test_add_variant_to_order_edits_line_for_existing_variant()add_variant_to_order(- order_with_lines,- line_data,- info.context.user,- info.context.app,- info.context.plugins,- site_settings,+ order=order_with_lines,+ line_data=line_data,+ user=anonymous_user,+ app=None,+ manager=anonymous_plugins,+ site_settings=site_settings,)existing_line.refresh_from_db()@@ -252,7 +269,7 @@ def test_add_variant_to_order_edits_line_for_existing_variant(def test_add_variant_to_order_not_allocates_stock_for_existing_variant(- order_with_lines, info, site_settings+ order_with_lines, anonymous_user, anonymous_plugins, site_settings):existing_line = order_with_lines.lines.first()variant = existing_line.variant@@ -265,12 +282,12 @@ def test_add_variant_to_order_not_allocates_stock_for_existing_variant()add_variant_to_order(- order_with_lines,- line_data,- info.context.user,- info.context.app,- info.context.plugins,- site_settings,+ order=order_with_lines,+ line_data=line_data,+ user=anonymous_user,+ app=None,+ manager=anonymous_plugins,+ site_settings=site_settings,)stock.refresh_from_db()@@ -542,17 +559,19 @@ def test_calculate_order_weight(order_with_lines):assert calculated_weight == order_weight-def test_order_weight_add_more_variant(order_with_lines, info, site_settings):+def test_order_weight_add_more_variant(+ order_with_lines, anonymous_user, anonymous_plugins, site_settings+):variant = order_with_lines.lines.first().variantline_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=2)add_variant_to_order(- order_with_lines,- line_data,- info.context.user,- info.context.app,- info.context.plugins,- site_settings,+ order=order_with_lines,+ line_data=line_data,+ user=anonymous_user,+ app=None,+ manager=anonymous_plugins,+ site_settings=site_settings,)order_with_lines.refresh_from_db()@@ -561,17 +580,23 @@ def test_order_weight_add_more_variant(order_with_lines, info, site_settings):)-def test_order_weight_add_new_variant(order_with_lines, product, info, site_settings):+def test_order_weight_add_new_variant(+ order_with_lines,+ product,+ anonymous_user,+ anonymous_plugins,+ site_settings,+):variant = product.variants.first()line_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=2)add_variant_to_order(- order_with_lines,- line_data,- info.context.user,- info.context.app,- info.context.plugins,- site_settings,+ order=order_with_lines,+ line_data=line_data,+ user=anonymous_user,+ app=None,+ manager=anonymous_plugins,+ site_settings=site_settings,)order_with_lines.refresh_from_db()@@ -605,7 +630,11 @@ def test_order_weight_delete_line(lines_info):def test_get_order_weight_non_existing_product(- order_with_lines, product, info, site_settings+ order_with_lines,+ product,+ anonymous_user,+ anonymous_plugins,+ site_settings,):# Removing product should not affect order's weightorder = order_with_lines@@ -613,12 +642,12 @@ def test_get_order_weight_non_existing_product(line_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=1)add_variant_to_order(- order,- line_data,- info.context.user,- info.context.app,- info.context.plugins,- site_settings,+ order=order,+ line_data=line_data,+ user=anonymous_user,+ app=None,+ manager=anonymous_plugins,+ site_settings=site_settings,)old_weight = order.get_total_weight()diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 91ea1760a2..139c2adfdc 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -944,8 +944,10 @@ def _update_order_total_charged(order: Order):sum(order.payments.values_list("captured_amount", flat=True)) # type: ignoreor 0)- order.total_charged_amount += sum(- order.payment_transactions.values_list("charged_value", flat=True) # type: ignore # noqa: E501+ order.total_charged_amount += sum( # type: ignore+ order.payment_transactions.values_list( # type: ignore+ "charged_value", flat=True+ ))diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.pyindex d5e4fd5cd6..d37b05d78b 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py@@ -43,12 +43,16 @@ from .payloads import (@freeze_time("2022-05-12 12:00:00")@pytest.mark.parametrize("requestor_type", ["user", "app", None, "anonymous"])def test_subscription_query_with_meta(- requestor_type, voucher, staff_user, app, subscription_voucher_webhook_with_meta+ requestor_type,+ voucher,+ staff_user,+ app_with_token,+ subscription_voucher_webhook_with_meta,):# givenrequestor_map = {"user": staff_user,- "app": app,+ "app": app_with_token,None: None,"anonymous": AnonymousUser(),}diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 3babbcac0f..24c6213019 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -28,7 +28,7 @@ from PIL import Imagefrom prices import Money, TaxedMoney, fixed_discountfrom ..account.models import Address, StaffNotificationRecipient, User-from ..app.models import App, AppExtension, AppInstallation+from ..app.models import App, AppExtension, AppInstallation, AppTokenfrom ..app.types import AppExtensionMount, AppTypefrom ..attribute import AttributeEntityType, AttributeInputType, AttributeTypefrom ..attribute.models import (@@ -2483,7 +2483,6 @@ def product_with_variant_with_file_attribute(@pytest.fixturedef product_with_multiple_values_attributes(product, product_type, category) -> Product:-attribute = Attribute.objects.create(slug="modes",name="Available Modes",@@ -4385,7 +4384,8 @@ def draft_order_with_fixed_discount_order(draft_order):value_type=DiscountValueType.FIXED,value=value,reason="Discount reason",- amount=(draft_order.undiscounted_total - draft_order.total).gross, # type: ignore+ amount=(draft_order.undiscounted_total - draft_order.total).gross,+ # type: ignore)draft_order.save()return draft_order