Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Get rid of using get_plugins_manager method in order actions
IKarbowiakbae88491a85e
diff --git a/saleor/account/utils.py b/saleor/account/utils.pyindex 981aee7bee..0627d7659d 100644--- a/saleor/account/utils.py+++ b/saleor/account/utils.py@@ -11,7 +11,10 @@ if TYPE_CHECKING:def store_user_address(- user: User, address: "Address", address_type: str, manager: "PluginsManager"+ user: User,+ address: "Address",+ address_type: str,+ manager: "PluginsManager",):"""Add address to user address book and set as default one."""address = manager.change_user_address(address, address_type, user)diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 2dd7831094..cea971cf14 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -101,14 +101,11 @@ def _process_user_data_for_order(checkout_info: "CheckoutInfo", manager):"""Fetch, process and return shipping data from checkout."""billing_address = checkout_info.billing_address- if checkout_info.user:+ if checkout_info.user and billing_address:store_user_address(checkout_info.user, billing_address, AddressType.BILLING, manager=manager)- if (- billing_address- and checkout_info.user.addresses.filter(pk=billing_address.pk).exists()- ):+ if checkout_info.user.addresses.filter(pk=billing_address.pk).exists():billing_address = billing_address.get_copy()return {@@ -328,7 +325,12 @@ def _prepare_order_data(@transaction.atomicdef _create_order(- *, checkout_info: "CheckoutInfo", order_data: dict, user: User, site_settings=None+ *,+ checkout_info: "CheckoutInfo",+ order_data: dict,+ user: User,+ manager: "PluginsManager",+ site_settings=None) -> Order:"""Create an order from the checkout.@@ -403,7 +405,9 @@ def _create_order(order.private_metadata = checkout.private_metadataorder.save()- transaction.on_commit(lambda: order_created(order=order, user=user))+ transaction.on_commit(+ lambda: order_created(order=order, user=user, manager=manager)+ )# Send the order confirmation emailtransaction.on_commit(@@ -590,6 +594,7 @@ def complete_checkout(checkout_info=checkout_info,order_data=order_data,user=user, # type: ignore+ manager=manager,site_settings=site_settings,)# remove checkout after order is successfully createddiff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.pyindex 9c4da40ad1..db36361b4a 100644--- a/saleor/checkout/tests/test_checkout_complete.py+++ b/saleor/checkout/tests/test_checkout_complete.py@@ -53,6 +53,7 @@ def test_create_order_captured_payment_creates_expected_events(discounts=None,),user=customer_user,+ manager=manager,)flush_post_commit_hooks()@@ -193,6 +194,7 @@ def test_create_order_captured_payment_creates_expected_events_anonymous_user(discounts=None,),user=AnonymousUser(),+ manager=manager,)flush_post_commit_hooks()@@ -325,6 +327,7 @@ def test_create_order_preauth_payment_creates_expected_events(discounts=None,),user=customer_user,+ manager=manager,)flush_post_commit_hooks()@@ -436,6 +439,7 @@ def test_create_order_preauth_payment_creates_expected_events_anonymous_user(discounts=None,),user=AnonymousUser(),+ manager=manager,)flush_post_commit_hooks()@@ -549,6 +553,7 @@ def test_create_order_doesnt_duplicate_order(checkout_info=checkout_info,order_data=order_data,user=customer_user,+ manager=manager,)assert order_1.checkout_token == checkout.token@@ -556,6 +561,7 @@ def test_create_order_doesnt_duplicate_order(checkout_info=checkout_info,order_data=order_data,user=customer_user,+ manager=manager,)assert order_1.pk == order_2.pk@@ -604,6 +610,7 @@ def test_create_order_with_gift_card(discounts=None,),user=customer_user if not is_anonymous_user else AnonymousUser(),+ manager=manager,)assert order.gift_cards.count() == 1@@ -647,6 +654,7 @@ def test_create_order_with_gift_card_partial_use(discounts=None,),user=customer_user,+ manager=manager,)gift_card_used.refresh_from_db()@@ -704,6 +712,7 @@ def test_create_order_with_many_gift_cards(discounts=None,),user=customer_user,+ manager=manager,)gift_card_created_by_staff.refresh_from_db()@@ -735,6 +744,7 @@ def test_note_in_created_order(checkout_with_item, address, customer_user):discounts=None,),user=customer_user,+ manager=manager,)assert order.customer_note == checkout_with_item.note@@ -763,6 +773,7 @@ def test_create_order_with_variant_tracking_false(checkout_info=checkout_info,order_data=order_data,user=customer_user,+ manager=manager,)assert order_1.checkout_token == checkout.tokendiff --git a/saleor/graphql/order/bulk_mutations/orders.py b/saleor/graphql/order/bulk_mutations/orders.pyindex 40120683b9..c1126774c9 100644--- a/saleor/graphql/order/bulk_mutations/orders.py+++ b/saleor/graphql/order/bulk_mutations/orders.py@@ -33,4 +33,4 @@ class OrderBulkCancel(BaseBulkMutation):@classmethoddef bulk_action(cls, info, queryset, user):for order in queryset:- cancel_order(order=order, user=user)+ cancel_order(order=order, user=user, manager=info.context.plugins)diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex 62bb539e3f..ca7c59d9cb 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -384,7 +384,9 @@ class DraftOrderComplete(BaseMutation):except InsufficientStock as exc:errors = prepare_insufficient_stock_order_validation_errors(exc)raise ValidationError({"lines": errors})- order_created(order, user=info.context.user, from_draft=True)+ order_created(+ order, user=info.context.user, manager=info.context.plugins, from_draft=True+ )return DraftOrderComplete(order=order)diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.pyindex ec7952c500..4c04a9c6da 100644--- a/saleor/graphql/order/mutations/fulfillments.py+++ b/saleor/graphql/order/mutations/fulfillments.py@@ -215,7 +215,11 @@ class OrderFulfill(BaseMutation):try:fulfillments = create_fulfillments(- user, order, dict(lines_for_warehouses), notify_customer+ user,+ order,+ dict(lines_for_warehouses),+ info.context.plugins,+ notify_customer,)except InsufficientStock as exc:errors = prepare_insufficient_stock_order_validation_errors(exc)@@ -251,7 +255,9 @@ class FulfillmentUpdateTracking(BaseMutation):fulfillment.tracking_number = tracking_numberfulfillment.save()order = fulfillment.order- fulfillment_tracking_updated(fulfillment, info.context.user, tracking_number)+ fulfillment_tracking_updated(+ fulfillment, info.context.user, tracking_number, info.context.plugins+ )input_data = data.get("input", {})notify_customer = input_data.get("notify_customer")if notify_customer:@@ -294,7 +300,9 @@ class FulfillmentCancel(BaseMutation):)order = fulfillment.order- cancel_fulfillment(fulfillment, info.context.user, warehouse)+ cancel_fulfillment(+ fulfillment, info.context.user, warehouse, info.context.plugins+ )fulfillment.refresh_from_db(fields=["status"])order.refresh_from_db(fields=["status"])return FulfillmentCancel(fulfillment=fulfillment, order=order)diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 2272f3ff13..ebc395d465 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -286,7 +286,7 @@ class OrderUpdateShipping(BaseMutation):info.context.site.settings.include_taxes_in_prices,)# Post-process the results- order_shipping_updated(order)+ order_shipping_updated(order, info.context.plugins)return OrderUpdateShipping(order=order)@@ -359,7 +359,7 @@ class OrderCancel(BaseMutation):def perform_mutation(cls, _root, info, **data):order = cls.get_node_or_error(info, data.get("id"), only_type=Order)clean_order_cancel(order)- cancel_order(order=order, user=info.context.user)+ cancel_order(order=order, user=info.context.user, manager=info.context.plugins)return OrderCancel(order=order)@@ -395,7 +395,9 @@ class OrderMarkAsPaid(BaseMutation):order, info.context.user, None, clean_mark_order_as_paid, order)- mark_order_as_paid(order, info.context.user, transaction_reference)+ mark_order_as_paid(+ order, info.context.user, info.context.plugins, transaction_reference+ )return OrderMarkAsPaid(order=order)@@ -436,7 +438,9 @@ class OrderCapture(BaseMutation):# Confirm that we changed the status to capture. Some payment can receive# asynchronous webhook with update statusif transaction.kind == TransactionKind.CAPTURE:- order_captured(order, info.context.user, amount, payment)+ order_captured(+ order, info.context.user, amount, payment, info.context.plugins+ )return OrderCapture(order=order)@@ -464,7 +468,7 @@ class OrderVoid(BaseMutation):# Confirm that we changed the status to void. Some payment can receive# asynchronous webhook with update statusif transaction.kind == TransactionKind.VOID:- order_voided(order, info.context.user, payment)+ order_voided(order, info.context.user, payment, info.context.plugins)return OrderVoid(order=order)@@ -547,8 +551,9 @@ class OrderConfirm(ModelMutation):order.status = OrderStatus.UNFULFILLEDorder.save(update_fields=["status"])payment = order.get_last_payment()+ manager = info.context.pluginsif payment and payment.is_authorized and payment.can_capture():gateway.capture(payment)- order_captured(order, info.context.user, payment.total, payment)- order_confirmed(order, info.context.user, send_confirmation_email=True)+ order_captured(order, info.context.user, payment.total, payment, manager)+ order_confirmed(order, info.context.user, manager, send_confirmation_email=True)return OrderConfirm(order=order)diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.pyindex 8cfa3f45fb..38f3f8db8d 100644--- a/saleor/graphql/order/tests/test_fulfillment.py+++ b/saleor/graphql/order/tests/test_fulfillment.py@@ -1,4 +1,4 @@-from unittest.mock import patch+from unittest.mock import ANY, patchimport graphenefrom django.contrib.auth.models import AnonymousUser@@ -77,7 +77,7 @@ def test_order_fulfill(]}mock_create_fulfillments.assert_called_once_with(- staff_user, order, fulfillment_lines_for_warehouses, True+ staff_user, order, fulfillment_lines_for_warehouses, ANY, True)@@ -127,7 +127,7 @@ def test_order_fulfill_as_app(]}mock_create_fulfillments.assert_called_once_with(- AnonymousUser(), order, fulfillment_lines_for_warehouses, True+ AnonymousUser(), order, fulfillment_lines_for_warehouses, ANY, True)@@ -186,7 +186,7 @@ def test_order_fulfill_many_warehouses(}mock_create_fulfillments.assert_called_once_with(- staff_user, order, fulfillment_lines_for_warehouses, True+ staff_user, order, fulfillment_lines_for_warehouses, ANY, True)@@ -228,7 +228,7 @@ def test_order_fulfill_without_notification(str(warehouse.pk): [{"order_line": order_line, "quantity": 1}]}mock_create_fulfillments.assert_called_once_with(- staff_user, order, fulfillment_lines_for_warehouses, False+ staff_user, order, fulfillment_lines_for_warehouses, ANY, False)@@ -286,7 +286,7 @@ def test_order_fulfill_lines_with_empty_quantity(str(warehouse.pk): [{"order_line": order_line2, "quantity": 2}]}mock_create_fulfillments.assert_called_once_with(- staff_user, order, fulfillment_lines_for_warehouses, True+ staff_user, order, fulfillment_lines_for_warehouses, ANY, True)diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.pyindex 5644753b14..9917b7178a 100644--- a/saleor/graphql/order/tests/test_order.py+++ b/saleor/graphql/order/tests/test_order.py@@ -3210,7 +3210,9 @@ def test_order_cancel(assert not data["orderErrors"]mock_clean_order_cancel.assert_called_once_with(order)- mock_cancel_order.assert_called_once_with(order=order, user=staff_api_client.user)+ mock_cancel_order.assert_called_once_with(+ order=order, user=staff_api_client.user, manager=ANY+ )@patch("saleor.graphql.order.mutations.orders.cancel_order")@@ -3233,7 +3235,9 @@ def test_order_cancel_as_app(assert not data["orderErrors"]mock_clean_order_cancel.assert_called_once_with(order)- mock_cancel_order.assert_called_once_with(order=order, user=AnonymousUser())+ mock_cancel_order.assert_called_once_with(+ order=order, user=AnonymousUser(), manager=ANY+ )def test_order_capture(@@ -4358,7 +4362,9 @@ def test_order_bulk_cancel(assert data["count"] == expected_countassert not data["orderErrors"]- calls = [call(order=order, user=staff_api_client.user) for order in orders]+ calls = [+ call(order=order, user=staff_api_client.user, manager=ANY) for order in orders+ ]mock_cancel_order.assert_has_calls(calls, any_order=True)mock_cancel_order.call_count == expected_count@@ -4387,7 +4393,7 @@ def test_order_bulk_cancel_as_app(assert data["count"] == expected_countassert not data["orderErrors"]- calls = [call(order=order, user=AnonymousUser()) for order in orders]+ calls = [call(order=order, user=AnonymousUser(), manager=ANY) for order in orders]mock_cancel_order.assert_has_calls(calls, any_order=True)assert mock_cancel_order.call_count == expected_countdiff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 9530bdaabd..b892bf2075 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -20,7 +20,6 @@ from ..payment import ()from ..payment.models import Payment, Transactionfrom ..payment.utils import create_payment-from ..plugins.manager import PluginsManager, get_plugins_managerfrom ..warehouse.management import (deallocate_stock,deallocate_stock_for_order,@@ -59,6 +58,7 @@ from .utils import ()if TYPE_CHECKING:+ from ..plugins.manager import PluginsManagerfrom ..warehouse.models import Warehouselogger = logging.getLogger(__name__)@@ -68,40 +68,53 @@ OrderLineIDType = intQuantityType = int-def order_created(order: "Order", user: "User", from_draft: bool = False):+def order_created(+ order: "Order", user: "User", manager: "PluginsManager", from_draft: bool = False+):events.order_created_event(order=order, user=user, from_draft=from_draft)- manager = get_plugins_manager()manager.order_created(order)payment = order.get_last_payment()if payment:if order.is_captured():order_captured(- order=order, user=user, amount=payment.total, payment=payment+ order=order,+ user=user,+ amount=payment.total,+ payment=payment,+ manager=manager,)elif order.is_pre_authorized():order_authorized(- order=order, user=user, amount=payment.total, payment=payment+ order=order,+ user=user,+ amount=payment.total,+ payment=payment,+ manager=manager,)site_settings = Site.objects.get_current().settingsif site_settings.automatically_confirm_all_new_orders:- order_confirmed(order, user)+ order_confirmed(order, user, manager)def order_confirmed(- order: "Order", user: "User", send_confirmation_email: bool = False+ order: "Order",+ user: "User",+ manager: "PluginsManager",+ send_confirmation_email: bool = False,):"""Order confirmed.Trigger event, plugin hooks and optionally confirmation email."""events.order_confirmed_event(order=order, user=user)- manager = get_plugins_manager()manager.order_confirmed(order)if send_confirmation_email:send_order_confirmed.delay(order.pk, user.pk)-def handle_fully_paid_order(order: "Order", user: Optional["User"] = None):+def handle_fully_paid_order(+ manager: "PluginsManager", order: "Order", user: Optional["User"] = None+):events.order_fully_paid_event(order=order, user=user)if order.get_customer_email():@@ -117,13 +130,12 @@ def handle_fully_paid_order(order: "Order", user: Optional["User"] = None):except Exception:# Analytics failing should not abort the checkout flowlogger.exception("Recording order in analytics failed")- manager = get_plugins_manager()manager.order_fully_paid(order)manager.order_updated(order)@transaction.atomic-def cancel_order(order: "Order", user: Optional["User"]):+def cancel_order(order: "Order", user: Optional["User"], manager: "PluginsManager"):"""Cancel order.Release allocation of unfulfilled order items.@@ -135,7 +147,6 @@ def cancel_order(order: "Order", user: Optional["User"]):order.status = OrderStatus.CANCELEDorder.save(update_fields=["status"])- manager = get_plugins_manager()manager.order_cancelled(order)manager.order_updated(order)@@ -147,21 +158,21 @@ def order_refunded(user: Optional["User"],amount: "Decimal",payment: "Payment",- manager: Optional["PluginsManager"] = None,+ manager: "PluginsManager",):events.payment_refunded_event(order=order, user=user, amount=amount, payment=payment)- if not manager:- manager = get_plugins_manager()manager.order_updated(order)send_order_refunded_confirmation(order, user, amount, payment.currency)-def order_voided(order: "Order", user: "User", payment: "Payment"):+def order_voided(+ order: "Order", user: "User", payment: "Payment", manager: "PluginsManager"+):events.payment_voided_event(order=order, user=user, payment=payment)- get_plugins_manager().order_updated(order)+ manager.order_updated(order)def order_returned(@@ -180,6 +191,7 @@ def order_fulfilled(fulfillments: List["Fulfillment"],user: "User",fulfillment_lines: List["FulfillmentLine"],+ manager: "PluginsManager",notify_customer=True,):order = fulfillments[0].order@@ -187,7 +199,6 @@ def order_fulfilled(events.fulfillment_fulfilled_items_event(order=order, user=user, fulfillment_lines=fulfillment_lines)- manager = get_plugins_manager()manager.order_updated(order)for fulfillment in fulfillments:@@ -201,33 +212,44 @@ def order_fulfilled(send_fulfillment_confirmation_to_customer(order, fulfillment, user)-def order_shipping_updated(order: "Order"):+def order_shipping_updated(order: "Order", manager: "PluginsManager"):recalculate_order(order)- get_plugins_manager().order_updated(order)+ manager.order_updated(order)def order_authorized(- order: "Order", user: Optional["User"], amount: "Decimal", payment: "Payment"+ order: "Order",+ user: Optional["User"],+ amount: "Decimal",+ payment: "Payment",+ manager: "PluginsManager",):events.payment_authorized_event(order=order, user=user, amount=amount, payment=payment)- get_plugins_manager().order_updated(order)+ manager.order_updated(order)def order_captured(- order: "Order", user: Optional["User"], amount: "Decimal", payment: "Payment"+ order: "Order",+ user: Optional["User"],+ amount: "Decimal",+ payment: "Payment",+ manager: "PluginsManager",):events.payment_captured_event(order=order, user=user, amount=amount, payment=payment)- get_plugins_manager().order_updated(order)+ manager.order_updated(order)if order.is_fully_paid():- handle_fully_paid_order(order, user)+ handle_fully_paid_order(manager, order, user)def fulfillment_tracking_updated(- fulfillment: "Fulfillment", user: "User", tracking_number: str+ fulfillment: "Fulfillment",+ user: "User",+ tracking_number: str,+ manager: "PluginsManager",):events.fulfillment_tracking_updated_event(order=fulfillment.order,@@ -235,12 +257,15 @@ def fulfillment_tracking_updated(tracking_number=tracking_number,fulfillment=fulfillment,)- get_plugins_manager().order_updated(fulfillment.order)+ manager.order_updated(fulfillment.order)@transaction.atomicdef cancel_fulfillment(- fulfillment: "Fulfillment", user: "User", warehouse: "Warehouse"+ fulfillment: "Fulfillment",+ user: "User",+ warehouse: "Warehouse",+ manager: "PluginsManager",):"""Cancel fulfillment.@@ -260,12 +285,15 @@ def cancel_fulfillment(fulfillment.status = FulfillmentStatus.CANCELEDfulfillment.save(update_fields=["status"])update_order_status(fulfillment.order)- get_plugins_manager().order_updated(fulfillment.order)+ manager.order_updated(fulfillment.order)@transaction.atomicdef mark_order_as_paid(- order: "Order", request_user: "User", external_reference: Optional[str] = None+ order: "Order",+ request_user: "User",+ manager: "PluginsManager",+ external_reference: Optional[str] = None,):"""Mark order as paid.@@ -299,7 +327,6 @@ def mark_order_as_paid(events.order_manually_marked_as_paid_event(order=order, user=request_user, transaction_reference=external_reference)- manager = get_plugins_manager()manager.order_fully_paid(order)manager.order_updated(order)@@ -460,6 +487,7 @@ def create_fulfillments(requester: "User",order: "Order",fulfillment_lines_for_warehouses: Dict,+ manager: "PluginsManager",notify_customer: bool = True,) -> List[Fulfillment]:"""Fulfill order.@@ -481,6 +509,7 @@ def create_fulfillments(...]}+ manager (PluginsManager): Base manager for handling plugins logic.notify_customer (bool): If `True` system send email aboutfulfillments to customer.@@ -512,6 +541,7 @@ def create_fulfillments(fulfillments,requester,fulfillment_lines,+ manager,notify_customer,))@@ -977,7 +1007,7 @@ def create_fulfillments_for_returned_products(payment: Optional[Payment],order_lines: List[OrderLineData],fulfillment_lines: List[FulfillmentLineData],- plugin_manager: PluginsManager,+ plugin_manager: "PluginsManager",refund: bool = False,amount: Optional[Decimal] = None,refund_shipping_costs=False,diff --git a/saleor/order/tests/test_fulfullments_actions.py b/saleor/order/tests/test_fulfullments_actions.pyindex 1fcbdf1587..431d8f34f7 100644--- a/saleor/order/tests/test_fulfullments_actions.py+++ b/saleor/order/tests/test_fulfullments_actions.py@@ -3,6 +3,7 @@ from unittest.mock import patchimport pytestfrom ...core.exceptions import InsufficientStock+from ...plugins.manager import get_plugins_managerfrom ...tests.utils import flush_post_commit_hooksfrom ...warehouse.models import Allocation, Stockfrom ..actions import create_fulfillments@@ -26,7 +27,7 @@ def test_create_fulfillments(}[fulfillment] = create_fulfillments(- staff_user, order, fulfillment_lines_for_warehouses, True+ staff_user, order, fulfillment_lines_for_warehouses, get_plugins_manager(), True)flush_post_commit_hooks()@@ -75,7 +76,11 @@ def test_create_fulfillments_without_notification(}[fulfillment] = create_fulfillments(- staff_user, order, fulfillment_lines_for_warehouses, False+ staff_user,+ order,+ fulfillment_lines_for_warehouses,+ get_plugins_manager(),+ False,)flush_post_commit_hooks()@@ -133,7 +138,11 @@ def test_create_fulfillments_many_warehouses(}[fulfillment1, fulfillment2] = create_fulfillments(- staff_user, order, fulfillment_lines_for_warehouses, False+ staff_user,+ order,+ fulfillment_lines_for_warehouses,+ get_plugins_manager(),+ False,)flush_post_commit_hooks()@@ -181,7 +190,7 @@ def test_create_fulfillments_with_one_line_empty_quantity(}[fulfillment] = create_fulfillments(- staff_user, order, fulfillment_lines_for_warehouses, True+ staff_user, order, fulfillment_lines_for_warehouses, get_plugins_manager(), True)flush_post_commit_hooks()@@ -227,7 +236,7 @@ def test_create_fulfillments_with_variant_without_inventory_tracking(}[fulfillment] = create_fulfillments(- staff_user, order, fulfillment_lines_for_warehouses, True+ staff_user, order, fulfillment_lines_for_warehouses, get_plugins_manager(), True)flush_post_commit_hooks()@@ -270,7 +279,7 @@ def test_create_fulfillments_without_allocations(}[fulfillment] = create_fulfillments(- staff_user, order, fulfillment_lines_for_warehouses, True+ staff_user, order, fulfillment_lines_for_warehouses, get_plugins_manager(), True)flush_post_commit_hooks()@@ -319,7 +328,13 @@ def test_create_fulfillments_warehouse_without_stock(}with pytest.raises(InsufficientStock) as exc:- create_fulfillments(staff_user, order, fulfillment_lines_for_warehouses, True)+ create_fulfillments(+ staff_user,+ order,+ fulfillment_lines_for_warehouses,+ get_plugins_manager(),+ True,+ )assert len(exc.value.items) == 2assert {item.variant for item in exc.value.items} == {@@ -365,7 +380,13 @@ def test_create_fulfillments_with_variant_without_inventory_tracking_and_without}with pytest.raises(InsufficientStock) as exc:- create_fulfillments(staff_user, order, fulfillment_lines_for_warehouses, True)+ create_fulfillments(+ staff_user,+ order,+ fulfillment_lines_for_warehouses,+ get_plugins_manager(),+ True,+ )assert len(exc.value.items) == 1assert exc.value.items[0].variant == order_line.variantdiff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.pyindex e63d6e96db..b9a68eaa92 100644--- a/saleor/order/tests/test_order_actions.py+++ b/saleor/order/tests/test_order_actions.py@@ -74,7 +74,8 @@ def test_handle_fully_paid_order_digital_lines(order = order_with_digital_lineorder.redirect_url = redirect_urlorder.save()- handle_fully_paid_order(order)+ manager = get_plugins_manager()+ handle_fully_paid_order(manager, order)fulfillment = order.fulfillments.first()@@ -108,7 +109,8 @@ def test_handle_fully_paid_order_digital_lines(@patch("saleor.order.emails.send_payment_confirmation.delay")def test_handle_fully_paid_order(mock_send_payment_confirmation, order):- handle_fully_paid_order(order)+ manager = get_plugins_manager()+ handle_fully_paid_order(manager, order)event_order_paid, event_email_sent = order.events.all()assert event_order_paid.type == OrderEvents.ORDER_FULLY_PAID@@ -125,15 +127,17 @@ def test_handle_fully_paid_order(mock_send_payment_confirmation, order):def test_handle_fully_paid_order_no_email(mock_send_payment_confirmation, order):order.user = Noneorder.user_email = ""+ manager = get_plugins_manager()- handle_fully_paid_order(order)+ handle_fully_paid_order(manager, order)event = order.events.get()assert event.type == OrderEvents.ORDER_FULLY_PAIDassert not mock_send_payment_confirmation.calleddef test_mark_as_paid(admin_user, draft_order):- mark_order_as_paid(draft_order, admin_user)+ manager = get_plugins_manager()+ mark_order_as_paid(draft_order, admin_user, manager)payment = draft_order.payments.last()assert payment.charge_status == ChargeStatus.FULLY_CHARGEDassert payment.captured_amount == draft_order.total.gross.amount@@ -145,7 +149,10 @@ def test_mark_as_paid(admin_user, draft_order):def test_mark_as_paid_with_external_reference(admin_user, draft_order):external_reference = "transaction_id"- mark_order_as_paid(draft_order, admin_user, external_reference=external_reference)+ manager = get_plugins_manager()+ mark_order_as_paid(+ draft_order, admin_user, manager, external_reference=external_reference+ )payment = draft_order.payments.last()assert payment.charge_status == ChargeStatus.FULLY_CHARGEDassert payment.captured_amount == draft_order.total.gross.amount@@ -161,8 +168,9 @@ def test_mark_as_paid_no_billing_address(admin_user, draft_order):draft_order.billing_address = Nonedraft_order.save()+ manager = get_plugins_manager()with pytest.raises(Exception):- mark_order_as_paid(draft_order, admin_user)+ mark_order_as_paid(draft_order, admin_user, manager)def test_clean_mark_order_as_paid(payment_txn_preauth):@@ -175,7 +183,7 @@ def test_cancel_fulfillment(fulfilled_order, warehouse):fulfillment = fulfilled_order.fulfillments.first()line_1, line_2 = fulfillment.lines.all()- cancel_fulfillment(fulfillment, None, warehouse)+ cancel_fulfillment(fulfillment, None, warehouse, get_plugins_manager())fulfillment.refresh_from_db()fulfilled_order.refresh_from_db()@@ -193,7 +201,7 @@ def test_cancel_fulfillment_variant_witout_inventory_tracking(stock = line.order_line.variant.stocks.get()stock_quantity_before = stock.quantity- cancel_fulfillment(fulfillment, None, warehouse)+ cancel_fulfillment(fulfillment, None, warehouse, get_plugins_manager())fulfillment.refresh_from_db()line.refresh_from_db()@@ -211,13 +219,14 @@ def test_cancel_order():# givenorder = fulfilled_order_with_all_cancelled_fulfillments+ manager = get_plugins_manager()assert Allocation.objects.filter(order_line__order=order, quantity_allocated__gt=0).exists()# when- cancel_order(order, None)+ cancel_order(order, None, manager)# thenorder_event = order.events.last()diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.pyindex fabfa5547c..4cebb3795d 100644--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py@@ -302,8 +302,9 @@ def test_handle_cancel(value=to_adyen_price(payment.total, payment.currency),)config = adyen_plugin().config+ manager = get_plugins_manager()- handle_cancellation(notification, config)+ handle_cancellation(notification, config, manager)payment.order.refresh_from_db()assert payment.transactions.count() == 2@@ -331,8 +332,9 @@ def test_handle_cancel_invalid_payment_id(transaction_count = payment.transactions.count()caplog.set_level(logging.WARNING)+ manager = get_plugins_manager()- handle_cancellation(notification, config)+ handle_cancellation(notification, config, manager)payment.order.refresh_from_db()assert payment.transactions.count() == transaction_count@@ -354,8 +356,9 @@ def test_handle_cancel_already_canceled()config = adyen_plugin().configcreate_new_transaction(notification, payment, TransactionKind.CANCEL)+ manager = get_plugins_manager()- handle_cancellation(notification, config)+ handle_cancellation(notification, config, manager)assert payment.transactions.count() == 2@@ -672,7 +675,7 @@ def test_handle_refund(assert payment.captured_amount == Decimal("0.00")mock_order_refunded.assert_called_once_with(- payment.order, None, transaction.amount, payment+ payment.order, None, transaction.amount, payment, mock.ANY)external_events = payment.order.events.filter(type=OrderEvents.EXTERNAL_SERVICE_NOTIFICATION@@ -969,7 +972,7 @@ def test_handle_cancel_or_refund_action_cancel(handle_cancel_or_refund(notification, config)- mock_handle_cancellation.assert_called_once_with(notification, config)+ mock_handle_cancellation.assert_called_once_with(notification, config, mock.ANY)def test_handle_cancel_or_refund_action_cancel_invalid_payment_id(diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.pyindex 20d1a414b4..83649e829e 100644--- a/saleor/payment/gateways/adyen/webhooks.py+++ b/saleor/payment/gateways/adyen/webhooks.py@@ -5,7 +5,7 @@ import hmacimport jsonimport loggingfrom json.decoder import JSONDecodeError-from typing import Any, Callable, Dict, Optional+from typing import TYPE_CHECKING, Any, Callable, Dict, Optionalfrom urllib.parse import urlencode, urlparseimport Adyen@@ -47,6 +47,9 @@ from .utils.common import FAILED_STATUSES, api_call, from_adyen_pricelogger = logging.getLogger(__name__)+if TYPE_CHECKING:+ from ....plugins.manager import PluginsManager+def get_payment(payment_id: Optional[str],@@ -210,6 +213,7 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCoreturncheckout = get_checkout(payment)+ manager = get_plugins_manager()adyen_auto_capture = gateway_config.connection_params["adyen_auto_capture"]kind = TransactionKind.AUTHif adyen_auto_capture:@@ -232,10 +236,12 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCoif new_transaction.is_success:gateway_postprocess(new_transaction, payment)if adyen_auto_capture:- order_captured(payment.order, None, new_transaction.amount, payment)+ order_captured(+ payment.order, None, new_transaction.amount, payment, manager+ )else:order_authorized(- payment.order, None, new_transaction.amount, payment+ payment.order, None, new_transaction.amount, payment, manager)reason = notification.get("reason", "-")is_success = True if notification.get("success") == "true" else False@@ -246,7 +252,11 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCocreate_payment_notification_for_order(payment, success_msg, failed_msg, is_success)-def handle_cancellation(notification: Dict[str, Any], _gateway_config: GatewayConfig):+def handle_cancellation(+ notification: Dict[str, Any],+ _gateway_config: GatewayConfig,+ manager: "PluginsManager",+):# https://docs.adyen.com/checkout/cancel#cancellation-notifciationtransaction_id = notification.get("pspReference")payment = get_payment(@@ -273,7 +283,7 @@ def handle_cancellation(notification: Dict[str, Any], _gateway_config: GatewayCopayment, success_msg, failed_msg, new_transaction.is_success)if payment.order and new_transaction.is_success:- cancel_order(payment.order, None)+ cancel_order(payment.order, None, manager)def handle_cancel_or_refund(@@ -281,13 +291,14 @@ def handle_cancel_or_refund():# https://docs.adyen.com/checkout/cancel-or-refund#cancel-or-refund-notificationadditional_data = notification.get("additionalData")+ manager = get_plugins_manager()if not additional_data:returnaction = additional_data.get("modification.action")if action == "refund":handle_refund(notification, gateway_config)elif action == "cancel":- handle_cancellation(notification, gateway_config)+ handle_cancellation(notification, gateway_config, manager)def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):@@ -298,6 +309,7 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)returncheckout = get_checkout(payment)+ manager = get_plugins_manager()if not payment.order:handle_not_created_order(notification, payment, checkout, TransactionKind.CAPTURE@@ -313,7 +325,9 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig))if new_transaction.is_success and not capture_transaction:gateway_postprocess(new_transaction, payment)- order_captured(payment.order, None, new_transaction.amount, payment)+ order_captured(+ payment.order, None, new_transaction.amount, payment, manager+ )reason = notification.get("reason", "-")is_success = True if notification.get("success") == "true" else False@@ -393,7 +407,9 @@ def handle_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):payment, success_msg, failed_msg, new_transaction.is_success)if payment.order and new_transaction.is_success:- order_refunded(payment.order, None, new_transaction.amount, payment)+ order_refunded(+ payment.order, None, new_transaction.amount, payment, get_plugins_manager()+ )def _get_kind(transaction: Optional[Transaction]) -> str:@@ -641,7 +657,7 @@ def handle_webhook(request: WSGIRequest, gateway_config: "GatewayConfig"):event_handler = EVENT_MAP.get(notification.get("eventCode", ""))if event_handler:- event_handler(notification, gateway_config)+ event_handler(notification, gateway_config) # type: ignorereturn HttpResponse("[accepted]")return HttpResponse("[accepted]")diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex b15530fce0..66ec5adcab 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -66,6 +66,7 @@ from ..page.models import Page, PageTranslation, PageTypefrom ..payment import ChargeStatus, TransactionKindfrom ..payment.interface import GatewayConfig, PaymentDatafrom ..payment.models import Payment+from ..plugins.manager import get_plugins_managerfrom ..plugins.models import PluginConfigurationfrom ..plugins.vatlayer.plugin import VatlayerPluginfrom ..product import ProductMediaTypes@@ -2607,7 +2608,7 @@ def fulfilled_order_with_all_cancelled_fulfillments(fulfilled_order, staff_user, warehouse):fulfillment = fulfilled_order.fulfillments.get()- cancel_fulfillment(fulfillment, staff_user, warehouse)+ cancel_fulfillment(fulfillment, staff_user, warehouse, get_plugins_manager())return fulfilled_order