Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Merge branch 'master' into feature/webhooks
Maciej Korycinskic8a1cc4cd105
diff --cc saleor/extensions/base_plugin.pyindex f0ddda85c9,08ee00fe51..13a5c19028--- a/saleor/extensions/base_plugin.py+++ b/saleor/extensions/base_plugin.py@@@ -11,8 -12,9 +12,9 @@@ if TYPE_CHECKINGfrom ..core.taxes import TaxTypefrom ..checkout.models import Checkout, CheckoutLinefrom ..product.models import Product- from ..account.models import Address+ from ..account.models import Address, Userfrom ..order.models import OrderLine, Order+ from ..payment.interface import GatewayResponse, PaymentDataclass BasePlugin:@@@ -136,24 -138,42 +138,60 @@@) -> Decimal:return NotImplemented+ def customer_created(self, customer: "User", previous_value: Any) -> Any:+ return NotImplemented++ def product_created(self, product: "Product", previous_value: Any) -> Any:+ return NotImplemented++ def order_fully_paid(self, order: "Order", previous_value: Any) -> Any:+ return NotImplemented++ def order_updated(self, order: "Order", previous_value: Any) -> Any:+ return NotImplemented++ def order_cancelled(self, order: "Order", previous_value: Any) -> Any:+ return NotImplemented++ def order_fulfilled(self, order: "Order", previous_value: Any) -> Any:+ return NotImplemented++ def authorize_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return NotImplemented++ def capture_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return NotImplemented++ def refund_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return NotImplemented++ def confirm_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return NotImplemented++ def process_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return NotImplemented++ def list_payment_sources(+ self, customer_id: str, previous_value+ ) -> List["CustomerSource"]:+ return NotImplemented++ def create_form(self, data, payment_information, previous_value):+ return NotImplemented++ def get_client_token(self, token_config, previous_value):+ return NotImplemented+@classmethoddef _update_config_items(cls, configuration_to_update: List[dict], current_config: List[dict]diff --cc saleor/extensions/manager.pyindex ce7564eeaf,172302444c..3049c9848d--- a/saleor/extensions/manager.py+++ b/saleor/extensions/manager.py@@@ -13,11 -14,12 +14,12 @@@ if TYPE_CHECKINGfrom .base_plugin import BasePluginfrom ..checkout.models import Checkout, CheckoutLinefrom ..product.models import Product- from ..account.models import Address+ from ..account.models import Address, Userfrom ..order.models import OrderLine, Order+ from ..payment.interface import PaymentData, GatewayResponse, TokenConfig- class ExtensionsManager:+ class ExtensionsManager(PaymentInterface):"""Base manager for handling plugins logic."""plugins = None@@@ -178,31 -180,106 +180,130 @@@"postprocess_order_creation", default_value, order)+ def customer_created(self, customer: "User"):+ default_value = None+ return self.__run_method_on_plugins("customer_created", default_value, customer)++ def product_created(self, product: "Product"):+ default_value = None+ return self.__run_method_on_plugins("product_created", default_value, product)++ def order_fully_paid(self, order: "Order"):+ default_value = None+ return self.__run_method_on_plugins("order_fully_paid", default_value, order)++ def order_updated(self, order: "Order"):+ default_value = None+ return self.__run_method_on_plugins("order_updated", default_value, order)++ def order_cancelled(self, order: "Order"):+ default_value = None+ return self.__run_method_on_plugins("order_cancelled", default_value, order)++ def order_fulfilled(self, order: "Order"):+ default_value = None+ return self.__run_method_on_plugins("order_fulfilled", default_value, order)++ def authorize_payment(+ self, gateway: Gateway, payment_information: "PaymentData"+ ) -> "GatewayResponse":+ method_name = "authorize_payment"+ return self.__run_payment_method(gateway, method_name, payment_information)++ def capture_payment(+ self, gateway: Gateway, payment_information: "PaymentData"+ ) -> "GatewayResponse":+ method_name = "capture_payment"+ return self.__run_payment_method(gateway, method_name, payment_information)++ def refund_payment(+ self, gateway: Gateway, payment_information: "PaymentData"+ ) -> "GatewayResponse":+ method_name = "refund_payment"+ return self.__run_payment_method(gateway, method_name, payment_information)++ def void_payment(+ self, gateway: Gateway, payment_information: "PaymentData"+ ) -> "GatewayResponse":+ method_name = "void_payment"+ return self.__run_payment_method(gateway, method_name, payment_information)++ def confirm_payment(+ self, gateway: Gateway, payment_information: "PaymentData"+ ) -> "GatewayResponse":+ method_name = "confirm_payment"+ return self.__run_payment_method(gateway, method_name, payment_information)++ def process_payment(+ self, gateway: Gateway, payment_information: "PaymentData"+ ) -> "GatewayResponse":+ method_name = "process_payment"+ return self.__run_payment_method(gateway, method_name, payment_information)++ def create_payment_form(self, data, gateway, payment_information):+ method_name = "create_form"+ return self.__run_payment_method(+ gateway, method_name, payment_information, data=data+ )++ def get_client_token(self, gateway, token_config: "TokenConfig") -> str:+ method_name = "get_client_token"+ default_value = None+ gateway_name = gateway.value+ gtw = self.get_plugin(gateway_name)+ return self.__run_method_on_single_plugin(+ gtw, method_name, default_value, token_config=token_config+ )++ def list_payment_sources(+ self, gateway: Gateway, customer_id: str+ ) -> List["CustomerSource"]:+ default_value = []+ gateway_name = gateway.value+ gtw = self.get_plugin(gateway_name)+ if gtw is not None:+ return self.__run_method_on_single_plugin(+ gtw, "list_payment_sources", default_value, customer_id=customer_id+ )+ raise Exception(f"Payment plugin {gateway_name} is inaccessible!")++ def list_payment_gateways(self) -> List[Gateway]:+ payment_method = "process_payment"+ return [+ Gateway(plugin.PLUGIN_NAME)+ for plugin in self.plugins+ if payment_method in type(plugin).__dict__+ and self.get_plugin_configuration(plugin.PLUGIN_NAME).active+ ]++ def __run_payment_method(+ self,+ gateway: Gateway,+ method_name: str,+ payment_information: "PaymentData",+ **kwargs,+ ) -> Optional["GatewayResposne"]:+ default_value = None+ gateway_name = gateway.value+ gtw = self.get_plugin(gateway_name)+ if gtw is not None:+ resp = self.__run_method_on_single_plugin(+ gtw,+ method_name,+ previous_value=default_value,+ payment_information=payment_information,+ **kwargs,+ )+ if resp is not None:+ return resp++ raise Exception(+ f"Payment plugin {gateway_name} for {method_name}"+ " payment method is inaccessible!"+ )+# FIXME these methods should be more generic+def assign_tax_code_to_object_meta(self, obj: Union["Product", "ProductType"], tax_code: str):diff --cc saleor/graphql/account/mutations/account.pyindex d6f98f44fa,354674a872..a46192a123--- a/saleor/graphql/account/mutations/account.py+++ b/saleor/graphql/account/mutations/account.py@@@ -63,10 -66,12 +67,12 @@@ class AccountUpdate(BaseCustomerCreate)description = "Updates the account of the logged-in user."exclude = ["password"]model = models.User+ error_type_class = AccountError+ error_type_field = "account_errors"@classmethod- def check_permissions(cls, user):- return user.is_authenticated+ def check_permissions(cls, context):+ return context.user.is_authenticated@classmethoddef perform_mutation(cls, root, info, **data):@@@ -89,10 -94,12 +95,12 @@@ class AccountRequestDeletion(BaseMutatidescription = ("Sends an email with the account removal link for the logged-in user.")+ error_type_class = AccountError+ error_type_field = "account_errors"@classmethod- def check_permissions(cls, user):- return user.is_authenticated+ def check_permissions(cls, context):+ return context.user.is_authenticated@classmethoddef perform_mutation(cls, root, info, **data):@@@ -116,10 -123,12 +124,12 @@@ class AccountDelete(ModelDeleteMutationclass Meta:description = "Remove user account."model = models.User+ error_type_class = AccountError+ error_type_field = "account_errors"@classmethod- def check_permissions(cls, user):- return user.is_authenticated+ def check_permissions(cls, context):+ return context.user.is_authenticated@classmethoddef clean_instance(cls, info, instance):@@@ -166,10 -180,12 +181,12 @@@ class AccountAddressCreate(ModelMutatioclass Meta:description = "Create a new address for the customer."model = models.Address+ error_type_class = AccountError+ error_type_field = "account_errors"@classmethod- def check_permissions(cls, user):- return user.is_authenticated+ def check_permissions(cls, context):+ return context.user.is_authenticated@classmethoddef perform_mutation(cls, root, info, **data):@@@ -212,10 -232,12 +233,12 @@@ class AccountSetDefaultAddress(BaseMutaclass Meta:description = "Sets a default address for the authenticated user."+ error_type_class = AccountError+ error_type_field = "account_errors"@classmethod- def check_permissions(cls, user):- return user.is_authenticated+ def check_permissions(cls, context):+ return context.user.is_authenticated@classmethoddef perform_mutation(cls, _root, info, **data):diff --cc saleor/graphql/account/mutations/base.pyindex 7cda7306cc,e702aea7cf..ba26856482--- a/saleor/graphql/account/mutations/base.py+++ b/saleor/graphql/account/mutations/base.py@@@ -125,10 -156,12 +156,12 @@@ class PasswordChange(BaseMutation)class Meta:description = "Change the password of the logged in user."+ error_type_class = AccountError+ error_type_field = "account_errors"@classmethod- def check_permissions(cls, user):- return user.is_authenticated+ def check_permissions(cls, context):+ return context.user.is_authenticated@classmethoddef perform_mutation(cls, _root, info, **data):diff --cc saleor/graphql/order/mutations/fulfillments.pyindex f77c5fd0ff,95d740d7a1..ec2dd1fc63--- a/saleor/graphql/order/mutations/fulfillments.py+++ b/saleor/graphql/order/mutations/fulfillments.py@@@ -2,11 -2,12 +2,13 @@@ import graphenfrom django.core.exceptions import ValidationErrorfrom django.utils.translation import npgettext_lazy, pgettext_lazy-from ....order import events, models+from ....extensions.manager import get_extensions_manager+from ....order import OrderStatus, events, modelsfrom ....order.emails import send_fulfillment_confirmation_to_customer+ from ....order.error_codes import OrderErrorCodefrom ....order.utils import cancel_fulfillment, fulfill_order_line, update_order_statusfrom ...core.mutations import BaseMutation+ from ...core.types.common import OrderErrorfrom ...order.types import Fulfillment, Orderfrom ..types import OrderLinediff --cc saleor/graphql/product/mutations/attributes.pyindex 2fa4564069,7ad9010fd8..077b1c631a--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@@ -286,10 -321,12 +321,12 @@@ class AttributeAssign(BaseMutation)class Meta:description = "Assign attributes to a given product type."+ error_type_class = ProductError+ error_type_field = "product_errors"@classmethod- def check_permissions(cls, user):- return user.has_perm("product.manage_products")+ def check_permissions(cls, context):+ return context.user.has_perm("product.manage_products")@classmethoddef get_operations(cls, info, operations: List[AttributeAssignInput]):@@@ -416,10 -467,12 +467,12 @@@ class AttributeUnassign(BaseMutation)class Meta:description = "Un-assign attributes from a given product type."+ error_type_class = ProductError+ error_type_field = "product_errors"@classmethod- def check_permissions(cls, user):- return user.has_perm("product.manage_products")+ def check_permissions(cls, context):+ return context.user.has_perm("product.manage_products")@classmethoddef save_field_values(cls, product_type, field, pks):diff --cc saleor/payment/utils.pyindex 1f0441ddef,3f51466866..ccde0cc29e--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@@ -117,27 -85,8 +86,11 @@@ def handle_fully_paid_order(order)except Exception:# Analytics failing should not abort the checkout flowlogger.exception("Recording order in analytics failed")+ manager = get_extensions_manager()+ manager.order_fully_paid(order)+ manager.order_updated(order)- def require_active_payment(view):- """Require an active payment instance.-- Decorate a view to check if payment is authorized, so any actions- can be performed on it.- """-- @wraps(view)- def func(payment: Payment, *args, **kwargs):- if not payment.is_active:- raise PaymentError("This payment is no longer active.")- return view(payment, *args, **kwargs)-- return func--def create_payment(gateway: str,total: Decimal,diff --cc tests/conftest.pyindex 6b7ebfafb6,fb9f85101b..4c769d7ec6--- a/tests/conftest.py+++ b/tests/conftest.py@@@ -1432,15 -1427,17 +1434,31 @@@ def other_description_raw())+def service_account(db):+ return ServiceAccount.objects.create(name="Sample service account", is_active=True)+++def webhook(service_account):+ webhook = Webhook.objects.create(+ service_account=service_account, target_url="http://www.example.com/test"+ )+ webhook.events.create(event_type=WebhookEventType.ORDER_CREATED)+ return webhook+++++ @pytest.fixture+ def fake_payment_interface(mocker):+ return mocker.Mock(spec=PaymentInterface)+++ @pytest.fixture+ def mock_get_manager(mocker, fake_payment_interface):+ mgr = mocker.patch(+ "saleor.payment.gateway.get_extensions_manager",+ autospec=True,+ return_value=fake_payment_interface,+ )+ yield fake_payment_interface+ mgr.assert_called_once()