Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add using of dynamic settings to avatax
Maciej Korycinski5aabe854cddd
diff --git a/saleor/extensions/plugins/avatax/__init__.py b/saleor/extensions/plugins/avatax/__init__.pyindex 12a6d5c55d..e2551d0372 100644--- a/saleor/extensions/plugins/avatax/__init__.py+++ b/saleor/extensions/plugins/avatax/__init__.py@@ -1,5 +1,6 @@import jsonimport logging+from dataclasses import dataclassfrom datetime import datefrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Unionfrom urllib.parse import urljoin@@ -32,6 +33,15 @@ COMMON_CARRIER_CODE = "FR020100"COMMON_DISCOUNT_VOUCHER_CODE = "OD010000"+@dataclass+class AvataxConfiguration:+ username_or_account: str+ password_or_license: str+ use_sandbox: bool = True+ company_name: str = "DEFAULT"+ autocommit: bool = False++class TransactionType:INVOICE = "SalesInvoice"ORDER = "SalesOrder"@@ -51,21 +61,18 @@ class CustomerErrors:return cls.DEFAULT_MSG-def get_api_url() -> str:+def get_api_url(use_sandbox=True) -> str:"""Based on settings return sanbox or production url."""- if settings.AVATAX_USE_SANDBOX:+ if use_sandbox:return "https://sandbox-rest.avatax.com/api/v2/"return "https://rest.avatax.com/api/v2/"def api_post_request(- url: str,- data: Dict[str, Any],- username: str = settings.AVATAX_USERNAME_OR_ACCOUNT,- password: str = settings.AVATAX_PASSWORD_OR_LICENSE,+ url: str, data: Dict[str, Any], config: AvataxConfiguration) -> Dict[str, Any]:try:- auth = HTTPBasicAuth(username, password)+ auth = HTTPBasicAuth(config.username_or_account, config.password_or_license)response = requests.post(url, auth=auth, data=json.dumps(data), timeout=TIMEOUT)logger.debug("Hit to Avatax to calculate taxes %s", url)except requests.exceptions.RequestException:@@ -74,13 +81,9 @@ def api_post_request(return response.json()-def api_get_request(- url: str,- username: str = settings.AVATAX_USERNAME_OR_ACCOUNT,- password: str = settings.AVATAX_PASSWORD_OR_LICENSE,-):+def api_get_request(url: str, config: AvataxConfiguration):try:- auth = HTTPBasicAuth(username, password)+ auth = HTTPBasicAuth(config.username_or_account, config.password_or_license)response = requests.get(url, auth=auth, timeout=TIMEOUT)logger.debug("[GET] Hit to %s", url)except requests.exceptions.RequestException:@@ -277,7 +280,7 @@ def generate_request_data(address: Dict[str, str],customer_code: Optional[int],customer_email: str,- commit=False,+ config: AvataxConfiguration,currency=settings.DEFAULT_CURRENCY,):company_address = Site.objects.get_current().settings.company_address@@ -291,7 +294,7 @@ def generate_request_data(company_address = {}data = {- "companyCode": settings.AVATAX_COMPANY_NAME,+ "companyCode": config.company_name,"type": transaction_type,"lines": lines,"code": transaction_token,@@ -315,7 +318,7 @@ def generate_request_data("postalCode": address.get("postal_code"),},},- "commit": commit,+ "commit": config.autocommit,"currencyCode": currency,"email": customer_email,}@@ -324,9 +327,9 @@ def generate_request_data(def generate_request_data_from_checkout(checkout: "Checkout",+ config: AvataxConfiguration,transaction_token=None,transaction_type=TransactionType.ORDER,- commit=False,discounts=None,):@@ -342,15 +345,19 @@ def generate_request_data_from_checkout(address=address.as_data(),customer_code=checkout.user.id if checkout.user else 0,customer_email=checkout.email,- commit=commit,+ config=config,currency=currency,)return data-def _fetch_new_taxes_data(data: List[Dict], data_cache_key: str):- transaction_url = urljoin(get_api_url(), "transactions/createoradjust")- response = api_post_request(transaction_url, data)+def _fetch_new_taxes_data(+ data: Dict[str, Dict], data_cache_key: str, config: AvataxConfiguration+):+ transaction_url = urljoin(+ get_api_url(config.use_sandbox), "transactions/createoradjust"+ )+ response = api_post_request(transaction_url, data, config)if response and "error" not in response:cache.set(data_cache_key, (data, response), CACHE_TIME)else:@@ -359,27 +366,34 @@ def _fetch_new_taxes_data(data: List[Dict], data_cache_key: str):return response-def get_cached_response_or_fetch(data, token_in_cache, force_refresh=False):+def get_cached_response_or_fetch(+ data: Dict[str, Dict],+ token_in_cache: str,+ config: AvataxConfiguration,+ force_refresh: bool = False,+):"""Try to find response in cache.Return cached response if requests data are the same. Fetch new data in other cases."""data_cache_key = CACHE_KEY + token_in_cacheif taxes_need_new_fetch(data, token_in_cache) or force_refresh:- response = _fetch_new_taxes_data(data, data_cache_key)+ response = _fetch_new_taxes_data(data, data_cache_key, config)else:_, response = cache.get(data_cache_key)return response-def get_checkout_tax_data(checkout: "Checkout", discounts) -> Dict[str, Any]:- data = generate_request_data_from_checkout(checkout, discounts=discounts)- return get_cached_response_or_fetch(data, str(checkout.token))+def get_checkout_tax_data(+ checkout: "Checkout", discounts, config: AvataxConfiguration+) -> Dict[str, Any]:+ data = generate_request_data_from_checkout(checkout, config, discounts=discounts)+ return get_cached_response_or_fetch(data, str(checkout.token), config)def get_order_tax_data(- order: "Order", commit=False, force_refresh=False+ order: "Order", config: AvataxConfiguration, force_refresh=False) -> Dict[str, Any]:address = order.shipping_address or order.billing_addresslines = get_order_lines_data(order)@@ -393,11 +407,11 @@ def get_order_tax_data(address=address.as_data(),customer_code=order.user.id if order.user else None,customer_email=order.user_email,- commit=commit,+ config=config,currency=order.total.currency,)response = get_cached_response_or_fetch(- data, "order_%s" % order.token, force_refresh+ data, "order_%s" % order.token, config, force_refresh)return response@@ -412,15 +426,17 @@ def generate_tax_codes_dict(return tax_codes-def get_cached_tax_codes_or_fetch(cache_time: int = TAX_CODES_CACHE_TIME):+def get_cached_tax_codes_or_fetch(+ config: AvataxConfiguration, cache_time: int = TAX_CODES_CACHE_TIME+):"""Try to get cached tax codes.If the cache is empty, fetch the newest taxcodes from avatax."""tax_codes = cache.get(TAX_CODES_CACHE_KEY, {})if not tax_codes:- tax_codes_url = urljoin(get_api_url(), "definitions/taxcodes")- response = api_get_request(tax_codes_url)+ tax_codes_url = urljoin(get_api_url(config.use_sandbox), "definitions/taxcodes")+ response = api_get_request(tax_codes_url, config)if response and "error" not in response:tax_codes = generate_tax_codes_dict(response)cache.set(TAX_CODES_CACHE_KEY, tax_codes, cache_time)diff --git a/saleor/extensions/plugins/avatax/plugin.py b/saleor/extensions/plugins/avatax/plugin.pyindex d361b9625d..8b5a9308c6 100644--- a/saleor/extensions/plugins/avatax/plugin.py+++ b/saleor/extensions/plugins/avatax/plugin.py@@ -9,9 +9,11 @@ from prices import Money, TaxedMoney, TaxedMoneyRangefrom ....core.taxes import TaxError, TaxType, zero_taxed_moneyfrom ... import ConfigurationTypeFieldfrom ...base_plugin import BasePlugin+from ...models import PluginConfigurationfrom . import (META_FIELD,META_NAMESPACE,+ AvataxConfiguration,CustomerErrors,TransactionType,_validate_checkout,@@ -37,12 +39,48 @@ class AvataxPlugin(BasePlugin):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)- self._enabled = (- settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE- )+ self._cached_config_from_db = None+ self.config = None+ self.active = None++ def _initialize_plugin_configuration(self):+ plugin_config_qs = PluginConfiguration.objects.filter(name=self.PLUGIN_NAME)+ plugin_config = self._cached_config_from_db or plugin_config_qs.first()++ if plugin_config and plugin_config.configuration:+ configuration = plugin_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"] == "true",+ company_name=configuration["Company name"],+ autocommit=configuration["Autocommit"] == "true",+ )+ self.active = plugin_config.active++ if not self._cached_config_from_db:+ self._cached_config_from_db = plugin_config++ 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,+ )+ self.active = (+ settings.AVATAX_USERNAME_OR_ACCOUNT+ and settings.AVATAX_PASSWORD_OR_LICENSE+ )def _skip_plugin(self, previous_value: Union[TaxedMoney, TaxedMoneyRange]) -> bool:- if not self._enabled:+ if not (self.config.username_or_account and self.config.password_or_license):+ return True++ if not self.active:return True# The previous plugin already calculated taxes so we can skip our logic@@ -62,13 +100,15 @@ class AvataxPlugin(BasePlugin):discounts: List["DiscountInfo"],previous_value: TaxedMoney,) -> TaxedMoney:+ self._initialize_plugin_configuration()+if self._skip_plugin(previous_value):return previous_valuecheckout_total = checkout.get_total(discounts=discounts)if not _validate_checkout(checkout):return TaxedMoney(net=checkout_total, gross=checkout_total)- response = get_checkout_tax_data(checkout, discounts)+ response = get_checkout_tax_data(checkout, discounts, self.config)if not response or "error" in response:return TaxedMoney(net=checkout_total, gross=checkout_total)@@ -103,6 +143,7 @@ class AvataxPlugin(BasePlugin):discounts: List["DiscountInfo"],previous_value: TaxedMoney,) -> TaxedMoney:+ self._initialize_plugin_configuration()if self._skip_plugin(previous_value):return previous_value@@ -111,7 +152,7 @@ class AvataxPlugin(BasePlugin):if not _validate_checkout(checkout):return TaxedMoney(net=sub_total, gross=sub_total)- response = get_checkout_tax_data(checkout, discounts)+ response = get_checkout_tax_data(checkout, discounts, self.config)if not response or "error" in response:return TaxedMoney(net=sub_total, gross=sub_total)@@ -139,6 +180,8 @@ class AvataxPlugin(BasePlugin):discounts: List["DiscountInfo"],previous_value: TaxedMoney,) -> TaxedMoney:+ self._initialize_plugin_configuration()+if self._skip_plugin(previous_value):return previous_value@@ -146,7 +189,7 @@ class AvataxPlugin(BasePlugin):if not _validate_checkout(checkout):return TaxedMoney(net=shipping_price, gross=shipping_price)- response = get_checkout_tax_data(checkout, discounts)+ response = get_checkout_tax_data(checkout, discounts, self.config)if not response or "error" in response:return TaxedMoney(net=shipping_price, gross=shipping_price)@@ -162,16 +205,22 @@ class AvataxPlugin(BasePlugin):Raise an error when can't receive taxes."""- if not self._enabled:- return+ self._initialize_plugin_configuration()++ if not self.active:+ return previous_value+data = generate_request_data_from_checkout(checkout,+ self.config,transaction_token=str(checkout.token),transaction_type=TransactionType.ORDER,discounts=discounts,)- transaction_url = urljoin(get_api_url(), "transactions/createoradjust")- response = api_post_request(transaction_url, data)+ transaction_url = urljoin(+ get_api_url(self.config.use_sandbox), "transactions/createoradjust"+ )+ response = api_post_request(transaction_url, data, self.config)if not response or "error" in response:msg = response.get("error", {}).get("message", "")error_code = response.get("error", {}).get("code", "")@@ -184,16 +233,20 @@ class AvataxPlugin(BasePlugin):)customer_msg = CustomerErrors.get_error_msg(response.get("error", {}))raise TaxError(customer_msg)+ return previous_value- def postprocess_order_creation(self, order: "Order", previous_value: Any):- if not self._enabled:- return- data = get_order_tax_data(- order, commit=settings.AVATAX_AUTOCOMMIT, force_refresh=True- )+ def postprocess_order_creation(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)- transaction_url = urljoin(get_api_url(), "transactions/createoradjust")+ transaction_url = urljoin(+ get_api_url(self.config.use_sandbox), "transactions/createoradjust"+ )api_post_request_task.delay(transaction_url, data)+ return previous_valuedef calculate_checkout_line_total(self,@@ -201,6 +254,8 @@ class AvataxPlugin(BasePlugin):discounts: List["DiscountInfo"],previous_value: TaxedMoney,) -> TaxedMoney:+ self._initialize_plugin_configuration()+if self._skip_plugin(previous_value):return previous_value@@ -208,7 +263,7 @@ class AvataxPlugin(BasePlugin):total = checkout_line.get_total(discounts)if not _validate_checkout(checkout):return TaxedMoney(net=total, gross=total)- taxes_data = get_checkout_tax_data(checkout, discounts)+ taxes_data = get_checkout_tax_data(checkout, discounts, self.config)currency = taxes_data.get("currencyCode")for line in taxes_data.get("lines", []):if line.get("itemCode") == checkout_line.variant.sku:@@ -223,7 +278,7 @@ class AvataxPlugin(BasePlugin):def _calculate_order_line_unit(self, order_line):order = order_line.order- taxes_data = get_order_tax_data(order)+ taxes_data = get_order_tax_data(order, self.config)currency = taxes_data.get("currencyCode")for line in taxes_data.get("lines", []):if line.get("itemCode") == order_line.variant.sku:@@ -237,6 +292,8 @@ 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@@ -247,12 +304,14 @@ 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_valueif not _validate_order(order):return zero_taxed_money(order.total.currency)- taxes_data = get_order_tax_data(order, False)+ taxes_data = get_order_tax_data(order, self.config, False)currency = taxes_data.get("currencyCode")for line in taxes_data.get("lines", []):if line["itemCode"] == "Shipping":@@ -266,20 +325,24 @@ class AvataxPlugin(BasePlugin):)def get_tax_rate_type_choices(self, previous_value: Any) -> List[TaxType]:- if not self._enabled:+ self._initialize_plugin_configuration()++ if not self.active:return previous_valuereturn [TaxType(code=tax_code, description=desc)- for tax_code, desc in get_cached_tax_codes_or_fetch().items()+ for tax_code, desc in get_cached_tax_codes_or_fetch(self.config).items()]def assign_tax_code_to_object_meta(self, obj: Union["Product", "ProductType"], tax_code: str, previous_value: Any):- if not self._enabled:+ self._initialize_plugin_configuration()++ if not self.active:return previous_value- codes = get_cached_tax_codes_or_fetch()+ codes = get_cached_tax_codes_or_fetch(self.config)if tax_code not in codes:return@@ -295,18 +358,24 @@ class AvataxPlugin(BasePlugin):def get_tax_code_from_object_meta(self, obj: Union["Product", "ProductType"], previous_value: Any) -> TaxType:- if not self._enabled:+ self._initialize_plugin_configuration()++ if not self.active:return previous_valuetax = obj.get_meta(namespace=META_NAMESPACE, client=META_FIELD)return TaxType(code=tax.get("code", ""), description=tax.get("description", ""))def show_taxes_on_storefront(self, previous_value: bool) -> bool:- if not self._enabled:+ self._initialize_plugin_configuration()++ if not self.active:return previous_valuereturn Falsedef taxes_are_enabled(self, previous_value: bool) -> bool:- if not self._enabled:+ self._initialize_plugin_configuration()++ if not self.active:return previous_valuereturn True@@ -340,7 +409,7 @@ class AvataxPlugin(BasePlugin):},{"name": "Company name",- "value": "",+ "value": "DEFAULT","type": ConfigurationTypeField.STRING,"help_text": "","label": "",diff --git a/tests/extensions/plugins/test_avatax.py b/tests/extensions/plugins/test_avatax.pyindex 51ba8a1849..41a70ee488 100644--- a/tests/extensions/plugins/test_avatax.py+++ b/tests/extensions/plugins/test_avatax.py@@ -5,6 +5,7 @@ from saleor.checkout.utils import add_variant_to_checkoutfrom saleor.core.taxes import TaxError, quantize_pricefrom saleor.extensions.manager import get_extensions_managerfrom saleor.extensions.plugins.avatax import (+ AvataxConfiguration,checkout_needs_new_fetch,generate_request_data_from_checkout,get_cached_tax_codes_or_fetch,@@ -40,7 +41,7 @@ def test_calculate_checkout_line_total(settings.PLUGINS = ["saleor.extensions.plugins.avatax.plugin.AvataxPlugin"]monkeypatch.setattr("saleor.extensions.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",- lambda: {"PC040156": "desc"},+ lambda _: {"PC040156": "desc"},)manager = get_extensions_manager(plugins=settings.PLUGINS)@@ -92,7 +93,7 @@ def test_calculate_checkout_total(settings.PLUGINS = ["saleor.extensions.plugins.avatax.plugin.AvataxPlugin"]monkeypatch.setattr("saleor.extensions.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",- lambda: {"PC040156": "desc"},+ lambda _: {"PC040156": "desc"},)manager = get_extensions_manager(plugins=settings.PLUGINS)checkout_with_item.shipping_address = address@@ -133,7 +134,7 @@ def test_calculate_checkout_shipping(settings.PLUGINS = ["saleor.extensions.plugins.avatax.plugin.AvataxPlugin"]monkeypatch.setattr("saleor.extensions.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",- lambda: {"PC040156": "desc"},+ lambda _: {"PC040156": "desc"},)manager = get_extensions_manager(plugins=settings.PLUGINS)site_settings.company_address = address_usa@@ -181,7 +182,7 @@ def test_calculate_checkout_subtotal(settings.PLUGINS = ["saleor.extensions.plugins.avatax.plugin.AvataxPlugin"]monkeypatch.setattr("saleor.extensions.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",- lambda: {"PC040156": "desc"},+ lambda _: {"PC040156": "desc"},)manager = get_extensions_manager(plugins=settings.PLUGINS)site_settings.company_address = address_usa@@ -272,7 +273,7 @@ def test_preprocess_order_creation(settings.PLUGINS = ["saleor.extensions.plugins.avatax.plugin.AvataxPlugin"]monkeypatch.setattr("saleor.extensions.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",- lambda: {"PC040156": "desc"},+ lambda _: {"PC040156": "desc"},)manager = get_extensions_manager(plugins=settings.PLUGINS)site_settings.company_address = address_usa@@ -301,7 +302,7 @@ def test_preprocess_order_creation_wrong_data(settings.PLUGINS = ["saleor.extensions.plugins.avatax.plugin.AvataxPlugin"]monkeypatch.setattr("saleor.extensions.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",- lambda: {"PC040156": "desc"},+ lambda _: {"PC040156": "desc"},)manager = get_extensions_manager(plugins=settings.PLUGINS)@@ -316,25 +317,28 @@ def test_preprocess_order_creation_wrong_data(@pytest.mark.vcrdef test_get_cached_tax_codes_or_fetch(monkeypatch, settings):monkeypatch.setattr("saleor.extensions.plugins.avatax.cache.get", lambda x, y: {})- settings.AVATAX_USERNAME_OR_ACCOUNT = "test"- settings.AVATAX_PASSWORD_OR_LICENSE = "test"- tax_codes = get_cached_tax_codes_or_fetch()+ config = AvataxConfiguration(username_or_account="test", password_or_license="test")+ tax_codes = get_cached_tax_codes_or_fetch(config)assert len(tax_codes) > 0@pytest.mark.vcr-def test_get_cached_tax_codes_or_fetch_wrong_response(monkeypatch, settings):+def test_get_cached_tax_codes_or_fetch_wrong_response(monkeypatch):monkeypatch.setattr("saleor.extensions.plugins.avatax.cache.get", lambda x, y: {})- settings.AVATAX_USERNAME_OR_ACCOUNT = "wrong_data"- settings.AVATAX_PASSWORD_OR_LICENSE = "wrong_data"- tax_codes = get_cached_tax_codes_or_fetch()+ config = AvataxConfiguration(+ username_or_account="wrong_data", password_or_license="wrong_data"+ )+ tax_codes = get_cached_tax_codes_or_fetch(config)assert len(tax_codes) == 0def test_checkout_needs_new_fetch(monkeypatch, checkout_with_item, address):monkeypatch.setattr("saleor.extensions.plugins.avatax.cache.get", lambda x: None)checkout_with_item.shipping_address = address- checkout_data = generate_request_data_from_checkout(checkout_with_item)+ config = AvataxConfiguration(+ username_or_account="wrong_data", password_or_license="wrong_data"+ )+ checkout_data = generate_request_data_from_checkout(checkout_with_item, config)assert checkout_needs_new_fetch(checkout_data, str(checkout_with_item.token))