Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add MVP
Maciej Korycinskiaf2cd10a4f2a
diff --git a/saleor/core/__init__.py b/saleor/core/__init__.pyindex e2d512343a..6ae3e12ba6 100644--- a/saleor/core/__init__.py+++ b/saleor/core/__init__.py@@ -1,6 +1,8 @@from django.conf import settingsfrom django.core.checks import Warning, register+from .extensions.checks import check_extensions # NOQA: F401+TOKEN_PATTERN = ("(?P<token>[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}" "-[0-9a-z]{12})")diff --git a/saleor/core/extensions/__init__.py b/saleor/core/extensions/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/core/extensions/checks.py b/saleor/core/extensions/checks.pynew file mode 100644index 0000000000..8e0a7aee59--- /dev/null+++ b/saleor/core/extensions/checks.py@@ -0,0 +1,39 @@+import importlib++from django.conf import settings+from django.core.checks import Error, register+++@register()+def check_extensions(app_configs, **kwargs):+ """Confirm a correct import of plugins and manager."""+ errors = []+ if not settings.EXTENSION_MANAGER:+ return []+ manager_path = settings.EXTENSION_MANAGER+ manager_path, _, manager_name = manager_path.rpartition(".")+ manager_module = importlib.import_module(manager_path)+ manager_class = getattr(manager_module, manager_name, None)+ if not manager_class:+ errors.append(+ Error(+ "Extension Manager %s doesn't exists in specific path %s"+ % (manager_name, str(manager_module))+ )+ )++ plugins = settings.PLUGINS++ if plugins:+ for plugin_path in plugins:+ plugin_path, _, plugin_name = plugin_path.rpartition(".")+ plugin_module = importlib.import_module(plugin_path)+ plugin_class = getattr(plugin_module, plugin_name, None)+ if not plugin_class:+ errors.append(+ Error(+ "Plugin %s doesn't exists in specific path %s"+ % (plugin_name, str(plugin_module))+ )+ )+ return errorsdiff --git a/saleor/core/extensions/manager.py b/saleor/core/extensions/manager.pynew file mode 100644index 0000000000..26d488d7b5--- /dev/null+++ b/saleor/core/extensions/manager.py@@ -0,0 +1,57 @@+import importlib++from django.conf import settings++from .plugin import BasePlugin+++class PluginError(BaseException):+ """ Default plugin exception """+++class BaseManager(BasePlugin):+ """Base manager for handling a plugins logic. It inherits BasePlugin to support+ IDEs' hints"""++ plugins = None++ def __init__(self, plugins):+ self.plugins = []+ for plugin_path in plugins:+ plugin_path, _, plugin_name = plugin_path.rpartition(".")+ plugin_module = importlib.import_module(plugin_path)+ plugin_class = getattr(plugin_module, plugin_name)+ self.plugins.append(plugin_class)++ def __getattribute__(self, item):+ for name, func in vars(BasePlugin).items():+ # Run custom getattribute for all plugin methods+ if name == item and not name.startswith("__"):+ return super().__getattribute__("_BaseManager__get_plugin_method")(+ name=item+ )++ return super().__getattribute__(item)++ def __get_plugin_method(self, name):+ def run_plugin_method(*args, **kwargs):+ value = None+ for p in self.plugins:+ try:+ value = getattr(p, name)(p, *args, **kwargs)+ print(value)+ except NotImplementedError:+ continue+ except AttributeError:+ continue+ return value++ return run_plugin_method+++def get_enabled_manager() -> BaseManager:+ manager_path = settings.EXTENSION_MANAGER+ manager_path, _, manager_name = manager_path.rpartition(".")+ manager_module = importlib.import_module(manager_path)+ manager_class = getattr(manager_module, manager_name, None)+ return manager_class()diff --git a/saleor/core/extensions/plugin.py b/saleor/core/extensions/plugin.pynew file mode 100644index 0000000000..06656448ef--- /dev/null+++ b/saleor/core/extensions/plugin.py@@ -0,0 +1,109 @@+from typing import TYPE_CHECKING, List, Union++from django_countries.fields import Country+from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange++from ..taxes import TaxType++if TYPE_CHECKING:+ from ...checkout.models import Checkout, CheckoutLine+ from ...product.models import Product+ from ...account.models import Address+ from ...order.models import OrderLine, Order+++class BasePlugin:+ """Abstract class for storing all methods available for any plugin."""++ def calculate_checkout_total(+ self, checkout: "Checkout", discounts: List["DiscountInfo"]+ ) -> TaxedMoney:+ raise NotImplementedError()++ def calculate_checkout_subtotal(+ self, checkout: "Checkout", discounts: List["DiscountInfo"]+ ) -> TaxedMoney:+ raise NotImplementedError()++ def calculate_checkout_shipping(+ self, checkout: "Checkout", discounts: List["DiscountInfo"]+ ) -> TaxedMoney:+ raise NotImplementedError()++ def calculate_order_shipping(self, order: "Order") -> TaxedMoney:+ raise NotImplementedError()++ def apply_taxes_to_shipping(+ self, price: Money, shipping_address: "Address"+ ) -> TaxedMoney:+ raise NotImplementedError()++ def get_tax_rate_type_choices(self) -> List[TaxType]:+ raise NotImplementedError()++ def calculate_checkout_line_total(+ self, checkout_line: "CheckoutLine", discounts: List["DiscountInfo"]+ ) -> TaxedMoney:+ raise NotImplementedError()++ def calculate_order_line_unit(self, order_line: "OrderLine") -> TaxedMoney:+ raise NotImplementedError()++ def apply_taxes_to_product(+ self, product: "Product", price: Money, country: Country, **kwargs+ ):+ raise NotImplementedError()++ def show_taxes_on_storefront(self) -> bool:+ raise NotImplementedError()++ def taxes_are_enabled(self) -> bool:+ raise NotImplementedError()++ def apply_taxes_to_shipping_price_range(+ self, prices: MoneyRange, country: Country+ ) -> TaxedMoneyRange:+ raise NotImplementedError()++ def preprocess_order_creation(+ self, checkout: "Checkout", discounts: List["DiscountInfo"]+ ):+ raise NotImplementedError()++ def postprocess_order_creation(self, order: "Order"):+ raise NotImplementedError()++ def assign_data_to_object_meta(+ self, obj: Union["Product", "ProductType"], data: str+ ):+ raise NotImplementedError()++ def get_data_from_object_meta(+ self, obj: Union["Product", "ProductType"]+ ) -> TaxType:+ raise NotImplementedError()+++class VatlayerPlugin(BasePlugin):+ """"""++ taxes = None+ # SimpleLazyObject(+ # lambda: get_taxes_for_country(request.country)+ # )++ def apply_taxes_to_product(+ self, product: "Product", price: Money, country: Country, **kwargs+ ):+ from ..taxes.vatlayer import get_taxes_for_country+ from ..taxes.vatlayer.interface import apply_taxes_to_product++ if not self.taxes:+ self.taxes = get_taxes_for_country(country)+ return apply_taxes_to_product(+ product, price, country, taxes=self.taxes, **kwargs+ )+++class AvalaraPlugin(BasePlugin):+ """"""diff --git a/saleor/core/middleware.py b/saleor/core/middleware.pyindex 478dae5cac..ca26915d95 100644--- a/saleor/core/middleware.py+++ b/saleor/core/middleware.py@@ -23,6 +23,7 @@ from django_countries.fields import Countryfrom ..discount.utils import fetch_discountsfrom . import analytics+from .extensions.manager import get_enabled_managerfrom .utils import get_client_ip, get_country_by_ip, get_currency_for_countrylogger = logging.getLogger(__name__)@@ -175,3 +176,16 @@ def taxes(get_response):return get_response(request)return middleware+++def extensions(get_response):+ """Assign extensions manager"""++ def _get_manager():+ return get_enabled_manager()++ def middleware(request):+ request.extensions = SimpleLazyObject(_get_manager)+ return get_response(request)++ return middlewarediff --git a/saleor/settings.py b/saleor/settings.pyindex 46471e6b8f..6467825fb9 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -658,3 +658,7 @@ GRAPHENE = {"RELAY_CONNECTION_ENFORCE_FIRST_OR_LAST": True,"RELAY_CONNECTION_MAX_LIMIT": 100,}++EXTENSIONS_MANAGER = "saleor.core.extensions.manager.BaseManager"++PLUGINS = []