Skip to content

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

Drop support for settings.Vatlayer api_key. Remove old variables. Add fetch_taxes_data to manager

Maciej Korycinskia10f10a62ed4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 001e4c0afd..0d552c2206 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -104,6 +104,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Add home page - #5494 by @IKarbowiak and @dominik-zeglen
- Extend errors in OrderFulfill mutation - #5553 by @fowczarek
- Refactor OrderCancel mutation for many warehouses - #5554 by @fowczarek
+- Drop support for configuring Vatlayer plaugin from settings file. - by @korycins
## 2.9.0
diff --git a/poetry.lock b/poetry.lock
index 0194b040db..c9e6891fef 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -597,7 +597,7 @@ description = "vatlayer.com support for django"
name = "django-prices-vatlayer"
optional = false
python-versions = "*"
-version = "1.0.2"
+version = "1.1.0"
[package.dependencies]
Django = ">=1.11"
@@ -2172,7 +2172,7 @@ idna = ">=2.0"
multidict = ">=4.0"
[metadata]
-content-hash = "339e653c0fb997bd6e28f9fb5f1b1c5ff243178c7691a363e442d96be0fbf82d"
+content-hash = "f26df05351142985390bc570358bce1cadd0f2b36967b2492098797650730be6"
python-versions = "~3.8"
[metadata.files]
@@ -2422,7 +2422,8 @@ django-prices-openexchangerates = [
{file = "django_prices_openexchangerates-1.1.0-py3-none-any.whl", hash = "sha256:e8a8e85020ab62071bec29bf48eb7e688822141291e9d855b045efe1ab27ea74"},
]
django-prices-vatlayer = [
- {file = "django-prices-vatlayer-1.0.2.tar.gz", hash = "sha256:cd0e45a8e71b680c5fa8d7b2022535d7ccfd2bf71b10b18aa7f78b3aa0d596af"},
+ {file = "django-prices-vatlayer-1.1.0.tar.gz", hash = "sha256:54cb240dfd2b7c5fd22498aaf6e9141e602eccb2b0672911c64dc5add3fa666e"},
+ {file = "django_prices_vatlayer-1.1.0-py3-none-any.whl", hash = "sha256:de47234d46ae35d83dd35adbd83e3d26a9c90a8d184020590109bdef39474ed0"},
]
django-render-block = [
{file = "django_render_block-0.6-py2.py3-none-any.whl", hash = "sha256:95c7dc9610378a10e0c4a10d8364ec7307210889afccd6a67a6aaa0fd599bd4d"},
diff --git a/pyproject.toml b/pyproject.toml
index 3a07e5cbf9..513d55bda8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -28,7 +28,7 @@ django-mptt = "^0"
django-phonenumber-field = "^2.4"
django-prices = "^2.1"
django-prices-openexchangerates = "^1.0.1"
-django-prices-vatlayer = "^1.0.2"
+django-prices-vatlayer = "^1.1.0"
django-storages = { version = "^1.7.1", extras = [ "google" ] }
django-templated-email = "^2.3.0"
django-versatileimagefield = "^2.0"
diff --git a/requirements.txt b/requirements.txt
index 57b6f6c05a..0ed50cfece 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -29,7 +29,7 @@ django-mptt==0.11.0
django-phonenumber-field==2.4.0
django-prices==2.2.0
django-prices-openexchangerates==1.1.0
-django-prices-vatlayer==1.0.2
+django-prices-vatlayer==1.1.0
django-render-block==0.6
django-storages==1.9.1
django-templated-email==2.3.0
diff --git a/requirements_dev.txt b/requirements_dev.txt
index 851975d79d..c72609be81 100644
--- a/requirements_dev.txt
+++ b/requirements_dev.txt
@@ -46,7 +46,7 @@ django-mptt==0.11.0
django-phonenumber-field==2.4.0
django-prices==2.2.0
django-prices-openexchangerates==1.1.0
-django-prices-vatlayer==1.0.2
+django-prices-vatlayer==1.1.0
django-render-block==0.6
django-storages==1.9.1
django-stubs==1.2.0
diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.py
index 48821e144a..3d0d22e7e1 100644
--- a/saleor/graphql/shop/mutations.py
+++ b/saleor/graphql/shop/mutations.py
@@ -1,7 +1,5 @@
import graphene
-from django.conf import settings
from django.core.exceptions import ValidationError
-from django.core.management import call_command
from ...account import models as account_models
from ...core.error_codes import ShopErrorCode
@@ -170,14 +168,14 @@ class ShopFetchTaxRates(BaseMutation):
error_type_field = "shop_errors"
@classmethod
- def perform_mutation(cls, _root, _info):
- if not settings.VATLAYER_ACCESS_KEY:
+ def perform_mutation(cls, _root, info):
+
+ if not info.context.plugins.fetch_taxes_data():
raise ValidationError(
"Could not fetch tax rates. Make sure you have supplied a "
- "valid API Access Key.",
+ "valid credential for your tax plugin.",
code=ShopErrorCode.CANNOT_FETCH_TAX_RATES,
)
- call_command("get_vat_rates")
return ShopFetchTaxRates(shop=Shop())
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index 402830ff12..b7d47a94df 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -371,6 +371,12 @@ class AvataxPlugin(BasePlugin):
return previous_value
return False
+ def fetch_taxes_data(self, previous_value):
+ if not self.active:
+ return previous_value
+ get_cached_tax_codes_or_fetch(self.config)
+ return True
+
@classmethod
def validate_plugin_configuration(cls, plugin_configuration: "PluginConfiguration"):
"""Validate if provided configuration is correct."""
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index fc575d1ffc..554942ddf7 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -290,6 +290,10 @@ class BasePlugin:
"""
return NotImplemented
+ def fetch_taxes_data(self, previous_value: Any) -> Any:
+ """Triggered when ShopFetchTaxRates mutation is called."""
+ return NotImplemented
+
def authorize_payment(
self, payment_information: "PaymentData", previous_value
) -> "GatewayResponse":
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 65b3ee1e74..ae59bbad16 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -407,6 +407,10 @@ class PluginsManager(PaymentInterface):
return plugin
return None
+ def fetch_taxes_data(self) -> bool:
+ default_value = False
+ self.__run_method_on_plugins("fetch_taxes_data", default_value)
+
def get_plugins_manager(
manager_path: str = None, plugins: List[str] = None
diff --git a/saleor/plugins/vatlayer/__init__.py b/saleor/plugins/vatlayer/__init__.py
index fdfccb5fdc..9c896be943 100644
--- a/saleor/plugins/vatlayer/__init__.py
+++ b/saleor/plugins/vatlayer/__init__.py
@@ -1,3 +1,5 @@
+from dataclasses import dataclass
+
from django_prices_vatlayer.utils import get_tax_for_rate, get_tax_rates_for_country
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
@@ -63,6 +65,11 @@ class TaxRateType:
DEFAULT_TAX_RATE_NAME = TaxRateType.STANDARD
+@dataclass
+class VatlayerConfiguration:
+ access_key: str
+
+
def _convert_to_naive_taxed_money(base, taxes, rate_name):
"""Naively convert Money to TaxedMoney.
diff --git a/saleor/plugins/vatlayer/plugin.py b/saleor/plugins/vatlayer/plugin.py
index ae99b1945b..28f6335051 100644
--- a/saleor/plugins/vatlayer/plugin.py
+++ b/saleor/plugins/vatlayer/plugin.py
@@ -4,16 +4,21 @@ from typing import TYPE_CHECKING, Any, List, Union
from django.conf import settings
from django.core.exceptions import ValidationError
from django_countries.fields import Country
-from django_prices_vatlayer.utils import get_tax_rate_types
+from django_prices_vatlayer.utils import (
+ fetch_rate_types,
+ fetch_rates,
+ get_tax_rate_types,
+)
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
from ...checkout import calculations
from ...core.taxes import TaxType
from ...graphql.core.utils.error_codes import PluginErrorCode
-from ..base_plugin import BasePlugin
+from ..base_plugin import BasePlugin, ConfigurationTypeField
from . import (
DEFAULT_TAX_RATE_NAME,
TaxRateType,
+ VatlayerConfiguration,
apply_tax_to_price,
get_taxed_shipping_price,
get_taxes_for_country,
@@ -33,17 +38,24 @@ class VatlayerPlugin(BasePlugin):
PLUGIN_NAME = "Vatlayer"
META_CODE_KEY = "vatlayer.code"
META_DESCRIPTION_KEY = "vatlayer.description"
+ DEFAULT_CONFIGURATION = [{"name": "Access key", "value": None}]
+ CONFIG_STRUCTURE = {
+ "Access key": {
+ "type": ConfigurationTypeField.PASSWORD,
+ "help_text": "Required to authenticate to Vatlayer API.",
+ "label": "Access key",
+ },
+ }
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
+ # Convert to dict to easier take config elements
+ configuration = {item["name"]: item["value"] for item in self.configuration}
+ self.config = VatlayerConfiguration(access_key=configuration["Access key"])
self._cached_taxes = {}
- @classmethod
- def get_default_active(cls):
- return 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:
+ if not self.active or not self.config.access_key:
return True
# The previous plugin already calculated taxes so we can skip our logic
@@ -263,11 +275,37 @@ class VatlayerPlugin(BasePlugin):
tax = taxes.get(rate_name) or taxes.get(DEFAULT_TAX_RATE_NAME)
return Decimal(tax["value"])
+ def fetch_taxes_data(self, previous_value: Any) -> Any:
+ """Triggered when ShopFetchTaxRates mutation is called."""
+ if not self.active:
+ return previous_value
+ fetch_rates(self.config.access_key)
+ return True
+
@classmethod
def validate_plugin_configuration(cls, plugin_configuration: "PluginConfiguration"):
"""Validate if provided configuration is correct."""
- if not settings.VATLAYER_ACCESS_KEY and plugin_configuration.active:
+ configuration = plugin_configuration.configuration
+ configuration = {item["name"]: item["value"] for item in configuration}
+ access_key = configuration["Access key"]
+ if not access_key and plugin_configuration.active:
raise ValidationError(
- "Cannot be enabled without provided 'settings.VATLAYER_ACCESS_KEY'",
- code=PluginErrorCode.PLUGIN_MISCONFIGURED.value,
+ {
+ "Access key": ValidationError(
+ "Cannot be enabled without provided Access key",
+ code=PluginErrorCode.INVALID.value,
+ )
+ }
)
+ if access_key and plugin_configuration.active:
+ # let's check if access_key works
+ fetched_data = fetch_rate_types(access_key=access_key)
+ if not fetched_data["success"]:
+ raise ValidationError(
+ {
+ "Access key": ValidationError(
+ "Cannot enable Vatlayer. Incorrect API key.",
+ code=PluginErrorCode.INVALID.value,
+ )
+ }
+ )
diff --git a/saleor/settings.py b/saleor/settings.py
index fcf8315217..6110273b1f 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -359,19 +359,6 @@ COUNTRIES_OVERRIDE = {"EU": "European Union"}
OPENEXCHANGERATES_API_KEY = os.environ.get("OPENEXCHANGERATES_API_KEY")
-# VAT configuration
-# Enabling vat requires valid vatlayer access key.
-# If you are subscribed to a paid vatlayer plan, you can enable HTTPS.
-VATLAYER_ACCESS_KEY = os.environ.get("VATLAYER_ACCESS_KEY")
-VATLAYER_USE_HTTPS = get_bool_from_env("VATLAYER_USE_HTTPS", False)
-
-# Avatax supports two ways of log in - username:password or account:license
-AVATAX_USERNAME_OR_ACCOUNT = os.environ.get("AVATAX_USERNAME_OR_ACCOUNT")
-AVATAX_PASSWORD_OR_LICENSE = os.environ.get("AVATAX_PASSWORD_OR_LICENSE")
-AVATAX_USE_SANDBOX = get_bool_from_env("AVATAX_USE_SANDBOX", DEBUG)
-AVATAX_COMPANY_NAME = os.environ.get("AVATAX_COMPANY_NAME", "DEFAULT")
-AVATAX_AUTOCOMMIT = get_bool_from_env("AVATAX_AUTOCOMMIT", False)
-
GOOGLE_ANALYTICS_TRACKING_ID = os.environ.get("GOOGLE_ANALYTICS_TRACKING_ID")
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index 766d5e6ede..874e7e6b56 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -2118,11 +2118,14 @@ def test_product_type_query(
def test_product_type_create_mutation(
- staff_api_client, product_type, permission_manage_products, monkeypatch, settings
+ staff_api_client,
+ product_type,
+ permission_manage_products,
+ monkeypatch,
+ setup_vatlayer,
):
- settings.VATLAYER_ACCESS_KEY = "test"
- settings.PLUGINS = ["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
- manager = PluginsManager(plugins=settings.PLUGINS)
+ manager = PluginsManager(plugins=setup_vatlayer.PLUGINS)
+
query = """
mutation createProductType(
$name: String!,
diff --git a/tests/api/test_shop_taxes.py b/tests/api/test_shop_taxes.py
index d6f2a10799..3c92e6f471 100644
--- a/tests/api/test_shop_taxes.py
+++ b/tests/api/test_shop_taxes.py
@@ -1,4 +1,4 @@
-from unittest.mock import patch
+from unittest.mock import Mock
import pytest
from django_prices_vatlayer.models import VAT
@@ -54,7 +54,6 @@ def taxes(tax_rates):
@pytest.fixture
def vatlayer(db, settings, tax_rates, taxes):
- settings.VATLAYER_ACCESS_KEY = "enablevatlayer"
VAT.objects.create(country_code="PL", data=tax_rates)
tax_rates_2 = {
@@ -147,17 +146,17 @@ def test_shop_fetch_tax_rates_no_api_access_key(
data = content["data"]["shopFetchTaxRates"]
error_message = (
"Could not fetch tax rates. "
- "Make sure you have supplied a valid API Access Key."
+ "Make sure you have supplied a valid credential for your tax plugin."
)
assert data["errors"][0]["message"] == error_message
-@patch("saleor.graphql.shop.mutations.call_command")
def test_shop_fetch_tax_rates(
- mock_call_command, staff_api_client, permission_manage_settings, settings
+ monkeypatch, staff_api_client, permission_manage_settings, setup_vatlayer
):
- settings.VATLAYER_ACCESS_KEY = "KEY"
+ mocked_fetch = Mock()
+ monkeypatch.setattr("saleor.plugins.vatlayer.plugin.fetch_rates", mocked_fetch)
staff_api_client.user.user_permissions.add(permission_manage_settings)
response = staff_api_client.post_graphql(MUTATION_SHOP_FETCH_TAX_RATES)
get_graphql_content(response)
- mock_call_command.assert_called_once_with("get_vat_rates")
+ mocked_fetch.assert_called_once_with("vatlayer_access_key")
diff --git a/tests/conftest.py b/tests/conftest.py
index 48f2dbe93a..49d29ec894 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -45,6 +45,8 @@ from saleor.order.utils import recalculate_order
from saleor.page.models import Page, PageTranslation
from saleor.payment import ChargeStatus, TransactionKind
from saleor.payment.models import Payment
+from saleor.plugins.models import PluginConfiguration
+from saleor.plugins.vatlayer.plugin import VatlayerPlugin
from saleor.product import AttributeInputType
from saleor.product.models import (
Attribute,
@@ -165,6 +167,17 @@ def assert_max_num_queries(capture_queries):
return partial(capture_queries, exact=False)
+def setup_vatlayer(settings):
+ settings.PLUGINS = ["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
+ data = {
+ "active": True,
+ "configuration": [{"name": "Access key", "value": "vatlayer_access_key"},],
+ }
+ PluginConfiguration.objects.create(name=VatlayerPlugin.PLUGIN_NAME, **data)
+ return settings
+
+
@pytest.fixture(autouse=True)
def setup_dummy_gateway(settings):
settings.PLUGINS = ["saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin"]
diff --git a/tests/plugins/conftest.py b/tests/plugins/conftest.py
index b2ab8de1fa..7cab0c43ed 100644
--- a/tests/plugins/conftest.py
+++ b/tests/plugins/conftest.py
@@ -83,9 +83,8 @@ def taxes(tax_rates):
@pytest.fixture
-def vatlayer(db, settings, tax_rates, taxes):
- settings.VATLAYER_ACCESS_KEY = "enablevatlayer"
- settings.PLUGINS = ["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
+def vatlayer(db, tax_rates, taxes, setup_vatlayer):
+ setup_vatlayer
VAT.objects.create(country_code="PL", data=tax_rates)
tax_rates_2 = {
diff --git a/tests/plugins/test_vatlayer.py b/tests/plugins/test_vatlayer.py
index 78f324c34f..40da932aa8 100644
--- a/tests/plugins/test_vatlayer.py
+++ b/tests/plugins/test_vatlayer.py
@@ -471,7 +471,6 @@ def test_calculations_checkout_shipping_price_with_vatlayer(
def test_skip_diabled_plugin(settings):
settings.PLUGINS = ["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
- settings.VATLAYER_ACCESS_KEY = None
manager = get_plugins_manager()
plugin: VatlayerPlugin = manager.get_plugin("Vatlayer")
diff --git a/tests/settings.py b/tests/settings.py
index 57d8ffbce9..a1d8fdab4d 100644
--- a/tests/settings.py
+++ b/tests/settings.py
@@ -35,8 +35,6 @@ SEARCH_BACKEND = "saleor.search.backends.postgresql"
EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
-VATLAYER_ACCESS_KEY = ""
-
COUNTRIES_ONLY = None
MEDIA_ROOT = None