Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add impelementation of plugin methods to the BaseManager

Maciej Korycinskib2a417b06561
diff --git a/saleor/core/extensions/checks.py b/saleor/core/extensions/checks.py
index 19ababd17c..9b77f10efe 100644
--- a/saleor/core/extensions/checks.py
+++ b/saleor/core/extensions/checks.py
@@ -1,11 +1,9 @@
import importlib
-from typing import List, Set
+from typing import List
from django.conf import settings
from django.core.checks import Error, register
-from .plugin import BasePlugin
-
@register()
def check_extensions(app_configs, **kwargs):
@@ -42,25 +40,11 @@ def check_manager(errors: List[Error]):
def check_plugins(errors: List[Error], plugins: List[str]):
- base_methods = set([name for name in vars(BasePlugin) if not name.startswith("_")])
- plugins_methods = set()
for plugin_path in plugins:
- check_single_plugin(plugin_path, errors, plugins_methods)
-
- if not errors:
- missing_methods = base_methods.difference(plugins_methods)
- for missing_method in missing_methods:
- errors.append(
- Error(
- "Implementation of base method %s not found in plugin classes"
- % missing_method
- )
- )
+ check_single_plugin(plugin_path, errors)
-def check_single_plugin(
- plugin_path: str, errors: List[Error], plugins_methods: Set[str]
-):
+def check_single_plugin(plugin_path: str, errors: List[Error]):
if not plugin_path:
errors.append(Error("Wrong plugin_path %s" % plugin_path))
return
@@ -78,8 +62,3 @@ def check_single_plugin(
% (plugin_name, str(plugin_module))
)
)
- else:
- for method_name in vars(plugin_class):
- if method_name.startswith("_"):
- continue
- plugins_methods.add(method_name)
diff --git a/saleor/core/extensions/default_plugin.py b/saleor/core/extensions/default_plugin.py
deleted file mode 100644
index f7caf8ec27..0000000000
--- a/saleor/core/extensions/default_plugin.py
+++ /dev/null
@@ -1,99 +0,0 @@
-from typing import TYPE_CHECKING, List, Union
-
-from django_countries.fields import Country
-from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
-
-from ..taxes import TaxType, quantize_price
-from .plugin import BasePlugin
-
-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 DefaultPlugin(BasePlugin):
- """Default plugin class - overwrites all base plugin methods.
- It should be enabled to cover all base methods in case when
- implementation doesn't use custom plugins"""
-
- def calculate_checkout_total(
- self, checkout: "Checkout", discounts: List["DiscountInfo"]
- ) -> TaxedMoney:
- total = checkout.get_total(discounts)
- return quantize_price(TaxedMoney(net=total, gross=total), total.currency)
-
- def calculate_checkout_subtotal(
- self, checkout: "Checkout", discounts: List["DiscountInfo"]
- ) -> TaxedMoney:
- subtotal = checkout.get_subtotal(discounts)
- return quantize_price(
- TaxedMoney(net=subtotal, gross=subtotal), subtotal.currency
- )
-
- def calculate_checkout_shipping(
- self, checkout: "Checkout", discounts: List["DiscountInfo"]
- ) -> TaxedMoney:
- total = checkout.get_shipping_price()
- total = TaxedMoney(net=total, gross=total)
- return quantize_price(total, total.currency)
-
- def calculate_order_shipping(self, order: "Order") -> TaxedMoney:
- shipping_price = order.shipping_method.price
- return quantize_price(
- TaxedMoney(net=shipping_price, gross=shipping_price),
- shipping_price.currency,
- )
-
- def calculate_checkout_line_total(
- self, checkout_line: "CheckoutLine", discounts: List["DiscountInfo"]
- ):
- total = checkout_line.get_total(discounts)
- return quantize_price(TaxedMoney(net=total, gross=total), total.currency)
-
- def calculate_order_line_unit(self, order_line: "OrderLine"):
- unit_price = order_line.unit_price
- return quantize_price(unit_price, unit_price.currency)
-
- def get_tax_rate_type_choices(self) -> List[TaxType]:
- return []
-
- def show_taxes_on_storefront(self) -> bool:
- return False
-
- def taxes_are_enabled(self) -> bool:
- return False
-
- def apply_taxes_to_product(
- self, product: "Product", price: Money, country: Country, **kwargs
- ):
- return quantize_price(TaxedMoney(net=price, gross=price), price.currency)
-
- def apply_taxes_to_shipping(
- self, price: Money, shipping_address: "Address"
- ) -> TaxedMoney:
- return quantize_price(TaxedMoney(net=price, gross=price), price.currency)
-
- def apply_taxes_to_shipping_price_range(self, prices: MoneyRange, country: Country):
- start = TaxedMoney(net=prices.start, gross=prices.start)
- stop = TaxedMoney(net=prices.stop, gross=prices.stop)
- return quantize_price(TaxedMoneyRange(start=start, stop=stop), start.currency)
-
- def preprocess_order_creation(
- self, checkout: "Checkout", discounts: List["DiscountInfo"]
- ):
- return
-
- def postprocess_order_creation(self, order: "Order"):
- return
-
- def assign_data_to_object_meta(
- self, obj: Union["Product", "ProductType"], tax_code: str
- ):
- return
-
- def get_data_from_object_meta(
- self, obj: Union["Product", "ProductType"]
- ) -> TaxType:
- return TaxType(code="", description="")
diff --git a/saleor/core/extensions/manager.py b/saleor/core/extensions/manager.py
index 4777dacb7f..7275878cc7 100644
--- a/saleor/core/extensions/manager.py
+++ b/saleor/core/extensions/manager.py
@@ -1,14 +1,21 @@
import importlib
-from typing import List
+from typing import TYPE_CHECKING, Any, List, Union
from django.conf import settings
+from django_countries.fields import Country
+from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
-from .plugin import BasePlugin
+from ..taxes import TaxType, quantize_price
+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 BaseManager(BasePlugin):
- """Base manager for handling a plugins logic. It inherits BasePlugin to support
- IDEs' hints"""
+
+class BaseManager:
+ """Base manager for handling a plugins logic"""
plugins = None
@@ -20,32 +27,148 @@ class BaseManager(BasePlugin):
plugin_class = getattr(plugin_module, plugin_name)
self.plugins.append(plugin_class())
- def __getattribute__(self, item: str):
- 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: str):
- def run_plugin_method(*args, **kwargs):
- value = None
- for p in self.plugins:
- try:
- plugin_value = getattr(p, name)(*args, **kwargs)
- # FIXME
- if plugin_value:
- value = plugin_value
- except NotImplementedError:
- continue
- except AttributeError:
- continue
- return value
-
- return run_plugin_method
+ def run_plugin_method(self, name: str, default_value: Any, *args, **kwargs):
+ value = default_value
+ for p in self.plugins:
+ plugin_value = getattr(p, name, NotImplemented)(
+ *args, **kwargs, previous_value=value
+ )
+ if plugin_value == NotImplemented:
+ continue
+ value = plugin_value
+ return value
+
+ def calculate_checkout_total(
+ self, checkout: "Checkout", discounts: List["DiscountInfo"]
+ ) -> TaxedMoney:
+ total = checkout.get_total(discounts)
+ default_value = quantize_price(
+ TaxedMoney(net=total, gross=total), total.currency
+ )
+ return self.run_plugin_method(
+ "calculate_checkout_total", default_value, checkout, discounts
+ )
+
+ def calculate_checkout_subtotal(
+ self, checkout: "Checkout", discounts: List["DiscountInfo"]
+ ) -> TaxedMoney:
+ subtotal = checkout.get_subtotal(discounts)
+ default_value = quantize_price(
+ TaxedMoney(net=subtotal, gross=subtotal), subtotal.currency
+ )
+ return self.run_plugin_method(
+ "calculate_checkout_subtotal", default_value, checkout, discounts
+ )
+
+ def calculate_checkout_shipping(
+ self, checkout: "Checkout", discounts: List["DiscountInfo"]
+ ) -> TaxedMoney:
+ total = checkout.get_shipping_price()
+ total = TaxedMoney(net=total, gross=total)
+ default_value = quantize_price(total, total.currency)
+ return self.run_plugin_method(
+ "calculate_checkout_shipping", default_value, checkout, discounts
+ )
+
+ def calculate_order_shipping(self, order: "Order") -> TaxedMoney:
+ shipping_price = order.shipping_method.price
+ default_value = quantize_price(
+ TaxedMoney(net=shipping_price, gross=shipping_price),
+ shipping_price.currency,
+ )
+ return self.run_plugin_method("calculate_order_shipping", default_value, order)
+
+ def calculate_checkout_line_total(
+ self, checkout_line: "CheckoutLine", discounts: List["DiscountInfo"]
+ ):
+ total = checkout_line.get_total(discounts)
+ default_value = quantize_price(
+ TaxedMoney(net=total, gross=total), total.currency
+ )
+ return self.run_plugin_method(
+ "calculate_checkout_line_total", default_value, checkout_line, discounts
+ )
+
+ def calculate_order_line_unit(self, order_line: "OrderLine"):
+ unit_price = order_line.unit_price
+ default_value = quantize_price(unit_price, unit_price.currency)
+ return self.run_plugin_method(
+ "calculate_order_line_unit", default_value, order_line
+ )
+
+ def get_tax_rate_type_choices(self) -> List[TaxType]:
+ default_value = []
+ return self.run_plugin_method("get_tax_rate_type_choices", default_value)
+
+ def show_taxes_on_storefront(self) -> bool:
+ default_value = False
+ return self.run_plugin_method("show_taxes_on_storefront", default_value)
+
+ def taxes_are_enabled(self) -> bool:
+
+ default_value = False
+ return self.run_plugin_method("taxes_are_enabled", default_value)
+
+ def apply_taxes_to_product(
+ self, product: "Product", price: Money, country: Country, **kwargs
+ ):
+ default_value = quantize_price(
+ TaxedMoney(net=price, gross=price), price.currency
+ )
+ return self.run_plugin_method(
+ "apply_taxes_to_product", default_value, product, price, country, **kwargs
+ )
+
+ def apply_taxes_to_shipping(
+ self, price: Money, shipping_address: "Address"
+ ) -> TaxedMoney:
+ default_value = quantize_price(
+ TaxedMoney(net=price, gross=price), price.currency
+ )
+ return self.run_plugin_method(
+ "apply_taxes_to_shipping", default_value, price, shipping_address
+ )
+
+ def apply_taxes_to_shipping_price_range(self, prices: MoneyRange, country: Country):
+ start = TaxedMoney(net=prices.start, gross=prices.start)
+ stop = TaxedMoney(net=prices.stop, gross=prices.stop)
+ default_value = quantize_price(
+ TaxedMoneyRange(start=start, stop=stop), start.currency
+ )
+ return self.run_plugin_method(
+ "apply_taxes_to_shipping_price_range", default_value, prices, country
+ )
+
+ def preprocess_order_creation(
+ self, checkout: "Checkout", discounts: List["DiscountInfo"]
+ ):
+ default_value = None
+ return self.run_plugin_method(
+ "preprocess_order_creation", default_value, checkout, discounts
+ )
+
+ def postprocess_order_creation(self, order: "Order"):
+ default_value = None
+ return self.run_plugin_method(
+ "postprocess_order_creation", default_value, order
+ )
+
+ # FIXME these methods should be more generic
+ def assign_tax_code_to_object_meta(
+ self, obj: Union["Product", "ProductType"], tax_code: str
+ ):
+ default_value = None
+ return self.run_plugin_method(
+ "assign_tax_code_to_object_meta", default_value, obj, tax_code
+ )
+
+ def get_tax_code_from_object_meta(
+ self, obj: Union["Product", "ProductType"]
+ ) -> TaxType:
+ default_value = TaxType(code="", description="")
+ return self.run_plugin_method(
+ "get_tax_code_from_object_meta", default_value, obj
+ )
def get_extensions_manager(
diff --git a/saleor/core/extensions/plugin.py b/saleor/core/extensions/plugin.py
index fe936580ff..86fe0d5d25 100644
--- a/saleor/core/extensions/plugin.py
+++ b/saleor/core/extensions/plugin.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, List, Union
+from typing import TYPE_CHECKING, Any, List, Union
from django_countries.fields import Country
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
@@ -12,72 +12,98 @@ if TYPE_CHECKING:
class BasePlugin:
- """Abstract class for storing all methods available for any plugin."""
+ """Abstract class for storing all methods available for any plugin. All methods
+ take previous_value parameter. previous_value contains a value calculated by the
+ previous plugin in the queue. If the plugin is first, it will use default value
+ calculated by the manager"""
def calculate_checkout_total(
- self, checkout: "Checkout", discounts: List["DiscountInfo"]
+ self,
+ checkout: "Checkout",
+ discounts: List["DiscountInfo"],
+ previous_value: TaxedMoney,
) -> TaxedMoney:
- raise NotImplementedError()
+ return NotImplemented
def calculate_checkout_subtotal(
- self, checkout: "Checkout", discounts: List["DiscountInfo"]
+ self,
+ checkout: "Checkout",
+ discounts: List["DiscountInfo"],
+ previous_value: TaxedMoney,
) -> TaxedMoney:
- raise NotImplementedError()
+ return NotImplemented
def calculate_checkout_shipping(
- self, checkout: "Checkout", discounts: List["DiscountInfo"]
+ self,
+ checkout: "Checkout",
+ discounts: List["DiscountInfo"],
+ previous_value: TaxedMoney,
) -> TaxedMoney:
- raise NotImplementedError()
+ return NotImplemented
- def calculate_order_shipping(self, order: "Order") -> TaxedMoney:
- raise NotImplementedError()
+ def calculate_order_shipping(
+ self, order: "Order", previous_value: TaxedMoney
+ ) -> TaxedMoney:
+ return NotImplemented
def calculate_checkout_line_total(
- self, checkout_line: "CheckoutLine", discounts: List["DiscountInfo"]
+ self,
+ checkout_line: "CheckoutLine",
+ discounts: List["DiscountInfo"],
+ previous_value: TaxedMoney,
) -> TaxedMoney:
- raise NotImplementedError()
+ return NotImplemented
- def calculate_order_line_unit(self, order_line: "OrderLine") -> TaxedMoney:
- raise NotImplementedError()
+ def calculate_order_line_unit(
+ self, order_line: "OrderLine", previous_value: TaxedMoney
+ ) -> TaxedMoney:
+ return NotImplemented
- def get_tax_rate_type_choices(self) -> List["TaxType"]:
- raise NotImplementedError()
+ def get_tax_rate_type_choices(
+ self, previous_value: List["TaxType"]
+ ) -> List["TaxType"]:
+ return NotImplemented
- def show_taxes_on_storefront(self) -> bool:
- raise NotImplementedError()
+ def show_taxes_on_storefront(self, previous_value: bool) -> bool:
+ return NotImplemented
- def taxes_are_enabled(self) -> bool:
- raise NotImplementedError()
+ def taxes_are_enabled(self, previous_value: bool) -> bool:
+ return NotImplemented
def apply_taxes_to_shipping_price_range(
- self, prices: MoneyRange, country: Country
+ self, prices: MoneyRange, country: Country, previous_value: TaxedMoneyRange
) -> TaxedMoneyRange:
- raise NotImplementedError()
+ return NotImplemented
def apply_taxes_to_shipping(
- self, price: Money, shipping_address: "Address"
+ self, price: Money, shipping_address: "Address", previous_value: TaxedMoney
) -> TaxedMoney:
- raise NotImplementedError()
+ return NotImplemented
def apply_taxes_to_product(
- self, product: "Product", price: Money, country: Country, **kwargs
- ):
- raise NotImplementedError()
+ self,
+ product: "Product",
+ price: Money,
+ country: Country,
+ previous_value: TaxedMoney,
+ **kwargs,
+ ) -> TaxedMoney:
+ return NotImplemented
def preprocess_order_creation(
- self, checkout: "Checkout", discounts: List["DiscountInfo"]
+ self, checkout: "Checkout", discounts: List["DiscountInfo"], previous_value: Any
):
- raise NotImplementedError()
+ return NotImplemented
- def postprocess_order_creation(self, order: "Order"):
- raise NotImplementedError()
+ def postprocess_order_creation(self, order: "Order", previous_value: Any):
+ return NotImplemented
- def assign_data_to_object_meta(
- self, obj: Union["Product", "ProductType"], data: str
+ def assign_tax_code_to_object_meta(
+ self, obj: Union["Product", "ProductType"], tax_code: str, previous_value: Any
):
- raise NotImplementedError()
+ return NotImplemented
- def get_data_from_object_meta(
- self, obj: Union["Product", "ProductType"]
+ def get_tax_code_from_object_meta(
+ self, obj: Union["Product", "ProductType"], previous_value: "TaxType"
) -> "TaxType":
- raise NotImplementedError()
+ return NotImplemented
diff --git a/tests/extensions/test_checks.py b/tests/extensions/test_checks.py
index b84980bf03..2219791a68 100644
--- a/tests/extensions/test_checks.py
+++ b/tests/extensions/test_checks.py
@@ -24,9 +24,3 @@ def test_check_extensions_wrong_declaration_of_plugins(plugin_path, settings):
settings.PLUGINS = [plugin_path]
errors = check_extensions({})
assert errors
-
-
-def test_check_extensions_missing_implementation_of_base_methods(settings):
- settings.PLUGINS = ["tests.extensions.test_checks.Test"]
- errors = check_extensions({})
- assert errors
diff --git a/tests/extensions/test_manager.py b/tests/extensions/test_manager.py
index ed5a5d4b50..6d4e45d5a3 100644
--- a/tests/extensions/test_manager.py
+++ b/tests/extensions/test_manager.py
@@ -1,26 +1,14 @@
-from unittest.mock import patch
-
-from saleor.core.extensions.default_plugin import DefaultPlugin
from saleor.core.extensions.manager import BaseManager, get_extensions_manager
+from saleor.core.extensions.plugin import BasePlugin
+
+
+class TestPlugin(BasePlugin):
+ """"""
def test_get_extensions_manager():
manager_path = "saleor.core.extensions.manager.BaseManager"
- dummy_plugin_path = "saleor.core.extensions.default_plugin.DefaultPlugin"
- manager = get_extensions_manager(
- manager_path=manager_path, plugins=[dummy_plugin_path]
- )
+ plugin_path = "tests.extensions.test_manager.TestPlugin"
+ manager = get_extensions_manager(manager_path=manager_path, plugins=[plugin_path])
assert isinstance(manager, BaseManager)
assert len(manager.plugins) == 1
- assert isinstance(manager.plugins[0], DefaultPlugin)
-
-
[email protected](DefaultPlugin, "calculate_checkout_total")
-def test_manager_can_run_plugin_methods(
- mock_calculate, checkout_with_item, discount_info
-):
- dummy_plugin_path = "saleor.core.extensions.default_plugin.DefaultPlugin"
- manager = BaseManager(plugins=[dummy_plugin_path])
- discounts = [discount_info]
- manager.calculate_checkout_total(checkout_with_item, discounts)
- assert mock_calculate.called
diff --git a/tests/extensions/test_standard_plugin.py b/tests/extensions/test_standard_plugin.py
deleted file mode 100644
index 73521edffb..0000000000
--- a/tests/extensions/test_standard_plugin.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from saleor.core.extensions.default_plugin import DefaultPlugin
-from saleor.core.extensions.plugin import BasePlugin
-
-
-def test_standard_plugin_overwrites_all_base_plugin_methods():
- assert isinstance(BasePlugin(), DefaultPlugin.__bases__[0])
- dummy_vars = vars(DefaultPlugin)
- for name in vars(BasePlugin):
- if name.startswith("__"):
- continue
- assert name in dummy_vars