Skip to content

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

Initial work on extension manager

Patryk Zawadzkiadeba158df24
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index bc7ec96481..f5be4aed71 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -4,16 +4,16 @@ It's recommended to use functions from calculations.py module to take in account
manager.
"""
-from typing import TYPE_CHECKING, List
+from typing import TYPE_CHECKING, Iterable, List, Optional
from prices import TaxedMoney
from ..core.taxes import quantize_price, zero_taxed_money
+from ..discount import DiscountInfo
if TYPE_CHECKING:
# flake8: noqa
from .models import Checkout, CheckoutLine
- from ..discount.types import DiscountsListType
def base_checkout_shipping_price(checkout: "Checkout") -> TaxedMoney:
@@ -44,9 +44,9 @@ def base_checkout_total(
def base_checkout_line_total(
- line: "CheckoutLine", discounts: "DiscountsListType" = None
+ line: "CheckoutLine", discounts: Optional[Iterable[DiscountInfo]] = None
) -> TaxedMoney:
"""Return the total price of this line."""
- amount = line.quantity * line.variant.get_price(discounts)
+ amount = line.quantity * line.variant.get_price(discounts or [])
price = quantize_price(amount, amount.currency)
return TaxedMoney(net=price, gross=price)
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 2a2fda64ce..fa136583f1 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -1,35 +1,39 @@
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Iterable, Optional
+from ..discount import DiscountInfo
from ..extensions.manager import get_extensions_manager
if TYPE_CHECKING:
from prices import TaxedMoney
from .models import Checkout, CheckoutLine
- from ..discount.types import DiscountsListType
def checkout_shipping_price(
- checkout: "Checkout", discounts: "DiscountsListType" = None
+ checkout: "Checkout", discounts: Optional[Iterable[DiscountInfo]] = None
) -> "TaxedMoney":
"""Return checkout shipping price.
It takes in account all extensions.
"""
- return get_extensions_manager().calculate_checkout_shipping(checkout, discounts)
+ return get_extensions_manager().calculate_checkout_shipping(
+ checkout, discounts or []
+ )
def checkout_subtotal(
- checkout: "Checkout", discounts: "DiscountsListType" = None
+ checkout: "Checkout", discounts: Optional[Iterable[DiscountInfo]] = None
) -> "TaxedMoney":
"""Return the total cost of all the checkout lines, taxes included.
It takes in account all extensions.
"""
- return get_extensions_manager().calculate_checkout_subtotal(checkout, discounts)
+ return get_extensions_manager().calculate_checkout_subtotal(
+ checkout, discounts or []
+ )
def checkout_total(
- checkout: "Checkout", discounts: "DiscountsListType" = None
+ checkout: "Checkout", discounts: Optional[Iterable[DiscountInfo]] = None
) -> "TaxedMoney":
"""Return the total cost of the checkout.
@@ -38,14 +42,14 @@ def checkout_total(
It takes in account all extensions.
"""
- return get_extensions_manager().calculate_checkout_total(checkout, discounts)
+ return get_extensions_manager().calculate_checkout_total(checkout, discounts or [])
def checkout_line_total(
- line: "CheckoutLine", discounts: "DiscountsListType" = None
+ line: "CheckoutLine", discounts: Optional[Iterable[DiscountInfo]] = None
) -> "TaxedMoney":
"""Return the total price of provided line, taxes included.
It takes in account all extensions.
"""
- return get_extensions_manager().calculate_checkout_line_total(line, discounts)
+ return get_extensions_manager().calculate_checkout_line_total(line, discounts or [])
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index f5afd361e3..9150367ed4 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -1,7 +1,7 @@
"""Checkout-related utility functions."""
from datetime import date
from decimal import Decimal
-from typing import TYPE_CHECKING, List, Optional, Tuple
+from typing import Iterable, List, Optional, Tuple
from django.core.exceptions import ValidationError
from django.db import transaction
@@ -21,7 +21,7 @@ from ..core.utils.promo_code import (
promo_code_is_gift_card,
promo_code_is_voucher,
)
-from ..discount import VoucherType
+from ..discount import DiscountInfo, VoucherType
from ..discount.models import NotApplicable, Voucher
from ..discount.utils import (
add_voucher_usage_by_customer,
@@ -45,9 +45,6 @@ from ..warehouse.management import allocate_stock
from . import AddressType
from .models import Checkout, CheckoutLine
-if TYPE_CHECKING:
- from ..discount.types import DiscountsListType
-
COOKIE_NAME = "checkout"
@@ -211,7 +208,7 @@ def change_shipping_address_in_checkout(checkout, address):
def _get_shipping_voucher_discount_for_checkout(
- voucher, checkout, discounts: "DiscountsListType" = None
+ voucher, checkout, discounts: Optional[Iterable[DiscountInfo]] = None
):
"""Calculate discount value for a voucher of shipping type."""
if not checkout.is_shipping_required():
@@ -233,7 +230,7 @@ def _get_shipping_voucher_discount_for_checkout(
def _get_products_voucher_discount(
- checkout, voucher, discounts: "DiscountsListType" = None
+ checkout, voucher, discounts: Optional[Iterable[DiscountInfo]] = None
):
"""Calculate products discount value for a voucher, depending on its type."""
prices = None
@@ -246,7 +243,9 @@ def _get_products_voucher_discount(
def get_prices_of_discounted_specific_product(
- lines: List[CheckoutLine], voucher: Voucher, discounts: "DiscountsListType" = None
+ lines: List[CheckoutLine],
+ voucher: Voucher,
+ discounts: Optional[Iterable[DiscountInfo]] = None,
) -> List[Money]:
"""Get prices of variants belonging to the discounted specific products.
@@ -287,7 +286,9 @@ def get_prices_of_discounted_specific_product(
def get_voucher_discount_for_checkout(
- voucher: Voucher, checkout: Checkout, discounts: "DiscountsListType" = None
+ voucher: Voucher,
+ checkout: Checkout,
+ discounts: Optional[Iterable[DiscountInfo]] = None,
) -> Money:
"""Calculate discount value depending on voucher and discount types.
@@ -321,7 +322,9 @@ def get_voucher_for_checkout(
return None
-def recalculate_checkout_discount(checkout: Checkout, discounts: "DiscountsListType"):
+def recalculate_checkout_discount(
+ checkout: Checkout, discounts: Iterable[DiscountInfo]
+):
"""Recalculate `checkout.discount` based on the voucher.
Will clear both voucher and discount if the discount is no longer
@@ -359,7 +362,9 @@ def recalculate_checkout_discount(checkout: Checkout, discounts: "DiscountsListT
def add_promo_code_to_checkout(
- checkout: Checkout, promo_code: str, discounts: "DiscountsListType" = None
+ checkout: Checkout,
+ promo_code: str,
+ discounts: Optional[Iterable[DiscountInfo]] = None,
):
"""Add gift card or voucher data to checkout.
@@ -374,7 +379,9 @@ def add_promo_code_to_checkout(
def add_voucher_code_to_checkout(
- checkout: Checkout, voucher_code: str, discounts: "DiscountsListType" = None
+ checkout: Checkout,
+ voucher_code: str,
+ discounts: Optional[Iterable[DiscountInfo]] = None,
):
"""Add voucher data to checkout by code.
@@ -398,7 +405,9 @@ def add_voucher_code_to_checkout(
def add_voucher_to_checkout(
- checkout: Checkout, voucher: Voucher, discounts: "DiscountsListType" = None
+ checkout: Checkout,
+ voucher: Voucher,
+ discounts: Optional[Iterable[DiscountInfo]] = None,
):
"""Add voucher data to checkout.
@@ -455,7 +464,7 @@ def remove_voucher_from_checkout(checkout: Checkout):
def get_valid_shipping_methods_for_checkout(
checkout: Checkout,
- discounts: "DiscountsListType",
+ discounts: Iterable[DiscountInfo],
country_code: Optional[str] = None,
):
manager = get_extensions_manager()
@@ -466,7 +475,7 @@ def get_valid_shipping_methods_for_checkout(
)
-def is_valid_shipping_method(checkout: Checkout, discounts: "DiscountsListType"):
+def is_valid_shipping_method(checkout: Checkout, discounts: Iterable[DiscountInfo]):
"""Check if shipping method is valid and remove (if not)."""
if not checkout.shipping_method:
return False
@@ -479,7 +488,7 @@ def is_valid_shipping_method(checkout: Checkout, discounts: "DiscountsListType")
def get_shipping_price_estimate(
- checkout: Checkout, discounts: "DiscountsListType", country_code: str
+ checkout: Checkout, discounts: Iterable[DiscountInfo], country_code: str
) -> Optional[TaxedMoneyRange]:
"""Return the estimated price range for shipping for given order."""
@@ -755,7 +764,7 @@ def create_order(
return order
-def is_fully_paid(checkout: Checkout, discounts: "DiscountsListType"):
+def is_fully_paid(checkout: Checkout, discounts: Iterable[DiscountInfo]):
"""Check if provided payment methods cover the checkout's total amount.
Note that these payments may not be captured or charged at all.
@@ -772,7 +781,7 @@ def is_fully_paid(checkout: Checkout, discounts: "DiscountsListType"):
return total_paid >= checkout_total.amount
-def clean_checkout(checkout: Checkout, discounts: "DiscountsListType"):
+def clean_checkout(checkout: Checkout, discounts: Iterable[DiscountInfo]):
"""Check if checkout can be completed."""
if checkout.is_shipping_required():
if not checkout.shipping_method:
diff --git a/saleor/discount/types.py b/saleor/discount/types.py
deleted file mode 100644
index a372c167d2..0000000000
--- a/saleor/discount/types.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from typing import Iterable, Optional
-
-from . import DiscountInfo
-
-DiscountsListType = Optional[Iterable[DiscountInfo]]
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 7f21a578d1..0cb8c8652d 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -14,7 +14,6 @@ from .models import NotApplicable, Sale, VoucherCustomer
if TYPE_CHECKING:
# flake8: noqa
from .models import Voucher
- from .types import DiscountsListType
from ..product.models import Product
from ..checkout.models import Checkout
from ..order.models import Order
@@ -63,7 +62,9 @@ def get_product_discount_on_sale(
raise NotApplicable("Discount not applicable for this product")
-def get_product_discounts(product: "Product", discounts: "DiscountsListType") -> Money:
+def get_product_discounts(
+ product: "Product", discounts: Iterable[DiscountInfo]
+) -> Money:
"""Return discount values for all discounts applicable to a product."""
product_collections = set(product.collections.all().values_list("pk", flat=True))
for discount in discounts or []:
@@ -74,7 +75,7 @@ def get_product_discounts(product: "Product", discounts: "DiscountsListType") ->
def calculate_discounted_price(
- product: "Product", price: Money, discounts: "DiscountsListType"
+ product: "Product", price: Money, discounts: Iterable[DiscountInfo]
) -> Money:
"""Return minimum product's price of all prices with discounts applied."""
if discounts:
@@ -85,7 +86,7 @@ def calculate_discounted_price(
def validate_voucher_for_checkout(
- voucher: "Voucher", checkout: "Checkout", discounts: "DiscountsListType"
+ voucher: "Voucher", checkout: "Checkout", discounts: Iterable[DiscountInfo],
):
subtotal = calculations.checkout_subtotal(checkout, discounts)
diff --git a/saleor/extensions/base_plugin.py b/saleor/extensions/base_plugin.py
index 0e3566be00..76848634c2 100644
--- a/saleor/extensions/base_plugin.py
+++ b/saleor/extensions/base_plugin.py
@@ -2,7 +2,6 @@ from copy import copy
from decimal import Decimal
from typing import TYPE_CHECKING, Any, List, Optional, Union
-from django.db.models import QuerySet
from django_countries.fields import Country
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
@@ -20,6 +19,9 @@ if TYPE_CHECKING:
from ..payment.interface import GatewayResponse, PaymentData, CustomerSource
+PluginConfigurationType = List[dict]
+
+
class BasePlugin:
"""Abstract class for storing all methods available for any plugin.
@@ -29,24 +31,18 @@ class BasePlugin:
"""
PLUGIN_NAME = ""
+ PLUGIN_DESCRIPTION = ""
CONFIG_STRUCTURE = None
+ DEFAULT_CONFIGURATION = []
+ DEFAULT_ACTIVE = False
- def __init__(self, *args, **kwargs):
- self._cached_config = None
- self.active = None
+ def __init__(self, *, configuration: PluginConfigurationType, active: bool):
+ self.configuration = self.get_plugin_configuration(configuration)
+ self.active = active
def __str__(self):
return self.PLUGIN_NAME
- def _initialize_plugin_configuration(self):
- """Initialize plugin by fetching configuration from internal cache or DB."""
- plugin_config_qs = PluginConfiguration.objects.filter(name=self.PLUGIN_NAME)
- plugin_config = self._cached_config or plugin_config_qs.first()
-
- if plugin_config:
- self._cached_config = plugin_config
- self.active = plugin_config.active
-
def change_user_address(
self,
address: "Address",
@@ -361,17 +357,6 @@ class BasePlugin:
cls._append_config_structure(plugin_configuration.configuration)
return plugin_configuration
- @classmethod
- def _get_default_configuration(cls):
- """Return default configuration for plugin.
-
- Each configurable plugin has to provide the default structure of the
- configuration. If plugin configuration is not found in DB, the manager will use
- the config structure to create a new one in DB.
- """
- defaults = None
- return defaults
-
@classmethod
def _append_config_structure(cls, configuration):
"""Append configuration structure to config from the database.
@@ -392,39 +377,23 @@ class BasePlugin:
config_structure = getattr(cls, "CONFIG_STRUCTURE") or {}
desired_config_keys = set(config_structure.keys())
- config = configuration.configuration or []
+ config = configuration or []
configured_keys = set(d["name"] for d in config)
missing_keys = desired_config_keys - configured_keys
if not missing_keys:
return
- default_config = cls._get_default_configuration()
+ default_config = cls.DEFAULT_CONFIGURATION
if not default_config:
return
- update_values = [
- copy(k)
- for k in default_config["configuration"]
- if k["name"] in missing_keys
- ]
+ update_values = [copy(k) for k in default_config if k["name"] in missing_keys]
config.extend(update_values)
- configuration.configuration = config
- configuration.save(update_fields=["configuration"])
-
- @classmethod
- def get_plugin_configuration(
- cls, queryset: QuerySet = None
- ) -> "PluginConfiguration":
- if not queryset:
- queryset = PluginConfiguration.objects.all()
- defaults = cls._get_default_configuration()
- configuration = queryset.get_or_create(name=cls.PLUGIN_NAME, defaults=defaults)[
- 0
- ]
- cls._update_configuration_structure(configuration)
- if configuration.configuration:
+ def get_plugin_configuration(self, configuration: dict) -> "PluginConfiguration":
+ self._update_configuration_structure(configuration)
+ if configuration:
# Let's add a translated descriptions and labels
- cls._append_config_structure(configuration.configuration)
+ self._append_config_structure(configuration)
return configuration
diff --git a/saleor/extensions/manager.py b/saleor/extensions/manager.py
index 0b89594f02..008eb83a45 100644
--- a/saleor/extensions/manager.py
+++ b/saleor/extensions/manager.py
@@ -1,5 +1,5 @@
from decimal import Decimal
-from typing import TYPE_CHECKING, Any, List, Optional, Union
+from typing import TYPE_CHECKING, Any, List, Iterable, Optional, Union
from django.conf import settings
from django.utils.module_loading import import_string
@@ -9,14 +9,14 @@ from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
from ..checkout import base_calculations
from ..core.payments import PaymentInterface
from ..core.taxes import TaxType, quantize_price, zero_taxed_money
+from ..discount import DiscountInfo
from .models import PluginConfiguration
if TYPE_CHECKING:
# flake8: noqa
from django.db.models.query import QuerySet
- from .base_plugin import BasePlugin
+ from .base_plugin import BasePlugin, PluginConfigurationType
from ..checkout.models import Checkout, CheckoutLine
- from ..discount.types import DiscountsListType
from ..product.models import Product, ProductType
from ..account.models import Address, User
from ..order.models import Fulfillment, OrderLine, Order
@@ -35,9 +35,17 @@ class ExtensionsManager(PaymentInterface):
def __init__(self, plugins: List[str]):
self.plugins = []
+ all_configs = self._get_all_plugin_configs()
for plugin_path in plugins:
- plugin_class = import_string(plugin_path)
- self.plugins.append(plugin_class())
+ PluginClass: "BasePlugin" = import_string(plugin_path)
+ if PluginClass.PLUGIN_NAME in all_configs:
+ existing_config = all_configs[PluginClass.PLUGIN_NAME]
+ plugin_config = existing_config.configuration
+ active = existing_config.active
+ else:
+ plugin_config = PluginClass.DEFAULT_CONFIGURATION
+ active = PluginClass.DEFAULT_ACTIVE
+ self.plugins.append(PluginClass(configuration=plugin_config, active=active))
def __run_method_on_plugins(
self, method_name: str, default_value: Any, *args, **kwargs
@@ -85,7 +93,7 @@ class ExtensionsManager(PaymentInterface):
self.__run_method_on_plugins("checkout_quantity_changed", None, checkout)
def calculate_checkout_total(
- self, checkout: "Checkout", discounts: "DiscountsListType"
+ self, checkout: "Checkout", discounts: Iterable[DiscountInfo]
) -> TaxedMoney:
default_value = base_calculations.base_checkout_total(
@@ -99,7 +107,7 @@ class ExtensionsManager(PaymentInterface):
)
def calculate_checkout_subtotal(
- self, checkout: "Checkout", discounts: "DiscountsListType"
+ self, checkout: "Checkout", discounts: Iterable[DiscountInfo]
) -> TaxedMoney:
line_totals = [
self.calculate_checkout_line_total(line, discounts) for line in checkout
@@ -112,7 +120,7 @@ class ExtensionsManager(PaymentInterface):
)
def calculate_checkout_shipping(
- self, checkout: "Checkout", discounts: "DiscountsListType"
+ self, checkout: "Checkout", discounts: Iterable[DiscountInfo]
) -> TaxedMoney:
default_value = base_calculations.base_checkout_shipping_price(checkout)
return self.__run_method_on_plugins(
@@ -132,7 +140,7 @@ class ExtensionsManager(PaymentInterface):
)
def calculate_checkout_line_total(
- self, checkout_line: "CheckoutLine", discounts: "DiscountsListType"
+ self, checkout_line: "CheckoutLine", discounts: Iterable[DiscountInfo]
):
default_value = base_calculations.base_checkout_line_total(
checkout_line, discounts
@@ -187,7 +195,7 @@ class ExtensionsManager(PaymentInterface):
)
def preprocess_order_creation(
- self, checkout: "Checkout", discounts: "DiscountsListType"
+ self, checkout: "Checkout", discounts: Iterable[DiscountInfo]
):
default_value = None
return self.__run_method_on_plugins(
@@ -286,11 +294,7 @@ class ExtensionsManager(PaymentInterface):
def get_active_plugins(self, plugins=None) -> List["BasePlugin"]:
if plugins is None:
plugins = self.plugins
- return [
- plugin
- for plugin in plugins
- if getattr(self.get_plugin_configuration(plugin.PLUGIN_NAME), "active")
- ]
+ return [plugin for plugin in plugins if plugin.active]
def list_payment_plugin_names(self, active_only: bool = False) -> List[str]:
payment_method = "process_payment"
@@ -341,6 +345,13 @@ class ExtensionsManager(PaymentInterface):
" payment method is inaccessible!"
)
+ def _get_all_plugin_configs(self):
+ if not hasattr(self, "_plugin_configs"):
+ self._plugin_configs = {
+ pc.name: pc for pc in PluginConfiguration.objects.all()
+ }
+ return self._plugin_configs
+
# FIXME these methods should be more generic
def assign_tax_code_to_object_meta(
@@ -381,23 +392,6 @@ class ExtensionsManager(PaymentInterface):
return plugin
return None
- def get_plugin_configuration(self, plugin_name) -> Optional["PluginConfiguration"]:
- plugin = self.get_plugin(plugin_name)
- if plugin is not None:
- plugin_configurations_qs = PluginConfiguration.objects.all()
- return plugin.get_plugin_configuration(plugin_configurations_qs)
- return None
-
- def get_plugin_configurations(self) -> "QuerySet[PluginConfiguration]":
- plugin_configuration_ids = []
- plugin_configurations_qs = PluginConfiguration.objects.all()
- for plugin in self.plugins:
- plugin_configuration = plugin.get_plugin_configuration(
- plugin_configurations_qs
- )
- plugin_configuration_ids.append(plugin_configuration.pk)
- return PluginConfiguration.objects.filter(pk__in=plugin_configuration_ids)
-
def get_extensions_manager(
manager_path: str = None, plugins: List[str] = None
diff --git a/saleor/extensions/plugins/anonymize/plugin.py b/saleor/extensions/plugins/anonymize/plugin.py
index 2bb6939d86..4d70c78db3 100644
--- a/saleor/extensions/plugins/anonymize/plugin.py
+++ b/saleor/extensions/plugins/anonymize/plugin.py
@@ -12,6 +12,11 @@ class AnonymizePlugin(BasePlugin):
"""Anonymize all user data in the checkout, user profile and its orders."""
PLUGIN_NAME = "Anonymize"
+ DEFAULT_ACTIVE = True
+ PLUGIN_DESCRIPTION = (
+ "Anonymize customer's personal data in the checkout, such as shipping "
+ "or billing address, email and phone number."
+ )
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -37,16 +42,3 @@ class AnonymizePlugin(BasePlugin):
def customer_created(self, customer: "User", previous_value: Any) -> Any:
customer.email = obfuscate_email(customer.email)
customer.save()
-
- @classmethod
- def _get_default_configuration(cls):
- defaults = {
- "name": cls.PLUGIN_NAME,
- "description": (
- "Anonymize customer's personal data in the checkout, such as shipping "
- "or billing address, email and phone number."
- ),
- "active": True,
- "configuration": None,
- }
- return defaults
diff --git a/saleor/extensions/plugins/avatax/plugin.py b/saleor/extensions/plugins/avatax/plugin.py
index 6ce46f8e1e..b702ff8e6a 100644
--- a/saleor/extensions/plugins/avatax/plugin.py
+++ b/saleor/extensions/plugins/avatax/plugin.py
@@ -1,13 +1,13 @@
import logging
from decimal import Decimal
-from typing import TYPE_CHECKING, Any, Dict, List, Union
+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Union
from urllib.parse import urljoin
-from django.conf import settings
from django.core.exceptions import ValidationError
from prices import Money, TaxedMoney, TaxedMoneyRange
from ....core.taxes import TaxError, TaxType, zero_taxed_money
+from ....discount import DiscountInfo
from ... import ConfigurationTypeField
from ...base_plugin import BasePlugin
from ...error_codes import ExtensionsErrorCode
@@ -34,7 +34,6 @@ if TYPE_CHECKING:
from ....order.models import Order, OrderLine
from ....product.models import Product, ProductType
from ...models import PluginConfiguration
- from ....discount.types import DiscountsListType
logger = logging.getLogger(__name__)
@@ -42,6 +41,13 @@ logger = logging.getLogger(__name__)
class AvataxPlugin(BasePlugin):
PLUGIN_NAME = "Avalara"
+ DEFAULT_CONFIGURATION = [
+ {"name": "Username or account", "value": None},
+ {"name": "Password or license", "value": None},
+ {"name": "Use sandbox", "value": True},
+ {"name": "Company name", "value": "DEFAULT"},
+ {"name": "Autocommit", "value": False},
+ ]
CONFIG_STRUCTURE = {
"Username or account": {
"type": ConfigurationTypeField.STRING,
@@ -76,37 +82,15 @@ class AvataxPlugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- self.config = None
-
- def _initialize_plugin_configuration(self):
- super()._initialize_plugin_configuration()
-
- if self._cached_config and self._cached_config.configuration:
- configuration = self._cached_config.configuration
-
- # Convert to dict to easier take config elements
- configuration = {item["name"]: item["value"] for item in configuration}
- self.config = AvataxConfiguration(
- username_or_account=configuration["Username or account"],
- password_or_license=configuration["Password or license"],
- use_sandbox=configuration["Use sandbox"],
- company_name=configuration["Company name"],
- autocommit=configuration["Autocommit"],
- )
- else:
- # This should be removed after we drop an Avatax's settings from Django
- # settings file
- self.config = AvataxConfiguration(
- username_or_account=settings.AVATAX_USERNAME_OR_ACCOUNT,
- password_or_license=settings.AVATAX_PASSWORD_OR_LICENSE,
- use_sandbox=settings.AVATAX_USE_SANDBOX,
- autocommit=settings.AVATAX_AUTOCOMMIT,
- company_name=settings.AVATAX_COMPANY_NAME,
- )
- self.active = (
- settings.AVATAX_USERNAME_OR_ACCOUNT
- and settings.AVATAX_PASSWORD_OR_LICENSE
- )
+ # Convert to dict to easier take config elements
+ configuration = {item["name"]: item["value"] for item in self.configuration}
+ self.config = AvataxConfiguration(
+ username_or_account=configuration["Username or account"],
+ password_or_license=configuration["Password or license"],
+ use_sandbox=configuration["Use sandbox"],
+ company_name=configuration["Company name"],
+ autocommit=configuration["Autocommit"],
+ )
def _skip_plugin(self, previous_value: Union[TaxedMoney, TaxedMoneyRange]) -> bool:
if not (self.config.username_or_account and self.config.password_or_license):
@@ -129,11 +113,9 @@ class AvataxPlugin(BasePlugin):
def calculate_checkout_total(
self,
checkout: "Checkout",
- discounts: "DiscountsListType",
+ discounts: Iterable[DiscountInfo],
previous_value: TaxedMoney,
) -> TaxedMoney:
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
@@ -173,11 +155,9 @@ class AvataxPlugin(BasePlugin):
def calculate_checkout_subtotal(
self,
checkout: "Checkout",
- discounts: "DiscountsListType",
+ discounts: Iterable[DiscountInfo],
previous_value: TaxedMoney,
) -> TaxedMoney:
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
@@ -210,11 +190,9 @@ class AvataxPlugin(BasePlugin):
def calculate_checkout_shipping(
self,
checkout: "Checkout",
- discounts: "DiscountsListType",
+ discounts: Iterable[DiscountInfo],
previous_value: TaxedMoney,
) -> TaxedMoney:
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
@@ -232,14 +210,15 @@ class AvataxPlugin(BasePlugin):
)
def preprocess_order_creation(
- self, checkout: "Checkout", discounts: "DiscountsListType", previous_value: Any
+ self,
+ checkout: "Checkout",
+ discounts: Iterable[DiscountInfo],
+ previous_value: Any,
):
"""Ensure all the data is correct and we can proceed with creation of order.
Raise an error when can't receive taxes.
"""
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
@@ -269,8 +248,6 @@ class AvataxPlugin(BasePlugin):
return previous_value
def order_created(self, order: "Order", previous_value: Any) -> Any:
- self._initialize_plugin_configuration()
-
if not self.active:
return previous_value
data = get_order_tax_data(order, self.config, force_refresh=True)
@@ -284,11 +261,9 @@ class AvataxPlugin(BasePlugin):
def calculate_checkout_line_total(
self,
checkout_line: "CheckoutLine",
- discounts: "DiscountsListType",
+ discounts: Iterable[DiscountInfo],
previous_value: TaxedMoney,
) -> TaxedMoney:
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
@@ -326,8 +301,6 @@ class AvataxPlugin(BasePlugin):
def calculate_order_line_unit(
self, order_line: "OrderLine", previous_value: TaxedMoney
) -> TaxedMoney:
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
@@ -338,8 +311,6 @@ class AvataxPlugin(BasePlugin):
def calculate_order_shipping(
self, order: "Order", previous_value: TaxedMoney
) -> TaxedMoney:
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
@@ -361,8 +332,6 @@ class AvataxPlugin(BasePlugin):
)
def get_tax_rate_type_choices(self, previous_value: Any) -> List[TaxType]:
- self._initialize_plugin_configuration()
-
if not self.active:
return previous_value
return [
@@ -373,8 +342,6 @@ class AvataxPlugin(BasePlugin):
def assign_tax_code_to_object_meta(
self, obj: Union["Product", "ProductType"], tax_code: str, previous_value: Any
):
- self._initialize_plugin_configuration()
-
if not self.active:
return previous_value
@@ -390,8 +357,6 @@ class AvataxPlugin(BasePlugin):
def get_tax_code_from_object_meta(
self, obj: Union["Product", "ProductType"], previous_value: Any
) -> TaxType:
- self._initialize_plugin_configuration()
-
if not self.active:
return previous_value
tax_code = obj.get_value_from_metadata(META_CODE_KEY, "")
@@ -399,8 +364,6 @@ class AvataxPlugin(BasePlugin):
return TaxType(code=tax_code, description=tax_description,)
def show_taxes_on_storefront(self, previous_value: bool) -> bool:
- self._initialize_plugin_configuration()
-
if not self.active:
return previous_value
return False
@@ -425,19 +388,3 @@ class AvataxPlugin(BasePlugin):
error_msg + ", ".join(missing_fields),
code=ExtensionsErrorCode.PLUGIN_MISCONFIGURED.value,
)
-
- @classmethod
- def _get_default_configuration(cls):
- defaults = {
- "name": cls.PLUGIN_NAME,
- "description": "",
- "active": False,
- "configuration": [
- {"name": "Username or account", "value": None},
- {"name": "Password or license", "value": None},
- {"name": "Use sandbox", "value": True},
- {"name": "Company name", "value": "DEFAULT"},
- {"name": "Autocommit", "value": False},
- ],
- }
- return defaults
diff --git a/saleor/extensions/plugins/vatlayer/plugin.py b/saleor/extensions/plugins/vatlayer/plugin.py
index c410a157b8..190d94218a 100644
--- a/saleor/extensions/plugins/vatlayer/plugin.py
+++ b/saleor/extensions/plugins/vatlayer/plugin.py
@@ -31,22 +31,14 @@ if TYPE_CHECKING:
class VatlayerPlugin(BasePlugin):
PLUGIN_NAME = "Vatlayer"
+ DEFAULT_ACTIVE = bool(settings.VATLAYER_ACCESS_KEY)
META_CODE_KEY = "vatlayer.code"
META_DESCRIPTION_KEY = "vatlayer.description"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- self._enabled = bool(settings.VATLAYER_ACCESS_KEY)
self._cached_taxes = {}
- def _initialize_plugin_configuration(self):
- super()._initialize_plugin_configuration()
-
- if not self._cached_config:
- # This should be removed after we drop an Vatl's settings from Django
- # settings file
- self.active = bool(settings.VATLAYER_ACCESS_KEY)
-
def _skip_plugin(self, previous_value: Union[TaxedMoney, TaxedMoneyRange]) -> bool:
if not self.active or not settings.VATLAYER_ACCESS_KEY:
return True
@@ -68,9 +60,6 @@ class VatlayerPlugin(BasePlugin):
discounts: List["DiscountInfo"],
previous_value: TaxedMoney,
) -> TaxedMoney:
-
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
@@ -102,8 +91,6 @@ class VatlayerPlugin(BasePlugin):
previous_value: TaxedMoney,
) -> TaxedMoney:
"""Calculate shipping gross for checkout."""
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
@@ -119,8 +106,6 @@ class VatlayerPlugin(BasePlugin):
def calculate_order_shipping(
self, order: "Order", previous_value: TaxedMoney
) -> TaxedMoney:
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
@@ -138,8 +123,6 @@ class VatlayerPlugin(BasePlugin):
discounts: List["DiscountInfo"],
previous_value: TaxedMoney,
) -> TaxedMoney:
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
@@ -157,8 +140,6 @@ class VatlayerPlugin(BasePlugin):
def calculate_order_line_unit(
self, order_line: "OrderLine", previous_value: TaxedMoney
) -> TaxedMoney:
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
@@ -174,8 +155,6 @@ class VatlayerPlugin(BasePlugin):
def get_tax_rate_type_choices(
self, previous_value: List["TaxType"]
) -> List["TaxType"]:
- self._initialize_plugin_configuration()
-
if not self.active:
return previous_value
@@ -187,8 +166,6 @@ class VatlayerPlugin(BasePlugin):
return sorted(choices, key=lambda x: x.code)
def show_taxes_on_storefront(self, previous_value: bool) -> bool:
- self._initialize_plugin_configuration()
-
if not self.active:
return previous_value
return True
@@ -196,8 +173,6 @@ class VatlayerPlugin(BasePlugin):
def apply_taxes_to_shipping_price_range(
self, prices: MoneyRange, country: Country, previous_value: TaxedMoneyRange
) -> TaxedMoneyRange:
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
@@ -207,8 +182,6 @@ class VatlayerPlugin(BasePlugin):
def apply_taxes_to_shipping(
self, price: Money, shipping_address: "Address", previous_value: TaxedMoney
) -> TaxedMoney:
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
@@ -222,8 +195,6 @@ class VatlayerPlugin(BasePlugin):
country: Country,
previous_value: TaxedMoney,
) -> TaxedMoney:
- self._initialize_plugin_configuration()
-
if self._skip_plugin(previous_value):
return previous_value
return self.__apply_taxes_to_product(product, price, country)
@@ -245,8 +216,6 @@ class VatlayerPlugin(BasePlugin):
def assign_tax_code_to_object_meta(
self, obj: Union["Product", "ProductType"], tax_code: str, previous_value: Any
):
- self._initialize_plugin_configuration()
-
if not self.active:
return previous_value
@@ -261,8 +230,6 @@ class VatlayerPlugin(BasePlugin):
def get_tax_code_from_object_meta(
self, obj: Union["Product", "ProductType"], previous_value: "TaxType"
) -> "TaxType":
- self._initialize_plugin_configuration()
-
if not self.active:
return previous_value
return self.__get_tax_code_from_object_meta(obj)
@@ -278,8 +245,6 @@ class VatlayerPlugin(BasePlugin):
self, obj: Union["Product", "ProductType"], country: Country, previous_value
) -> Decimal:
"""Return tax rate percentage value for given tax rate type in the country."""
- self._initialize_plugin_configuration()
-
if not self.active:
return previous_value
taxes = self._get_taxes_for_country(country)
@@ -297,13 +262,3 @@ class VatlayerPlugin(BasePlugin):
"Cannot be enabled without provided 'settings.VATLAYER_ACCESS_KEY'",
code=ExtensionsErrorCode.PLUGIN_MISCONFIGURED.value,
)
-
- @classmethod
- def _get_default_configuration(cls):
- defaults = {
- "name": cls.PLUGIN_NAME,
- "description": "",
- "active": bool(settings.VATLAYER_ACCESS_KEY),
- "configuration": None,
- }
- return defaults
diff --git a/saleor/extensions/plugins/webhook/plugin.py b/saleor/extensions/plugins/webhook/plugin.py
index ffb264f45a..8b3ac1b930 100644
--- a/saleor/extensions/plugins/webhook/plugin.py
+++ b/saleor/extensions/plugins/webhook/plugin.py
@@ -20,48 +20,43 @@ if TYPE_CHECKING:
class WebhookPlugin(BasePlugin):
PLUGIN_NAME = "Webhooks"
+ DEFAULT_ACTIVE = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.active = True
def order_created(self, order: "Order", previous_value: Any) -> Any:
- self._initialize_plugin_configuration()
if not self.active:
return previous_value
order_data = generate_order_payload(order)
trigger_webhooks_for_event.delay(WebhookEventType.ORDER_CREATED, order_data)
def order_fully_paid(self, order: "Order", previous_value: Any) -> Any:
- self._initialize_plugin_configuration()
if not self.active:
return previous_value
order_data = generate_order_payload(order)
trigger_webhooks_for_event.delay(WebhookEventType.ORDER_FULLY_PAID, order_data)
def order_updated(self, order: "Order", previous_value: Any) -> Any:
- self._initialize_plugin_configuration()
if not self.active:
return previous_value
order_data = generate_order_payload(order)
trigger_webhooks_for_event.delay(WebhookEventType.ORDER_UPDATED, order_data)
def order_cancelled(self, order: "Order", previous_value: Any) -> Any:
- self._initialize_plugin_configuration()
if not self.active:
return previous_value
order_data = generate_order_payload(order)
trigger_webhooks_for_event.delay(WebhookEventType.ORDER_CANCELLED, order_data)
def order_fulfilled(self, order: "Order", previous_value: Any) -> Any:
- self._initialize_plugin_configuration()
if not self.active:
return previous_value
order_data = generate_order_payload(order)
trigger_webhooks_for_event.delay(WebhookEventType.ORDER_FULFILLED, order_data)
def fulfillment_created(self, fulfillment: "Fulfillment", previous_value):
- self._initialize_plugin_configuration()
if not self.active:
return previous_value
@@ -71,7 +66,6 @@ class WebhookPlugin(BasePlugin):
)
def customer_created(self, customer: "User", previous_value: Any) -> Any:
- self._initialize_plugin_configuration()
if not self.active:
return previous_value
@@ -81,7 +75,6 @@ class WebhookPlugin(BasePlugin):
)
def product_created(self, product: "Product", previous_value: Any) -> Any:
- self._initialize_plugin_configuration()
if not self.active:
return previous_value
product_data = generate_product_payload(product)
@@ -90,20 +83,9 @@ class WebhookPlugin(BasePlugin):
def checkout_quantity_changed(
self, checkout: "Checkout", previous_value: Any
) -> Any:
- self._initialize_plugin_configuration()
if not self.active:
return previous_value
checkout_data = generate_checkout_payload(checkout)
trigger_webhooks_for_event.delay(
WebhookEventType.CHECKOUT_QUANTITY_CHANGED, checkout_data
)
-
- @classmethod
- def _get_default_configuration(cls):
- defaults = {
- "name": cls.PLUGIN_NAME,
- "description": "",
- "active": True,
- "configuration": None,
- }
- return defaults
diff --git a/saleor/graphql/extensions/resolvers.py b/saleor/graphql/extensions/resolvers.py
index 96ec74aabd..e1fbf3de4d 100644
--- a/saleor/graphql/extensions/resolvers.py
+++ b/saleor/graphql/extensions/resolvers.py
@@ -1,20 +1,41 @@
-import graphene
-
+from ...extensions.base_plugin import BasePlugin
from ...extensions.manager import get_extensions_manager
-from ..utils import sort_queryset
from .sorters import PluginSortField
-from .types import Plugin
def resolve_plugin(info, plugin_global_id):
manager = get_extensions_manager()
- plugin = graphene.Node.get_node_from_global_id(info, plugin_global_id, Plugin)
+ plugin: BasePlugin = manager.get_plugin(plugin_global_id)
if not plugin:
return None
- return manager.get_plugin_configuration(plugin.name)
+ return {
+ "id": plugin.PLUGIN_NAME,
+ "active": plugin.active,
+ "configuration": plugin.configuration,
+ "description": plugin.PLUGIN_DESCRIPTION,
+ "name": plugin.PLUGIN_NAME,
+ }
def resolve_plugins(sort_by=None, **_kwargs):
manager = get_extensions_manager()
- qs = manager.get_plugin_configurations()
- return sort_queryset(qs, sort_by, PluginSortField)
+ sort_field = (
+ sort_by.get("field", PluginSortField.NAME) if sort_by else PluginSortField.NAME
+ )
+ sort_reverse = sort_by.get("reverse", False) if sort_by else False
+ if sort_field == PluginSortField.IS_ACTIVE:
+ plugins = sorted(manager.plugins, key=lambda p: (p.active, p.PLUGIN_NAME))
+ else:
+ plugins = sorted(manager.plugins, key=lambda p: p.PLUGIN_NAME)
+ if sort_reverse:
+ plugins = reversed(plugins)
+ return [
+ {
+ "id": plugin.PLUGIN_NAME,
+ "active": plugin.active,
+ "configuration": plugin.configuration,
+ "description": plugin.PLUGIN_DESCRIPTION,
+ "name": plugin.PLUGIN_NAME,
+ }
+ for plugin in plugins
+ ]
diff --git a/saleor/payment/gateways/braintree/plugin.py b/saleor/payment/gateways/braintree/plugin.py
index 475be8c395..345eb6412b 100644
--- a/saleor/payment/gateways/braintree/plugin.py
+++ b/saleor/payment/gateways/braintree/plugin.py
@@ -25,7 +25,6 @@ if TYPE_CHECKING:
def require_active_plugin(fn):
def wrapped(self, *args, **kwargs):
previous = kwargs.get("previous_value", None)
- self._initialize_plugin_configuration()
if not self.active:
return previous
return fn(self, *args, **kwargs)
@@ -35,6 +34,16 @@ def require_active_plugin(fn):
class BraintreeGatewayPlugin(BasePlugin):
PLUGIN_NAME = GATEWAY_NAME
+ DEFAULT_CONFIGURATION = [
+ {"name": "Public API key", "value": None},
+ {"name": "Secret API key", "value": None},
+ {"name": "Use sandbox", "value": True},
+ {"name": "Merchant ID", "value": None},
+ {"name": "Store customers card", "value": False},
+ {"name": "Automatic payment capture", "value": True},
+ {"name": "Require 3D secure", "value": False},
+ ]
+
CONFIG_STRUCTURE = {
"Public API key": {
"type": ConfigurationTypeField.SECRET,
@@ -76,48 +85,20 @@ class BraintreeGatewayPlugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
+ configuration = {item["name"]: item["value"] for item in self.configuration}
self.config = GatewayConfig(
- gateway_name=GATEWAY_NAME, auto_capture=True, connection_params={}
+ gateway_name=GATEWAY_NAME,
+ auto_capture=configuration["Automatic payment capture"],
+ connection_params={
+ "sandbox_mode": configuration["Use sandbox"],
+ "merchant_id": configuration["Merchant ID"],
+ "public_key": configuration["Public API key"],
+ "private_key": configuration["Secret API key"],
+ },
+ store_customer=configuration["Store customers card"],
+ require_3d_secure=configuration["Require 3D secure"],
)
- def _initialize_plugin_configuration(self):
- super()._initialize_plugin_configuration()
-
- if self._cached_config and self._cached_config.configuration:
- configuration = self._cached_config.configuration
-
- configuration = {item["name"]: item["value"] for item in configuration}
- self.config = GatewayConfig(
- gateway_name=GATEWAY_NAME,
- auto_capture=configuration["Automatic payment capture"],
- connection_params={
- "sandbox_mode": configuration["Use sandbox"],
- "merchant_id": configuration["Merchant ID"],
- "public_key": configuration["Public API key"],
- "private_key": configuration["Secret API key"],
- },
- store_customer=configuration["Store customers card"],
- require_3d_secure=configuration["Require 3D secure"],
- )
-
- @classmethod
- def _get_default_configuration(cls):
- defaults = {
- "name": cls.PLUGIN_NAME,
- "description": "",
- "active": False,
- "configuration": [
- {"name": "Public API key", "value": None},
- {"name": "Secret API key", "value": None},
- {"name": "Use sandbox", "value": True},
- {"name": "Merchant ID", "value": None},
- {"name": "Store customers card", "value": False},
- {"name": "Automatic payment capture", "value": True},
- {"name": "Require 3D secure", "value": False},
- ],
- }
- return defaults
-
def _get_gateway_config(self) -> GatewayConfig:
return self.config
diff --git a/saleor/payment/gateways/dummy/plugin.py b/saleor/payment/gateways/dummy/plugin.py
index 72471bf156..1bdd49a706 100644
--- a/saleor/payment/gateways/dummy/plugin.py
+++ b/saleor/payment/gateways/dummy/plugin.py
@@ -23,7 +23,6 @@ if TYPE_CHECKING:
def require_active_plugin(fn):
def wrapped(self, *args, **kwargs):
previous = kwargs.get("previous_value", None)
- self._initialize_plugin_configuration()
if not self.active:
return previous
return fn(self, *args, **kwargs)
@@ -33,6 +32,11 @@ def require_active_plugin(fn):
class DummyGatewayPlugin(BasePlugin):
PLUGIN_NAME = GATEWAY_NAME
+ DEFAULT_ACTIVE = True
+ DEFAULT_CONFIGURATION = [
+ {"name": "Store customers card", "value": False},
+ {"name": "Automatic payment capture", "value": True},
+ ]
CONFIG_STRUCTURE = {
"Store customers card": {
"type": ConfigurationTypeField.BOOLEAN,
@@ -48,41 +52,14 @@ class DummyGatewayPlugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- self.active = True
+ configuration = {item["name"]: item["value"] for item in self.configuration}
self.config = GatewayConfig(
gateway_name=GATEWAY_NAME,
- auto_capture=True,
+ auto_capture=configuration["Automatic payment capture"],
connection_params={},
- store_customer=False,
+ store_customer=configuration["Store customers card"],
)
- def _initialize_plugin_configuration(self):
- super()._initialize_plugin_configuration()
-
- if self._cached_config and self._cached_config.configuration:
- configuration = self._cached_config.configuration
-
- configuration = {item["name"]: item["value"] for item in configuration}
- self.config = GatewayConfig(
- gateway_name=GATEWAY_NAME,
- auto_capture=configuration["Automatic payment capture"],
- connection_params={},
- store_customer=configuration["Store customers card"],
- )
-
- @classmethod
- def _get_default_configuration(cls):
- defaults = {
- "name": cls.PLUGIN_NAME,
- "description": "",
- "active": True,
- "configuration": [
- {"name": "Store customers card", "value": False},
- {"name": "Automatic payment capture", "value": True},
- ],
- }
- return defaults
-
def _get_gateway_config(self):
return self.config
diff --git a/saleor/payment/gateways/razorpay/plugin.py b/saleor/payment/gateways/razorpay/plugin.py
index b97dfc48c3..ad855f1eb2 100644
--- a/saleor/payment/gateways/razorpay/plugin.py
+++ b/saleor/payment/gateways/razorpay/plugin.py
@@ -14,7 +14,6 @@ if TYPE_CHECKING:
def require_active_plugin(fn):
def wrapped(self, *args, **kwargs):
previous = kwargs.get("previous_value", None)
- self._initialize_plugin_configuration()
if not self.active:
return previous
return fn(self, *args, **kwargs)
@@ -24,6 +23,13 @@ def require_active_plugin(fn):
class RazorpayGatewayPlugin(BasePlugin):
PLUGIN_NAME = GATEWAY_NAME
+ DEFAULT_CONFIGURATION = [
+ {"name": "Public API key", "value": None},
+ {"name": "Secret API key", "value": None},
+ {"name": "Store customers card", "value": False},
+ {"name": "Automatic payment capture", "value": True},
+ ]
+
CONFIG_STRUCTURE = {
"Public API key": {
"type": ConfigurationTypeField.SECRET,
@@ -50,42 +56,19 @@ class RazorpayGatewayPlugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- self.config = None
-
- def _initialize_plugin_configuration(self):
- super()._initialize_plugin_configuration()
-
- if self._cached_config and self._cached_config.configuration:
- configuration = self._cached_config.configuration
-
- configuration = {item["name"]: item["value"] for item in configuration}
- self.config = GatewayConfig(
- gateway_name=GATEWAY_NAME,
- auto_capture=configuration["Automatic payment capture"],
- connection_params={
- "public_key": configuration["Public API key"],
- "private_key": configuration["Secret API key"],
- "prefill": True,
- "store_name": None,
- "store_image": None,
- },
- store_customer=configuration["Store customers card"],
- )
-
- @classmethod
- def _get_default_configuration(cls):
- defaults = {
- "name": cls.PLUGIN_NAME,
- "description": "",
- "active": False,
- "configuration": [
- {"name": "Public API key", "value": None},
- {"name": "Secret API key", "value": None},
- {"name": "Store customers card", "value": False},
- {"name": "Automatic payment capture", "value": True},
- ],
- }
- return defaults
+ configuration = {item["name"]: item["value"] for item in self.configuration}
+ self.config = GatewayConfig(
+ gateway_name=GATEWAY_NAME,
+ auto_capture=configuration["Automatic payment capture"],
+ connection_params={
+ "public_key": configuration["Public API key"],
+ "private_key": configuration["Secret API key"],
+ "prefill": True,
+ "store_name": None,
+ "store_image": None,
+ },
+ store_customer=configuration["Store customers card"],
+ )
def _get_gateway_config(self):
return self.config
diff --git a/saleor/payment/gateways/stripe/plugin.py b/saleor/payment/gateways/stripe/plugin.py
index ad8fa4153d..1bde128bf9 100644
--- a/saleor/payment/gateways/stripe/plugin.py
+++ b/saleor/payment/gateways/stripe/plugin.py
@@ -24,7 +24,6 @@ if TYPE_CHECKING:
def require_active_plugin(fn):
def wrapped(self, *args, **kwargs):
previous = kwargs.get("previous_value", None)
- self._initialize_plugin_configuration()
if not self.active:
return previous
return fn(self, *args, **kwargs)
@@ -34,6 +33,13 @@ def require_active_plugin(fn):
class StripeGatewayPlugin(BasePlugin):
PLUGIN_NAME = GATEWAY_NAME
+ DEFAULT_CONFIGURATION = [
+ {"name": "Public API key", "value": None},
+ {"name": "Secret API key", "value": None},
+ {"name": "Store customers card", "value": False},
+ {"name": "Automatic payment capture", "value": True},
+ ]
+
CONFIG_STRUCTURE = {
"Public API key": {
"type": ConfigurationTypeField.SECRET,
@@ -60,39 +66,16 @@ class StripeGatewayPlugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- self.config = None
-
- def _initialize_plugin_configuration(self):
- super()._initialize_plugin_configuration()
-
- if self._cached_config and self._cached_config.configuration:
- configuration = self._cached_config.configuration
-
- configuration = {item["name"]: item["value"] for item in configuration}
- self.config = GatewayConfig(
- gateway_name=GATEWAY_NAME,
- auto_capture=configuration["Automatic payment capture"],
- connection_params={
- "public_key": configuration["Public API key"],
- "private_key": configuration["Secret API key"],
- },
- store_customer=configuration["Store customers card"],
- )
-
- @classmethod
- def _get_default_configuration(cls):
- defaults = {
- "name": cls.PLUGIN_NAME,
- "description": "",
- "active": False,
- "configuration": [
- {"name": "Public API key", "value": None},
- {"name": "Secret API key", "value": None},
- {"name": "Store customers card", "value": False},
- {"name": "Automatic payment capture", "value": True},
- ],
- }
- return defaults
+ configuration = {item["name"]: item["value"] for item in self.configuration}
+ self.config = GatewayConfig(
+ gateway_name=GATEWAY_NAME,
+ auto_capture=configuration["Automatic payment capture"],
+ connection_params={
+ "public_key": configuration["Public API key"],
+ "private_key": configuration["Secret API key"],
+ },
+ store_customer=configuration["Store customers card"],
+ )
def _get_gateway_config(self):
return self.config
diff --git a/tests/extensions/conftest.py b/tests/extensions/conftest.py
index 0f210a03a8..f77349ce4c 100644
--- a/tests/extensions/conftest.py
+++ b/tests/extensions/conftest.py
@@ -8,18 +8,26 @@ from tests.extensions.sample_plugins import PluginInactive, PluginSample
@pytest.fixture
def plugin_configuration(db):
- plugin = PluginSample()
configuration, _ = PluginConfiguration.objects.get_or_create(
- name=PluginSample.PLUGIN_NAME, defaults=plugin._get_default_configuration()
+ name=PluginSample.PLUGIN_NAME,
+ defaults={
+ "active": PluginSample.DEFAULT_ACTIVE,
+ "configuration": PluginSample.DEFAULT_CONFIGURATION,
+ "name": PluginSample.PLUGIN_NAME,
+ },
)
return configuration
@pytest.fixture
def inactive_plugin_configuration(db):
- plugin = PluginInactive()
return PluginConfiguration.objects.get_or_create(
- name=PluginInactive.PLUGIN_NAME, defaults=plugin._get_default_configuration()
+ name=PluginInactive.PLUGIN_NAME,
+ defaults={
+ "active": PluginInactive.DEFAULT_ACTIVE,
+ "configuration": PluginInactive.DEFAULT_CONFIGURATION,
+ "name": PluginInactive.PLUGIN_NAME,
+ },
)[0]
diff --git a/tests/extensions/plugins/test_avatax.py b/tests/extensions/plugins/test_avatax.py
index 6190dff344..4d90ecb814 100644
--- a/tests/extensions/plugins/test_avatax.py
+++ b/tests/extensions/plugins/test_avatax.py
@@ -19,7 +19,11 @@ from saleor.extensions.plugins.avatax.plugin import AvataxPlugin
@pytest.fixture
def plugin_configuration(db):
- default_configuration = AvataxPlugin._get_default_configuration()
+ default_configuration = {
+ "active": AvataxPlugin.DEFAULT_ACTIVE,
+ "configuration": dict(AvataxPlugin.DEFAULT_CONFIGURATION),
+ "name": AvataxPlugin.PLUGIN_NAME,
+ }
for elem in default_configuration["configuration"]:
if elem["name"] == "Use sandbox":
elem["value"] = False
diff --git a/tests/extensions/plugins/test_plugins.py b/tests/extensions/plugins/test_plugins.py
index c103bb5efb..26f1fba60f 100644
--- a/tests/extensions/plugins/test_plugins.py
+++ b/tests/extensions/plugins/test_plugins.py
@@ -26,45 +26,32 @@ def test_update_config_items_convert_to_bool_value():
{"name": "Username", "value": "[email protected]"},
{"name": "Use sandbox", "value": "false"},
]
- plugin_sample = PluginSample()
- plugin_sample._initialize_plugin_configuration()
+ plugin_sample = PluginSample(
+ configuration=PluginSample.DEFAULT_CONFIGURATION,
+ active=PluginSample.DEFAULT_ACTIVE,
+ )
qs = PluginConfiguration.objects.all()
- configuration = PluginSample.get_plugin_configuration(qs)
- plugin_sample._update_config_items(data_to_update, configuration.configuration)
- configuration.save()
- configuration.refresh_from_db()
- assert get_config_value("Use sandbox", configuration.configuration) is False
-
-
-def test_base_plugin__update_configuration_structure_configuration_has_not_change(
- plugin_configuration,
-):
- plugin = PluginSample()
- old_configuration = plugin_configuration.configuration.copy()
- plugin._update_configuration_structure(plugin_configuration)
- plugin_configuration.refresh_from_db()
- assert old_configuration == plugin_configuration.configuration
+ configuration = plugin_sample.configuration
+ assert get_config_value("Use sandbox", configuration) is False
def test_base_plugin__update_configuration_structure_configuration_has_change(
monkeypatch, plugin_configuration
):
old_configuration = plugin_configuration.configuration.copy()
- plugin = PluginSample()
- config_structure = plugin.CONFIG_STRUCTURE
+ config_structure = PluginSample.CONFIG_STRUCTURE
config_structure["Private key"] = {
"help_text": "Test",
"label": "Test",
"type": ConfigurationTypeField.STRING,
}
- default_configuration = plugin._get_default_configuration()
private_key_dict = {"name": "Private key", "value": "123457"}
- default_configuration["configuration"].append(private_key_dict)
monkeypatch.setattr(
- "tests.extensions.plugins.test_plugins.PluginSample._get_default_configuration",
- lambda: default_configuration,
+ PluginSample,
+ "DEFAULT_CONFIGURATION",
+ PluginSample.DEFAULT_CONFIGURATION + private_key_dict,
)
- plugin._update_configuration_structure(plugin_configuration)
+ PluginSample._update_configuration_structure(plugin_configuration)
plugin_configuration.refresh_from_db()
assert len(old_configuration) + 1 == len(plugin_configuration.configuration)
old_configuration.append(private_key_dict)
diff --git a/tests/extensions/sample_plugins.py b/tests/extensions/sample_plugins.py
index 39df3b32b6..34e68ebc24 100644
--- a/tests/extensions/sample_plugins.py
+++ b/tests/extensions/sample_plugins.py
@@ -18,6 +18,15 @@ if TYPE_CHECKING:
class PluginSample(BasePlugin):
PLUGIN_NAME = "PluginSample"
+ PLUGIN_DESCRIPTION = "Test plugin description"
+ DEFAULT_ACTIVE = True
+ DEFAULT_CONFIGURATION = [
+ {"name": "Username", "value": "admin"},
+ {"name": "Password", "value": None},
+ {"name": "Use sandbox", "value": False},
+ {"name": "API private key", "value": None},
+ ]
+
CONFIG_STRUCTURE = {
"Username": {
"type": ConfigurationTypeField.STRING,
@@ -41,20 +50,6 @@ class PluginSample(BasePlugin):
},
}
- @classmethod
- def _get_default_configuration(cls):
- return {
- "name": "PluginSample",
- "description": "Test plugin description",
- "active": True,
- "configuration": [
- {"name": "Username", "value": "admin"},
- {"name": "Password", "value": None},
- {"name": "Use sandbox", "value": False},
- {"name": "API private key", "value": None},
- ],
- }
-
def calculate_checkout_total(self, checkout, discounts, previous_value):
total = Money("1.0", currency=checkout.currency)
return TaxedMoney(total, total)
@@ -104,51 +99,19 @@ class PluginSample(BasePlugin):
class PluginInactive(BasePlugin):
PLUGIN_NAME = "PluginInactive"
-
- @classmethod
- def _get_default_configuration(cls):
- return {
- "name": "PluginInactive",
- "description": "Test plugin description_2",
- "active": False,
- "configuration": None,
- }
+ PLUGIN_DESCRIPTION = "Test plugin description_2"
class ActivePlugin(BasePlugin):
- PLUGIN_NAME = "Plugin1"
-
- @classmethod
- def get_plugin_configuration(
- cls, queryset: "QuerySet" = None
- ) -> "PluginConfiguration":
- if queryset:
- configuration = queryset.filter(name="Active").first()
- if configuration:
- return configuration
-
- defaults = {
- "name": "Active",
- "description": "Not working",
- "active": True,
- "configuration": [],
- }
- return PluginConfiguration.objects.create(**defaults)
+ PLUGIN_NAME = "Active"
+ PLUGIN_DESCRIPTION = "Not working"
+ DEFAULT_ACTIVE = True
class ActivePaymentGateway(BasePlugin):
CLIENT_CONFIG = [{"field": "foo", "value": "bar"}]
PLUGIN_NAME = "braintree"
-
- @classmethod
- def _get_default_configuration(cls):
- defaults = {
- "name": "braintree",
- "description": "",
- "active": True,
- "configuration": None,
- }
- return defaults
+ DEFAULT_ACTIVE = True
def process_payment(self, payment_information, previous_value):
pass
@@ -160,15 +123,5 @@ class ActivePaymentGateway(BasePlugin):
class InactivePaymentGateway(BasePlugin):
PLUGIN_NAME = "stripe"
- @classmethod
- def _get_default_configuration(cls):
- defaults = {
- "name": "stripe",
- "description": "",
- "active": False,
- "configuration": None,
- }
- return defaults
-
def process_payment(self, payment_information, previous_value):
pass
diff --git a/tests/extensions/test_manager.py b/tests/extensions/test_manager.py
index ad04f94826..6986535cb8 100644
--- a/tests/extensions/test_manager.py
+++ b/tests/extensions/test_manager.py
@@ -219,21 +219,15 @@ def test_plugin_updates_configuration_shape(
plugin_configuration,
monkeypatch,
):
- def new_default_configuration():
- defaults = {
- "name": "PluginSample",
- "description": "",
- "active": True,
- "configuration": plugin_configuration.configuration + [new_config],
- }
- return defaults
config_structure = PluginSample.CONFIG_STRUCTURE.copy()
config_structure["Foo"] = new_config_structure
monkeypatch.setattr(PluginSample, "CONFIG_STRUCTURE", config_structure)
monkeypatch.setattr(
- PluginSample, "_get_default_configuration", new_default_configuration
+ PluginSample,
+ "DEFAULT_CONFIGURATION",
+ plugin_configuration.configuration + [new_config],
)
configuration = manager_with_plugin_enabled.get_plugin_configuration(
@@ -251,17 +245,9 @@ def test_plugin_add_new_configuration(
inactive_plugin_configuration,
monkeypatch,
):
- def new_default_configuration():
- defaults = {
- "name": "PluginInactive",
- "description": "",
- "active": True,
- "configuration": [new_config],
- }
- return defaults
-
+ monkeypatch.setattr(PluginInactive, "DEFAULT_ACTIVE", True)
monkeypatch.setattr(
- PluginInactive, "_get_default_configuration", new_default_configuration
+ PluginInactive, "DEFAULT_CONFIGURATION", [new_config],
)
config_structure = {"Foo": new_config_structure}
monkeypatch.setattr(PluginInactive, "CONFIG_STRUCTURE", config_structure)