Skip to content

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

Move Avalara to plugin

Maciej Korycinski387804d11498
diff --git a/saleor/core/taxes/avatax/__init__.py b/saleor/core/extensions/plugins/avatax/__init__.py
similarity index 98%
rename from saleor/core/taxes/avatax/__init__.py
rename to saleor/core/extensions/plugins/avatax/__init__.py
index 3150990a9f..64472f320e 100644
--- a/saleor/core/taxes/avatax/__init__.py
+++ b/saleor/core/extensions/plugins/avatax/__init__.py
@@ -10,13 +10,12 @@ from django.core.cache import cache
from django.utils.translation import pgettext_lazy
from requests.auth import HTTPBasicAuth
-from saleor.core.utils import get_company_address
-
-from .. import charge_taxes_on_shipping, include_taxes_in_prices
+from ....taxes import charge_taxes_on_shipping, include_taxes_in_prices
+from ....utils import get_company_address # FIXME shouldn't use logic from saleor
if TYPE_CHECKING:
- from ....checkout.models import Checkout
- from ....order.models import Order
+ from .....checkout.models import Checkout
+ from .....order.models import Order
logger = logging.getLogger(__name__)
diff --git a/saleor/core/extensions/plugins/avatax/plugin.py b/saleor/core/extensions/plugins/avatax/plugin.py
new file mode 100644
index 0000000000..587ff614e5
--- /dev/null
+++ b/saleor/core/extensions/plugins/avatax/plugin.py
@@ -0,0 +1,285 @@
+import logging
+from decimal import Decimal
+from typing import TYPE_CHECKING, Any, List, Union
+from urllib.parse import urljoin
+
+from django.conf import settings
+from prices import Money, TaxedMoney, TaxedMoneyRange
+
+from .....checkout import models as checkout_models
+from ....taxes import TaxType, zero_taxed_money
+from ....taxes.errors import TaxError
+from ...plugin import BasePlugin
+from . import (
+ META_FIELD,
+ CustomerErrors,
+ TransactionType,
+ _validate_checkout,
+ _validate_order,
+ api_post_request,
+ generate_request_data_from_checkout,
+ get_api_url,
+ get_cached_tax_codes_or_fetch,
+ get_checkout_tax_data,
+ get_order_tax_data,
+)
+
+if TYPE_CHECKING:
+ from .....checkout.models import Checkout
+ from .....order.models import Order, OrderLine
+
+logger = logging.getLogger(__name__)
+
+
+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
+ )
+
+ def _skip_plugin(self, previous_value: Union[TaxedMoney, TaxedMoneyRange]) -> bool:
+ if not self._enabled:
+ return True
+
+ # The previous plugin already calculated taxes so we can skip our logic
+ if isinstance(previous_value, TaxedMoneyRange):
+ start = previous_value.start
+ stop = previous_value.stop
+
+ return start.net != start.gross and stop.net != stop.gross
+
+ if isinstance(previous_value, TaxedMoney):
+ return previous_value.net != previous_value.gross
+ return False
+
+ def calculate_checkout_total(
+ self,
+ checkout: "checkout_models.Checkout",
+ discounts: List["DiscountInfo"],
+ previous_value: TaxedMoney,
+ ) -> TaxedMoney:
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ checkout_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)
+ if not response or "error" in response:
+ return TaxedMoney(net=checkout_total, gross=checkout_total)
+
+ currency = response.get("currencyCode")
+ tax = Decimal(response.get("totalTax", 0.0))
+ total_net = Decimal(response.get("totalAmount", 0.0))
+ total_gross = Money(amount=total_net + tax, currency=currency)
+ total_net = Money(amount=total_net, currency=currency)
+ total = TaxedMoney(net=total_net, gross=total_gross)
+ voucher_amount = checkout.discount_amount
+ if voucher_amount:
+ total -= voucher_amount
+ return max(total, zero_taxed_money(total.currency))
+
+ def calculate_checkout_subtotal(
+ self,
+ checkout: "checkout_models.Checkout",
+ discounts: List["DiscountInfo"],
+ previous_value: TaxedMoney,
+ ) -> TaxedMoney:
+
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ sub_total = checkout.get_subtotal(discounts)
+ if not _validate_checkout(checkout):
+ return TaxedMoney(net=sub_total, gross=sub_total)
+
+ response = get_checkout_tax_data(checkout, discounts)
+ if not response or "error" in response:
+ return TaxedMoney(net=sub_total, gross=sub_total)
+
+ currency = response.get("currencyCode")
+ sub_tax = Decimal(0.0)
+ sub_net = Decimal(0.0)
+ for line in response.get("lines", []):
+ if line["itemCode"] == "Shipping":
+ continue
+ sub_tax += Decimal(line["tax"])
+ sub_net += Decimal(line.get("lineAmount", 0.0))
+
+ sub_total_gross = Money(sub_net + sub_tax, currency)
+ sub_total_net = Money(sub_net, currency)
+ return TaxedMoney(net=sub_total_net, gross=sub_total_gross)
+
+ def calculate_checkout_shipping(
+ self,
+ checkout: "checkout_models.Checkout",
+ discounts: List["DiscountInfo"],
+ previous_value: TaxedMoney,
+ ) -> TaxedMoney:
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ shipping_price = checkout.get_shipping_price()
+ if not _validate_checkout(checkout):
+ return TaxedMoney(net=shipping_price, gross=shipping_price)
+
+ response = get_checkout_tax_data(checkout, discounts)
+ if not response or "error" in response:
+ return TaxedMoney(net=shipping_price, gross=shipping_price)
+
+ shipping_tax = Decimal(0.0)
+ shipping_net = shipping_price.amount
+ currency = response.get("currencyCode")
+ for line in response.get("lines", []):
+ if line["itemCode"] == "Shipping":
+ shipping_net = Decimal(line["lineAmount"])
+ shipping_tax = Decimal(line["tax"])
+ break
+
+ shipping_gross = Money(amount=shipping_net + shipping_tax, currency=currency)
+ shipping_net = Money(amount=shipping_net, currency=currency)
+ return TaxedMoney(net=shipping_net, gross=shipping_gross)
+
+ def preprocess_order_creation(
+ self, checkout: "Checkout", discounts: List["DiscountInfo"], previous_value: Any
+ ):
+ """Confirm that all data is correct and we can proceed with creation of order.
+ Raise error when can't receive taxes"""
+ if not self._enabled:
+ return
+ data = generate_request_data_from_checkout(
+ checkout,
+ 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)
+ if not response or "error" in response:
+ msg = response.get("error", {}).get("message", "")
+ error_code = response.get("error", {}).get("code", "")
+ logger.warning(
+ "Unable to calculate taxes for checkout %s, error_code: %s, "
+ "error_msg: %s",
+ checkout.token,
+ error_code,
+ msg,
+ )
+ customer_msg = CustomerErrors.get_error_msg(response.get("error", {}))
+ raise TaxError(customer_msg)
+
+ def postprocess_order_creation(self, order: "Order", previous_value: Any):
+ # FIXME after we introduce plugin architecture, this logic could be a celery
+ # task
+ if not self._enabled:
+ return
+ data = get_order_tax_data(
+ order, commit=settings.AVATAX_AUTOCOMMIT, force_refresh=True
+ )
+
+ transaction_url = urljoin(get_api_url(), "transactions/createoradjust")
+ api_post_request(transaction_url, data)
+
+ def calculate_checkout_line_total(
+ self,
+ checkout_line: "checkout_models.CheckoutLine",
+ discounts: List["DiscountInfo"],
+ previous_value: TaxedMoney,
+ ) -> TaxedMoney:
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ checkout = checkout_line.checkout
+ 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)
+ currency = taxes_data.get("currencyCode")
+ for line in taxes_data.get("lines", []):
+ if line.get("itemCode") == checkout_line.variant.sku:
+ tax = Decimal(line.get("tax", 0.0))
+ line_net = Decimal(line["lineAmount"])
+ line_gross = Money(amount=line_net + tax, currency=currency)
+ line_net = Money(amount=line_net, currency=currency)
+ return TaxedMoney(net=line_net, gross=line_gross)
+
+ total = checkout_line.get_total(discounts)
+ return TaxedMoney(net=total, gross=total)
+
+ def calculate_order_line_unit(
+ self, order_line: "OrderLine", previous_value: TaxedMoney
+ ) -> TaxedMoney:
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ order = order_line.order
+ if _validate_order(order):
+ taxes_data = get_order_tax_data(order)
+ currency = taxes_data.get("currencyCode")
+ for line in taxes_data.get("lines", []):
+ if line.get("itemCode") == order_line.variant.sku:
+ tax = Decimal(line.get("tax", 0.0)) / order_line.quantity
+ net = Decimal(line.get("lineAmount", 0.0)) / order_line.quantity
+
+ gross = Money(amount=net + tax, currency=currency)
+ net = Money(amount=net, currency=currency)
+ return TaxedMoney(net=net, gross=gross)
+ return order_line.unit_price
+
+ def calculate_order_shipping(
+ self, order: "Order", previous_value: TaxedMoney
+ ) -> TaxedMoney:
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ if not _validate_order(order):
+ return zero_taxed_money(order.total.currency)
+ taxes_data = get_order_tax_data(order, False)
+ currency = taxes_data.get("currencyCode")
+ for line in taxes_data.get("lines", []):
+ if line["itemCode"] == "Shipping":
+ tax = Decimal(line.get("tax", 0.0))
+ net = Decimal(line.get("lineAmount", 0.0))
+ gross = Money(amount=net + tax, currency=currency)
+ net = Money(amount=net, currency=currency)
+ return TaxedMoney(net=net, gross=gross)
+ return TaxedMoney(
+ net=order.shipping_method.price, gross=order.shipping_method.price
+ )
+
+ def get_tax_rate_type_choices(self, previous_value: Any) -> List[TaxType]:
+ if not self._enabled:
+ return previous_value
+ return [
+ TaxType(code=tax_code, description=desc)
+ for tax_code, desc in get_cached_tax_codes_or_fetch().items()
+ ]
+
+ def assign_tax_code_to_object_meta(
+ self, obj: Union["Product", "ProductType"], tax_code: str, previous_value: Any
+ ):
+ if not self._enabled:
+ return previous_value
+
+ codes = get_cached_tax_codes_or_fetch()
+ if tax_code not in codes:
+ return
+
+ tax_description = codes[tax_code]
+ if not hasattr(obj, "meta"):
+ return
+ if "taxes" not in obj.meta:
+ obj.meta["taxes"] = {}
+ obj.meta["taxes"][META_FIELD] = {
+ "code": tax_code,
+ "description": tax_description,
+ }
+
+ def get_tax_code_from_object_meta(
+ self, obj: Union["Product", "ProductType"], previous_value: Any
+ ) -> TaxType:
+ if not self._enabled:
+ return previous_value
+ tax = obj.meta.get("taxes", {}).get(META_FIELD, {})
+ return TaxType(code=tax.get("code", ""), description=tax.get("description", ""))
diff --git a/saleor/core/extensions/plugins/vatlayer/plugin.py b/saleor/core/extensions/plugins/vatlayer/plugin.py
index 5b60616a70..4eda7261aa 100644
--- a/saleor/core/extensions/plugins/vatlayer/plugin.py
+++ b/saleor/core/extensions/plugins/vatlayer/plugin.py
@@ -225,8 +225,7 @@ class VatlayerPlugin(BasePlugin):
if tax_code not in dict(TaxRateType.CHOICES):
return previous_value
- if not hasattr(obj, "meta"):
- return previous_value
+
if "taxes" not in obj.meta:
obj.meta["taxes"] = {}
obj.meta["taxes"][self.META_FIELD] = {"code": tax_code, "description": tax_code}
diff --git a/saleor/core/middleware.py b/saleor/core/middleware.py
index 0a904021b7..607f3a8dcf 100644
--- a/saleor/core/middleware.py
+++ b/saleor/core/middleware.py
@@ -102,7 +102,7 @@ def taxes(get_response):
if settings.VATLAYER_ACCESS_KEY:
# FIXME this should be disabled after we will introduce plugin architecure.
# For now, a lot of templates use tax_rate function.
- from .taxes.vatlayer import get_taxes_for_country
+ from .extensions.plugins.vatlayer import get_taxes_for_country
request.taxes = SimpleLazyObject(
lambda: get_taxes_for_country(request.country)
diff --git a/saleor/core/taxes/avatax/interface.py b/saleor/core/taxes/avatax/interface.py
deleted file mode 100644
index 7329858c62..0000000000
--- a/saleor/core/taxes/avatax/interface.py
+++ /dev/null
@@ -1,220 +0,0 @@
-import logging
-from decimal import Decimal
-from typing import TYPE_CHECKING, List, Union
-from urllib.parse import urljoin
-
-from django.conf import settings
-from prices import Money, TaxedMoney
-
-from ....checkout import models as checkout_models
-from .. import TaxType, zero_taxed_money
-from ..errors import TaxError
-from . import (
- META_FIELD,
- CustomerErrors,
- TransactionType,
- _validate_checkout,
- _validate_order,
- api_post_request,
- generate_request_data_from_checkout,
- get_api_url,
- get_cached_tax_codes_or_fetch,
- get_checkout_tax_data,
- get_order_tax_data,
-)
-
-if TYPE_CHECKING:
- from ....checkout.models import Checkout
- from ....order.models import Order, OrderLine
-
-logger = logging.getLogger(__name__)
-
-
-def calculate_checkout_total(
- checkout: "checkout_models.Checkout", discounts: List["DiscountInfo"]
-):
- checkout_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)
- if not response or "error" in response:
- return TaxedMoney(net=checkout_total, gross=checkout_total)
-
- currency = response.get("currencyCode")
- tax = Decimal(response.get("totalTax", 0.0))
- total_net = Decimal(response.get("totalAmount", 0.0))
- total_gross = Money(amount=total_net + tax, currency=currency)
- total_net = Money(amount=total_net, currency=currency)
- total = TaxedMoney(net=total_net, gross=total_gross)
- voucher_amount = checkout.discount_amount
- if voucher_amount:
- total -= voucher_amount
- return max(total, zero_taxed_money(total.currency))
-
-
-def calculate_checkout_subtotal(
- checkout: "checkout_models.Checkout", discounts: List["DiscountInfo"]
-):
- sub_total = checkout.get_subtotal(discounts)
- if not _validate_checkout(checkout):
- return TaxedMoney(net=sub_total, gross=sub_total)
-
- response = get_checkout_tax_data(checkout, discounts)
- if not response or "error" in response:
- return TaxedMoney(net=sub_total, gross=sub_total)
-
- currency = response.get("currencyCode")
- sub_tax = Decimal(0.0)
- sub_net = Decimal(0.0)
- for line in response.get("lines", []):
- if line["itemCode"] == "Shipping":
- continue
- sub_tax += Decimal(line["tax"])
- sub_net += Decimal(line.get("lineAmount", 0.0))
-
- sub_total_gross = Money(sub_net + sub_tax, currency)
- sub_total_net = Money(sub_net, currency)
- return TaxedMoney(net=sub_total_net, gross=sub_total_gross)
-
-
-def calculate_checkout_shipping(
- checkout: "checkout_models.Checkout", discounts: List["DiscountInfo"]
-):
- shipping_price = checkout.get_shipping_price()
- if not _validate_checkout(checkout):
- return TaxedMoney(net=shipping_price, gross=shipping_price)
-
- response = get_checkout_tax_data(checkout, discounts)
- if not response or "error" in response:
- return TaxedMoney(net=shipping_price, gross=shipping_price)
-
- shipping_tax = Decimal(0.0)
- shipping_net = shipping_price.amount
- currency = response.get("currencyCode")
- for line in response.get("lines", []):
- if line["itemCode"] == "Shipping":
- shipping_net = Decimal(line["lineAmount"])
- shipping_tax = Decimal(line["tax"])
- break
-
- shipping_gross = Money(amount=shipping_net + shipping_tax, currency=currency)
- shipping_net = Money(amount=shipping_net, currency=currency)
- return TaxedMoney(net=shipping_net, gross=shipping_gross)
-
-
-def preprocess_order_creation(checkout: "Checkout", discounts: List["DiscountInfo"]):
- """Confirm that all data is correct and we can proceed with creation of order.
- Raise error when can't receive taxes"""
-
- data = generate_request_data_from_checkout(
- checkout,
- 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)
- if not response or "error" in response:
- msg = response.get("error", {}).get("message", "")
- error_code = response.get("error", {}).get("code", "")
- logger.warning(
- "Unable to calculate taxes for checkout %s, error_code: %s, error_msg: %s",
- checkout.token,
- error_code,
- msg,
- )
- customer_msg = CustomerErrors.get_error_msg(response.get("error", {}))
- raise TaxError(customer_msg)
-
-
-def postprocess_order_creation(order: "Order"):
- # FIXME after we introduce plugin architecture, this logic could be a celery task
-
- data = get_order_tax_data(
- order, commit=settings.AVATAX_AUTOCOMMIT, force_refresh=True
- )
-
- transaction_url = urljoin(get_api_url(), "transactions/createoradjust")
- api_post_request(transaction_url, data)
-
-
-def calculate_checkout_line_total(
- checkout_line: "checkout_models.CheckoutLine", discounts: List["DiscountInfo"]
-):
- checkout = checkout_line.checkout
- 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)
- currency = taxes_data.get("currencyCode")
- for line in taxes_data.get("lines", []):
- if line.get("itemCode") == checkout_line.variant.sku:
- tax = Decimal(line.get("tax", 0.0))
- line_net = Decimal(line["lineAmount"])
- line_gross = Money(amount=line_net + tax, currency=currency)
- line_net = Money(amount=line_net, currency=currency)
- return TaxedMoney(net=line_net, gross=line_gross)
-
- total = checkout_line.get_total(discounts)
- return TaxedMoney(net=total, gross=total)
-
-
-def calculate_order_line_unit(order_line: "OrderLine"):
- order = order_line.order
- if _validate_order(order):
- taxes_data = get_order_tax_data(order)
- currency = taxes_data.get("currencyCode")
- for line in taxes_data.get("lines", []):
- if line.get("itemCode") == order_line.variant.sku:
- tax = Decimal(line.get("tax", 0.0)) / order_line.quantity
- net = Decimal(line.get("lineAmount", 0.0)) / order_line.quantity
-
- gross = Money(amount=net + tax, currency=currency)
- net = Money(amount=net, currency=currency)
- return TaxedMoney(net=net, gross=gross)
- return order_line.unit_price
-
-
-def calculate_order_shipping(order: "Order"):
- if not _validate_order(order):
- return zero_taxed_money(order.total.currency)
- taxes_data = get_order_tax_data(order, False)
- currency = taxes_data.get("currencyCode")
- for line in taxes_data.get("lines", []):
- if line["itemCode"] == "Shipping":
- tax = Decimal(line.get("tax", 0.0))
- net = Decimal(line.get("lineAmount", 0.0))
- gross = Money(amount=net + tax, currency=currency)
- net = Money(amount=net, currency=currency)
- return TaxedMoney(net=net, gross=gross)
- return TaxedMoney(
- net=order.shipping_method.price, gross=order.shipping_method.price
- )
-
-
-def get_tax_rate_type_choices() -> List[TaxType]:
- return [
- TaxType(code=tax_code, description=desc)
- for tax_code, desc in get_cached_tax_codes_or_fetch().items()
- ]
-
-
-def assign_tax_to_object_meta(obj: Union["Product", "ProductType"], tax_code: str):
- codes = get_cached_tax_codes_or_fetch()
- if tax_code not in codes:
- return
-
- tax_description = codes[tax_code]
- if not hasattr(obj, "meta"):
- return
- if "taxes" not in obj.meta:
- obj.meta["taxes"] = {}
- obj.meta["taxes"]["avatax"] = {"code": tax_code, "description": tax_description}
-
-
-def get_tax_from_object_meta(obj: Union["Product", "ProductType"]) -> TaxType:
- if not hasattr(obj, "meta"):
- return TaxType(code="", description="")
-
- tax = obj.meta.get("taxes", {}).get(META_FIELD, {})
- return TaxType(code=tax.get("code", ""), description=tax.get("description", ""))
diff --git a/saleor/core/taxes/interface.py b/saleor/core/taxes/interface.py
deleted file mode 100644
index f66da247c2..0000000000
--- a/saleor/core/taxes/interface.py
+++ /dev/null
@@ -1,207 +0,0 @@
-from typing import TYPE_CHECKING, List, Union
-
-from django.conf import settings
-from django_countries.fields import Country
-from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
-
-from . import TaxType, quantize_price
-from .avatax import interface as avatax_interface
-from .vatlayer import interface as vatlayer_interface
-
-if TYPE_CHECKING:
- from ...checkout.models import Checkout, CheckoutLine
- from ...product.models import Product
- from ...account.models import Address
- from ...order.models import OrderLine, Order
-
-
-def calculate_checkout_total(
- checkout: "Checkout", discounts: List["DiscountInfo"]
-) -> TaxedMoney:
- """Calculate total gross for checkout"""
-
- total = None
- if settings.VATLAYER_ACCESS_KEY:
- total = vatlayer_interface.calculate_checkout_total(checkout, discounts)
- elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- total = avatax_interface.calculate_checkout_total(checkout, discounts)
-
- if total is not None:
- return quantize_price(total, total.currency)
-
- total = checkout.get_total(discounts)
- return quantize_price(TaxedMoney(net=total, gross=total), total.currency)
-
-
-def calculate_checkout_subtotal(
- checkout: "Checkout", discounts: List["DiscountInfo"]
-) -> TaxedMoney:
- """Calculate subtotal gross for checkout"""
-
- subtotal = None
- if settings.VATLAYER_ACCESS_KEY:
- subtotal = vatlayer_interface.calculate_checkout_subtotal(checkout, discounts)
- elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- subtotal = avatax_interface.calculate_checkout_subtotal(checkout, discounts)
-
- if subtotal is not None:
- return quantize_price(subtotal, subtotal.currency)
-
- subtotal = checkout.get_subtotal(discounts)
- return quantize_price(TaxedMoney(net=subtotal, gross=subtotal), subtotal.currency)
-
-
-def calculate_checkout_shipping(
- checkout: "Checkout", discounts: List["DiscountInfo"]
-) -> TaxedMoney:
- """Calculate shipping gross for checkout"""
- total = checkout.get_shipping_price()
- total = TaxedMoney(net=total, gross=total)
- if not checkout.shipping_method:
- return quantize_price(total, total.currency)
- if settings.VATLAYER_ACCESS_KEY:
- total = vatlayer_interface.calculate_checkout_shipping(checkout, discounts)
- elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- total = avatax_interface.calculate_checkout_shipping(checkout, discounts)
- return quantize_price(total, total.currency)
-
-
-def calculate_order_shipping(order: "Order") -> TaxedMoney:
- """Calculate shipping price that assigned to order"""
- shipping_price = None
- if settings.VATLAYER_ACCESS_KEY:
- shipping_price = vatlayer_interface.calculate_order_shipping(order)
- elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- shipping_price = avatax_interface.calculate_order_shipping(order)
-
- if shipping_price is not None:
- return quantize_price(shipping_price, shipping_price.currency)
- shipping_price = order.shipping_method.price
- return quantize_price(
- TaxedMoney(net=shipping_price, gross=shipping_price), shipping_price.currency
- )
-
-
-def apply_taxes_to_shipping(price: Money, shipping_address: "Address") -> TaxedMoney:
- """Apply taxes for shipping methods that user can use during checkout"""
- if shipping_address:
- if settings.VATLAYER_ACCESS_KEY:
- return quantize_price(
- vatlayer_interface.apply_taxes_to_shipping(price, shipping_address),
- price.currency,
- )
- if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- # For now we can't calculate product/shipping prices that are not directly
- # assigned to order. Avatax has api only to calculate prices based on
- # checkout/order data
- pass
- return quantize_price(TaxedMoney(net=price, gross=price), price.currency)
-
-
-def get_tax_rate_type_choices() -> List[TaxType]:
- if settings.VATLAYER_ACCESS_KEY:
- return vatlayer_interface.get_tax_rate_type_choices()
- if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- return avatax_interface.get_tax_rate_type_choices()
- return []
-
-
-def calculate_checkout_line_total(
- checkout_line: "CheckoutLine", discounts: List["DiscountInfo"]
-):
- total = None
- if settings.VATLAYER_ACCESS_KEY:
- total = vatlayer_interface.calculate_checkout_line_total(
- checkout_line, discounts
- )
- elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- total = avatax_interface.calculate_checkout_line_total(checkout_line, discounts)
- if total is not None:
- return quantize_price(total, total.currency)
- total = checkout_line.get_total(discounts)
- return quantize_price(TaxedMoney(net=total, gross=total), total.currency)
-
-
-def calculate_order_line_unit(order_line: "OrderLine"):
- """It updates unit_price for a given order line based on current price of variant"""
- if settings.VATLAYER_ACCESS_KEY:
- unit_price = vatlayer_interface.calculate_order_line_unit(order_line)
- elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- unit_price = avatax_interface.calculate_order_line_unit(order_line)
- else:
- unit_price = order_line.unit_price
-
- return quantize_price(unit_price, unit_price.currency)
-
-
-def apply_taxes_to_product(
- product: "Product", price: Money, country: Country, **kwargs
-):
- if settings.VATLAYER_ACCESS_KEY:
- return quantize_price(
- vatlayer_interface.apply_taxes_to_product(
- product, price, country, **kwargs
- ),
- price.currency,
- )
- elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- pass
- return quantize_price(TaxedMoney(net=price, gross=price), price.currency)
-
-
-def show_taxes_on_storefront() -> bool:
- """Specify if taxes are enabled"""
- if settings.VATLAYER_ACCESS_KEY:
- return True
- if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- return False
- return False
-
-
-def taxes_are_enabled() -> bool:
- if settings.VATLAYER_ACCESS_KEY:
- return True
- if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- return True
- return False
-
-
-def apply_taxes_to_shipping_price_range(prices: MoneyRange, country: Country):
- if country:
- if settings.VATLAYER_ACCESS_KEY:
- return quantize_price(
- vatlayer_interface.apply_taxes_to_shipping_price_range(prices, country),
- prices.currency,
- )
- if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- pass
- start = TaxedMoney(net=prices.start, gross=prices.start)
- stop = TaxedMoney(net=prices.stop, gross=prices.stop)
- return quantize_price(TaxedMoneyRange(start=start, stop=stop), start.currency)
-
-
-def preprocess_order_creation(checkout: "Checkout", discounts: List["DiscountInfo"]):
- if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- return avatax_interface.preprocess_order_creation(checkout, discounts)
-
-
-# FIXME this should be converted to the plugin action after we introduce plugin
-# architecture
-def postprocess_order_creation(order: "Order"):
- if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- return avatax_interface.postprocess_order_creation(order)
-
-
-def assign_tax_to_object_meta(obj: Union["Product", "ProductType"], tax_code: str):
- if settings.VATLAYER_ACCESS_KEY:
- vatlayer_interface.assign_tax_to_object_meta(obj, tax_code)
- if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- avatax_interface.assign_tax_to_object_meta(obj, tax_code)
-
-
-def get_tax_from_object_meta(obj: Union["Product", "ProductType"],) -> TaxType:
- if settings.VATLAYER_ACCESS_KEY:
- return vatlayer_interface.get_tax_from_object_meta(obj)
- if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- return avatax_interface.get_tax_from_object_meta(obj)
- return TaxType(code="", description="")
diff --git a/saleor/core/templatetags/taxed_prices.py b/saleor/core/templatetags/taxed_prices.py
index 4742ffa5d6..238d7472da 100644
--- a/saleor/core/templatetags/taxed_prices.py
+++ b/saleor/core/templatetags/taxed_prices.py
@@ -1,8 +1,8 @@
from django import template
from prices import MoneyRange, TaxedMoney, TaxedMoneyRange
+from ...core.extensions.plugins.vatlayer import DEFAULT_TAX_RATE_NAME
from ...core.taxes import get_display_price
-from ...core.taxes.vatlayer import DEFAULT_TAX_RATE_NAME
# FIXME This const variable belongs to vatlayer, we shouldn't take it directly from
# vatlayer module. This should be moved to plugin after we will introduce plugin
diff --git a/saleor/dashboard/taxes/views.py b/saleor/dashboard/taxes/views.py
index 756d36e4e2..3d40e79854 100644
--- a/saleor/dashboard/taxes/views.py
+++ b/saleor/dashboard/taxes/views.py
@@ -13,7 +13,7 @@ from django.views.decorators.http import require_POST
from django_countries.fields import Country
from django_prices_vatlayer.models import VAT
-from ...core.taxes.vatlayer import TaxRateType, get_taxes_for_country
+from ...core.extensions.plugins.vatlayer import TaxRateType, get_taxes_for_country
from ...core.utils import get_paginator_items
from ...dashboard.taxes.filters import TaxFilter
from ...dashboard.taxes.forms import TaxesConfigurationForm
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index 7af4636322..e1ccf94c8b 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -1,7 +1,7 @@
import graphene
+from ...core.extensions.plugins.vatlayer import TaxRateType as CoreTaxRateType
from ...core.permissions import MODELS_PERMISSIONS
-from ...core.taxes.vatlayer import TaxRateType as CoreTaxRateType
from ...core.weight import WeightUnits
from .utils import str_to_enum
diff --git a/saleor/product/migrations/0079_default_tax_rate_instead_of_empty_field.py b/saleor/product/migrations/0079_default_tax_rate_instead_of_empty_field.py
index d1cd6116d7..6fde07be9c 100644
--- a/saleor/product/migrations/0079_default_tax_rate_instead_of_empty_field.py
+++ b/saleor/product/migrations/0079_default_tax_rate_instead_of_empty_field.py
@@ -2,13 +2,11 @@
from django.db import migrations, models
-from ...core.taxes.vatlayer import DEFAULT_TAX_RATE_NAME
-
def add_default_tax_rate_instead_of_empty_field(apps, schema_editor):
ProductType = apps.get_model("product", "ProductType")
product_types = ProductType.objects.filter(tax_rate="")
- product_types.update(tax_rate=DEFAULT_TAX_RATE_NAME)
+ product_types.update(tax_rate="standard")
class Migration(migrations.Migration):
diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.py
index 7d1cf49149..7cf81a54a3 100644
--- a/saleor/product/utils/__init__.py
+++ b/saleor/product/utils/__init__.py
@@ -141,7 +141,7 @@ def get_product_list_context(request, filter_set):
request.discounts,
request.country,
request.currency,
- request.taxes,
+ request.extensions,
)
)
now_sorted_by = get_now_sorted_by(filter_set)
diff --git a/tests/taxes/cassettes/test_calculate_checkout_line_total[False-24.39-30.00-True].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_line_total[False-24.39-30.00-True].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_line_total[False-24.39-30.00-True].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_line_total[False-24.39-30.00-True].yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_line_total[False-30.00-36.90-False].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_line_total[False-30.00-36.90-False].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_line_total[False-30.00-36.90-False].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_line_total[False-30.00-36.90-False].yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_line_total[True-12.20-15.00-True].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_line_total[True-12.20-15.00-True].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_line_total[True-12.20-15.00-True].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_line_total[True-12.20-15.00-True].yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_line_total[True-15.00-18.45-False].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_line_total[True-15.00-18.45-False].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_line_total[True-15.00-18.45-False].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_line_total[True-15.00-18.45-False].yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_shipping.yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_shipping.yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_shipping.yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_shipping.yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_subtotal[False-40.65-50.00-True].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_subtotal[False-40.65-50.00-True].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_subtotal[False-40.65-50.00-True].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_subtotal[False-40.65-50.00-True].yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_subtotal[False-50.00-61.50-False].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_subtotal[False-50.00-61.50-False].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_subtotal[False-50.00-61.50-False].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_subtotal[False-50.00-61.50-False].yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_subtotal[True-20.33-25.00-True].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_subtotal[True-20.33-25.00-True].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_subtotal[True-20.33-25.00-True].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_subtotal[True-20.33-25.00-True].yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_subtotal[True-25.00-30.75-False].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_subtotal[True-25.00-30.75-False].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_subtotal[True-25.00-30.75-False].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_subtotal[True-25.00-30.75-False].yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_total[False-29.52-37.00-3.0-True].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_total[False-29.52-37.00-3.0-True].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_total[False-29.52-37.00-3.0-True].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_total[False-29.52-37.00-3.0-True].yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_total[False-37.00-37.00-3.0-True].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_total[False-37.00-37.00-3.0-True].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_total[False-37.00-37.00-3.0-True].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_total[False-37.00-37.00-3.0-True].yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_total[False-40.00-40.00-0.0-False].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_total[False-40.00-40.00-0.0-False].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_total[False-40.00-40.00-0.0-False].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_total[False-40.00-40.00-0.0-False].yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_total[False-40.00-49.20-0.0-False].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_total[False-40.00-49.20-0.0-False].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_total[False-40.00-49.20-0.0-False].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_total[False-40.00-49.20-0.0-False].yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_total[True-20.00-20.00-5.0-False].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_total[True-20.00-20.00-5.0-False].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_total[True-20.00-20.00-5.0-False].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_total[True-20.00-20.00-5.0-False].yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_total[True-20.00-25.75-5.0-False].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_total[True-20.00-25.75-5.0-False].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_total[True-20.00-25.75-5.0-False].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_total[True-20.00-25.75-5.0-False].yaml
diff --git a/tests/taxes/cassettes/test_calculate_checkout_total[True-20.33-25.00-0.0-True].yaml b/tests/extensions/plugins/cassettes/test_calculate_checkout_total[True-20.33-25.00-0.0-True].yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_checkout_total[True-20.33-25.00-0.0-True].yaml
rename to tests/extensions/plugins/cassettes/test_calculate_checkout_total[True-20.33-25.00-0.0-True].yaml
diff --git a/tests/taxes/cassettes/test_calculate_order_line_unit.yaml b/tests/extensions/plugins/cassettes/test_calculate_order_line_unit.yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_order_line_unit.yaml
rename to tests/extensions/plugins/cassettes/test_calculate_order_line_unit.yaml
diff --git a/tests/taxes/cassettes/test_calculate_order_shipping.yaml b/tests/extensions/plugins/cassettes/test_calculate_order_shipping.yaml
similarity index 100%
rename from tests/taxes/cassettes/test_calculate_order_shipping.yaml
rename to tests/extensions/plugins/cassettes/test_calculate_order_shipping.yaml
diff --git a/tests/taxes/test_avatax.py b/tests/extensions/plugins/test_avatax.py
similarity index 69%
rename from tests/taxes/test_avatax.py
rename to tests/extensions/plugins/test_avatax.py
index 1dba0099f5..46b9b93d82 100644
--- a/tests/taxes/test_avatax.py
+++ b/tests/extensions/plugins/test_avatax.py
@@ -2,8 +2,8 @@ import pytest
from prices import Money, TaxedMoney
from saleor.checkout.utils import add_variant_to_checkout
+from saleor.core.extensions.manager import get_extensions_manager
from saleor.core.taxes import quantize_price
-from saleor.core.taxes.avatax import interface
@pytest.mark.vcr()
@@ -28,11 +28,17 @@ def test_calculate_checkout_line_total(
site_settings,
monkeypatch,
shipping_zone,
+ settings,
):
+ settings.AVATAX_USERNAME_OR_ACCOUNT = "test"
+ settings.AVATAX_PASSWORD_OR_LICENSE = "test"
+ settings.PLUGINS = ["saleor.core.extensions.plugins.avatax.plugin.AvataxPlugin"]
monkeypatch.setattr(
- "saleor.core.taxes.avatax.interface.get_cached_tax_codes_or_fetch",
+ "saleor.core.extensions.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",
lambda: {"PC040156": "desc"},
)
+ manager = get_extensions_manager(plugins=settings.PLUGINS)
+
checkout_with_item.shipping_address = address
checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
checkout_with_item.save()
@@ -41,10 +47,10 @@ def test_calculate_checkout_line_total(
site_settings.save()
line = checkout_with_item.lines.first()
product = line.variant.product
- interface.assign_tax_to_object_meta(product, "PC040156")
+ manager.assign_tax_code_to_object_meta(product, "PC040156")
product.save()
discounts = [discount_info] if with_discount else None
- total = interface.calculate_checkout_line_total(line, discounts)
+ total = manager.calculate_checkout_line_total(line, discounts)
total = quantize_price(total, total.currency)
assert total == TaxedMoney(
net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
@@ -74,11 +80,16 @@ def test_calculate_checkout_total(
address_usa,
site_settings,
monkeypatch,
+ settings,
):
+ settings.AVATAX_USERNAME_OR_ACCOUNT = "test"
+ settings.AVATAX_PASSWORD_OR_LICENSE = "test"
+ settings.PLUGINS = ["saleor.core.extensions.plugins.avatax.plugin.AvataxPlugin"]
monkeypatch.setattr(
- "saleor.core.taxes.avatax.interface.get_cached_tax_codes_or_fetch",
+ "saleor.core.extensions.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",
lambda: {"PC040156": "desc"},
)
+ manager = get_extensions_manager(plugins=settings.PLUGINS)
checkout_with_item.shipping_address = address
checkout_with_item.save()
site_settings.company_address = address_usa
@@ -90,11 +101,11 @@ def test_calculate_checkout_total(
checkout_with_item.save()
line = checkout_with_item.lines.first()
product = line.variant.product
- interface.assign_tax_to_object_meta(product, "PC040156")
+ manager.assign_tax_code_to_object_meta(product, "PC040156")
product.save()
discounts = [discount_info] if with_discount else None
- total = interface.calculate_checkout_total(checkout_with_item, discounts)
+ total = manager.calculate_checkout_total(checkout_with_item, discounts)
total = quantize_price(total, total.currency)
assert total == TaxedMoney(
net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
@@ -110,19 +121,23 @@ def test_calculate_checkout_shipping(
address_usa,
site_settings,
monkeypatch,
+ settings,
):
+ settings.AVATAX_USERNAME_OR_ACCOUNT = "test"
+ settings.AVATAX_PASSWORD_OR_LICENSE = "test"
+ settings.PLUGINS = ["saleor.core.extensions.plugins.avatax.plugin.AvataxPlugin"]
monkeypatch.setattr(
- "saleor.core.taxes.avatax.interface.get_cached_tax_codes_or_fetch",
+ "saleor.core.extensions.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",
lambda: {"PC040156": "desc"},
)
-
+ manager = get_extensions_manager(plugins=settings.PLUGINS)
site_settings.company_address = address_usa
site_settings.save()
checkout_with_item.shipping_address = address
checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
checkout_with_item.save()
- shipping_price = interface.calculate_checkout_shipping(
+ shipping_price = manager.calculate_checkout_shipping(
checkout_with_item, [discount_info]
)
shipping_price = quantize_price(shipping_price, shipping_price.currency)
@@ -154,12 +169,16 @@ def test_calculate_checkout_subtotal(
address_usa,
shipping_zone,
address,
+ settings,
):
+ settings.AVATAX_USERNAME_OR_ACCOUNT = "test"
+ settings.AVATAX_PASSWORD_OR_LICENSE = "test"
+ settings.PLUGINS = ["saleor.core.extensions.plugins.avatax.plugin.AvataxPlugin"]
monkeypatch.setattr(
- "saleor.core.taxes.avatax.interface.get_cached_tax_codes_or_fetch",
+ "saleor.core.extensions.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",
lambda: {"PC040156": "desc"},
)
-
+ manager = get_extensions_manager(plugins=settings.PLUGINS)
site_settings.company_address = address_usa
site_settings.include_taxes_in_prices = taxes_in_prices
site_settings.save()
@@ -170,7 +189,7 @@ def test_calculate_checkout_subtotal(
discounts = [discount_info] if with_discount else None
add_variant_to_checkout(checkout_with_item, variant, 2)
- total = interface.calculate_checkout_subtotal(checkout_with_item, discounts)
+ total = manager.calculate_checkout_subtotal(checkout_with_item, discounts)
total = quantize_price(total, total.currency)
assert total == TaxedMoney(
net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
@@ -179,8 +198,12 @@ def test_calculate_checkout_subtotal(
@pytest.mark.vcr
def test_calculate_order_shipping(
- order_line, shipping_zone, site_settings, address_usa
+ order_line, shipping_zone, site_settings, address_usa, settings
):
+ settings.AVATAX_USERNAME_OR_ACCOUNT = "test"
+ settings.AVATAX_PASSWORD_OR_LICENSE = "test"
+ settings.PLUGINS = ["saleor.core.extensions.plugins.avatax.plugin.AvataxPlugin"]
+ manager = get_extensions_manager(plugins=settings.PLUGINS)
order = order_line.order
method = shipping_zone.shipping_methods.get()
order.shipping_address = order.billing_address.get_copy()
@@ -191,15 +214,20 @@ def test_calculate_order_shipping(
site_settings.company_address = address_usa
site_settings.save()
- price = interface.calculate_order_shipping(order)
+ price = manager.calculate_order_shipping(order)
price = quantize_price(price, price.currency)
assert price == TaxedMoney(net=Money("8.13", "USD"), gross=Money("10.00", "USD"))
@pytest.mark.vcr
def test_calculate_order_line_unit(
- order_line, shipping_zone, site_settings, address_usa
+ order_line, shipping_zone, site_settings, address_usa, settings
):
+ settings.AVATAX_USERNAME_OR_ACCOUNT = "test"
+ settings.AVATAX_PASSWORD_OR_LICENSE = "test"
+ settings.PLUGINS = ["saleor.core.extensions.plugins.avatax.plugin.AvataxPlugin"]
+
+ manager = get_extensions_manager(plugins=settings.PLUGINS)
order_line.unit_price = TaxedMoney(
net=Money("10.00", "USD"), gross=Money("10.00", "USD")
)
@@ -215,7 +243,7 @@ def test_calculate_order_line_unit(
site_settings.company_address = address_usa
site_settings.save()
- line_price = interface.calculate_order_line_unit(order_line)
+ line_price = manager.calculate_order_line_unit(order_line)
line_price = quantize_price(line_price, line_price.currency)
assert line_price == TaxedMoney(
net=Money("8.13", "USD"), gross=Money("10.00", "USD")
diff --git a/tests/extensions/plugins/test_vatlayer.py b/tests/extensions/plugins/test_vatlayer.py
index ee69c00571..cdfab75296 100644
--- a/tests/extensions/plugins/test_vatlayer.py
+++ b/tests/extensions/plugins/test_vatlayer.py
@@ -1,4 +1,5 @@
from unittest import mock
+from urllib.parse import urlparse
import pytest
from django.core.exceptions import ImproperlyConfigured
@@ -15,10 +16,17 @@ from saleor.core.extensions.plugins.vatlayer import (
get_taxes_for_address,
get_taxes_for_country,
)
-from saleor.core.utils import get_country_name_by_code
from saleor.dashboard.taxes.filters import get_country_choices_for_vat
-from ..utils import get_redirect_location
+
+def get_url_path(url):
+ parsed_url = urlparse(url)
+ return parsed_url.path
+
+
+def get_redirect_location(response):
+ # Due to Django 1.8 compatibility, we have to handle both cases
+ return get_url_path(response["Location"])
@pytest.fixture
@@ -273,11 +281,6 @@ def test_get_taxes_for_country(vatlayer, compare_taxes):
compare_taxes(taxes, vatlayer)
-def test_get_country_name_by_code():
- country_name = get_country_name_by_code("PL")
- assert country_name == "Poland"
-
-
def test_apply_tax_to_price_do_not_include_tax(site_settings, taxes):
site_settings.include_taxes_in_prices = False
site_settings.save()
diff --git a/tests/taxes/__init__.py b/tests/taxes/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/tests/taxes/test_interface.py b/tests/taxes/test_interface.py
deleted file mode 100644
index 847905a28f..0000000000
--- a/tests/taxes/test_interface.py
+++ /dev/null
@@ -1,140 +0,0 @@
-import pytest
-from django_countries.fields import Country
-from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
-
-from saleor.checkout.utils import add_variant_to_checkout
-from saleor.core.taxes import interface, quantize_price
-from saleor.shipping import ShippingMethodType
-
-
- "with_discount, expected_net, expected_gross",
- [(True, "15.00", "15.00"), (False, "30.00", "30.00")],
-)
-def test_calculate_checkout_line_total(
- with_discount, expected_net, expected_gross, discount_info, checkout_with_item
-):
- line = checkout_with_item.lines.first()
- discounts = [discount_info] if with_discount else None
- total = interface.calculate_checkout_line_total(line, discounts)
- assert total == TaxedMoney(
- net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
- )
-
-
- "with_discount, expected_net, expected_gross, voucher_amount",
- [
- (True, "25.00", "25.00", "0.0"),
- (True, "20.00", "20.00", "5.0"),
- (False, "40.00", "40.00", "0.0"),
- (False, "37.00", "37.00", "3.0"),
- ],
-)
-def test_calculate_checkout_total(
- with_discount,
- expected_net,
- expected_gross,
- voucher_amount,
- checkout_with_item,
- discount_info,
- shipping_zone,
-):
- voucher_amount = Money(voucher_amount, "USD")
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
- checkout_with_item.discount_amount = voucher_amount
- checkout_with_item.save()
- discounts = [discount_info] if with_discount else None
- total = interface.calculate_checkout_total(checkout_with_item, discounts)
- assert total == TaxedMoney(
- net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
- )
-
-
-def test_calculate_checkout_shipping(checkout_with_item, shipping_zone, discount_info):
- checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
- checkout_with_item.save()
- shipping_price = interface.calculate_checkout_shipping(
- checkout_with_item, discount_info
- )
- assert shipping_price == TaxedMoney(
- net=Money("10.00", "USD"), gross=Money("10.00", "USD")
- )
-
-
- "with_discount, expected_net, expected_gross",
- [(True, "25.00", "25.00"), (False, "50.00", "50.00")],
-)
-def test_calculate_checkout_subtotal(
- with_discount,
- expected_net,
- expected_gross,
- discount_info,
- checkout_with_item,
- variant,
-):
- discounts = [discount_info] if with_discount else None
- add_variant_to_checkout(checkout_with_item, variant, 2)
- total = interface.calculate_checkout_subtotal(checkout_with_item, discounts)
-
- assert total == TaxedMoney(
- net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
- )
-
-
-def test_calculate_order_shipping(order, shipping_zone):
- order.shipping_address = order.billing_address.get_copy()
- method = shipping_zone.shipping_methods.get()
- order.shipping_method_name = method.name
- order.shipping_method = method
- order.save()
- price = interface.calculate_order_shipping(order)
- assert price == TaxedMoney(net=Money("10.00", "USD"), gross=Money("10.00", "USD"))
-
-
-def test_calculate_order_line_unit(order_line):
- assert interface.calculate_order_line_unit(order_line) == quantize_price(
- order_line.unit_price, order_line.unit_price.currency
- )
-
-
- "with_discount, expected_net, expected_gross",
- [(True, "5.00", "5.00"), (False, "10.00", "10.00")],
-)
-def test_apply_taxes_to_product(
- with_discount, expected_net, expected_gross, discount_info, variant
-):
- country = Country("PL")
- discounts = [discount_info] if with_discount else None
- price = interface.apply_taxes_to_product(
- variant.product, variant.get_price(discounts), country
- )
- assert price == TaxedMoney(
- net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
- )
-
-
-def test_apply_taxes_to_shipping(shipping_zone, address):
- method = shipping_zone.shipping_methods.get()
- net = method.get_total()
- price = interface.apply_taxes_to_shipping(net, address)
- assert price == TaxedMoney(net=Money("10.00", "USD"), gross=Money("10.00", "USD"))
-
-
-def test_apply_taxes_to_shipping_price_range(shipping_zone, address):
- shipping_zone.shipping_methods.create(
- name="Super_DHL",
- minimum_order_price=Money(0, "USD"),
- type=ShippingMethodType.PRICE_BASED,
- price=Money(20, "USD"),
- shipping_zone=shipping_zone,
- )
- methods = shipping_zone.shipping_methods.all()
- shipping_methods = methods.values_list("price", flat=True)
- prices = MoneyRange(start=min(shipping_methods), stop=max(shipping_methods))
- price_range = interface.apply_taxes_to_shipping_price_range(prices, address)
- start = TaxedMoney(net=Money("10.00", "USD"), gross=Money("10.00", "USD"))
- stop = TaxedMoney(net=Money("20.00", "USD"), gross=Money("20.00", "USD"))
- assert price_range == TaxedMoneyRange(start, stop)
diff --git a/tests/test_cart.py b/tests/test_cart.py
index 1d53db8e6b..cb48bd1202 100644
--- a/tests/test_cart.py
+++ b/tests/test_cart.py
@@ -33,7 +33,7 @@ def checkout_request_factory(rf, monkeypatch):
else:
request.user = user
request.discounts = Sale.objects.all()
- request.taxes = None
+ request.extensions = None
monkeypatch.setattr(request, "get_signed_cookie", Mock(return_value=token))
return request
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index 54c2c956bb..c7798a5e31 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -30,9 +30,8 @@ from saleor.checkout.utils import (
remove_voucher_from_checkout,
)
from saleor.core.exceptions import InsufficientStock
-from saleor.core.extensions.manager import ExtensionsManager
+from saleor.core.extensions.manager import ExtensionsManager, get_extensions_manager
from saleor.core.taxes import zero_money, zero_taxed_money
-from saleor.core.taxes.interface import calculate_checkout_subtotal, taxes_are_enabled
from saleor.discount import DiscountValueType, VoucherType
from saleor.discount.models import NotApplicable, Voucher
from saleor.order import OrderEvents, OrderEventsEmails
@@ -866,7 +865,8 @@ def test_get_voucher_discount_for_checkout_voucher_validation(
mock_validate_voucher, voucher, checkout_with_voucher
):
get_voucher_discount_for_checkout(voucher, checkout_with_voucher)
- subtotal = calculate_checkout_subtotal(checkout_with_voucher, [])
+ manager = get_extensions_manager()
+ subtotal = manager.calculate_checkout_subtotal(checkout_with_voucher, [])
quantity = checkout_with_voucher.quantity
customer_email = checkout_with_voucher.get_customer_email()
mock_validate_voucher.assert_called_once_with(
@@ -1388,9 +1388,10 @@ def test_recalculate_checkout_discount_expired_voucher(checkout_with_voucher, vo
def test_get_checkout_context(checkout_with_voucher):
line_price = TaxedMoney(net=Money("30.00", "USD"), gross=Money("30.00", "USD"))
+ manager = get_extensions_manager()
expected_data = {
"checkout": checkout_with_voucher,
- "checkout_are_taxes_handled": taxes_are_enabled(),
+ "checkout_are_taxes_handled": manager.taxes_are_enabled(),
"checkout_lines": [(checkout_with_voucher.lines.first(), line_price)],
"checkout_shipping_price": zero_taxed_money(),
"checkout_subtotal": line_price,
diff --git a/tests/test_core.py b/tests/test_core.py
index cff38b77d4..8240bdc914 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -20,6 +20,7 @@ from saleor.core.utils import (
create_thumbnails,
format_money,
get_country_by_ip,
+ get_country_name_by_code,
get_currency_for_country,
random_data,
)
@@ -299,3 +300,8 @@ def test_csrf_middleware_is_enabled():
checkout_url = reverse("checkout:index")
response = csrf_client.post(checkout_url)
assert response.status_code == 403
+
+
+def test_get_country_name_by_code():
+ country_name = get_country_name_by_code("PL")
+ assert country_name == "Poland"