Skip to content

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

Reduce Cognitive Complexity for extension module

Maciej Korycinski3d71c02aaada
diff --git a/saleor/core/extensions/base_plugin.py b/saleor/core/extensions/base_plugin.py
index 86fe0d5d25..87bc96efa9 100644
--- a/saleor/core/extensions/base_plugin.py
+++ b/saleor/core/extensions/base_plugin.py
@@ -86,7 +86,6 @@ class BasePlugin:
price: Money,
country: Country,
previous_value: TaxedMoney,
- **kwargs,
) -> TaxedMoney:
return NotImplemented
diff --git a/saleor/core/extensions/manager.py b/saleor/core/extensions/manager.py
index a317916965..67caca35e8 100644
--- a/saleor/core/extensions/manager.py
+++ b/saleor/core/extensions/manager.py
@@ -132,13 +132,13 @@ class ExtensionsManager:
return self.__run_method_on_plugins("taxes_are_enabled", default_value)
def apply_taxes_to_product(
- self, product: "Product", price: Money, country: Country, **kwargs
+ self, product: "Product", price: Money, country: Country
):
default_value = quantize_price(
TaxedMoney(net=price, gross=price), price.currency
)
return self.__run_method_on_plugins(
- "apply_taxes_to_product", default_value, product, price, country, **kwargs
+ "apply_taxes_to_product", default_value, product, price, country
)
def apply_taxes_to_shipping(
diff --git a/saleor/core/extensions/plugins/avatax/__init__.py b/saleor/core/extensions/plugins/avatax/__init__.py
index 3ad11801aa..fe97576bc3 100644
--- a/saleor/core/extensions/plugins/avatax/__init__.py
+++ b/saleor/core/extensions/plugins/avatax/__init__.py
@@ -89,6 +89,18 @@ def api_get_request(
return response.json()
+def _validate_adddress_details(
+ shipping_address, is_shipping_required, address, shipping_method
+):
+ if not is_shipping_required and not address:
+ return False
+ if not shipping_address:
+ return False
+ if not shipping_method:
+ return False
+ return True
+
+
def _validate_order(order: "Order") -> bool:
"""Validate if order object contains enough information to generate a request to
avatax"""
@@ -97,14 +109,9 @@ def _validate_order(order: "Order") -> bool:
shipping_address = order.shipping_address
is_shipping_required = order.is_shipping_required()
address = shipping_address or order.billing_address
-
- if not is_shipping_required and not address:
- return False
- if not shipping_address:
- return False
- if not order.shipping_method:
- return False
- return True
+ return _validate_adddress_details(
+ shipping_address, is_shipping_required, address, order.shipping_method
+ )
def _validate_checkout(checkout: "Checkout") -> bool:
@@ -116,13 +123,9 @@ def _validate_checkout(checkout: "Checkout") -> bool:
shipping_address = checkout.shipping_address
is_shipping_required = checkout.is_shipping_required
address = shipping_address or checkout.billing_address
- if not is_shipping_required and not address:
- return False
- if not shipping_address:
- return False
- if not checkout.shipping_method:
- return False
- return True
+ return _validate_adddress_details(
+ shipping_address, is_shipping_required, address, checkout.shipping_method
+ )
def _retrieve_from_cache(token):
@@ -183,6 +186,20 @@ def append_line_to_data(
)
+def append_shipping_to_data(data: List[Dict], shipping_method):
+ charge_taxes_on_shipping = (
+ Site.objects.get_current().settings.charge_taxes_on_shipping
+ )
+ if charge_taxes_on_shipping and shipping_method:
+ append_line_to_data(
+ data,
+ quantity=1,
+ amount=str(shipping_method.price.amount),
+ tax_code=COMMON_CARRIER_CODE,
+ item_code="Shipping",
+ )
+
+
def get_checkout_lines_data(
checkout: "Checkout", discounts=None
) -> List[Dict[str, str]]:
@@ -209,17 +226,7 @@ def get_checkout_lines_data(
description=description,
)
- charge_taxes_on_shipping = (
- Site.objects.get_current().settings.charge_taxes_on_shipping
- )
- if charge_taxes_on_shipping and checkout.shipping_method:
- append_line_to_data(
- data,
- quantity=1,
- amount=str(checkout.shipping_method.price.amount),
- tax_code=COMMON_CARRIER_CODE,
- item_code="Shipping",
- )
+ append_shipping_to_data(data, checkout.shipping_method)
return data
@@ -255,17 +262,7 @@ def get_order_lines_data(order: "Order") -> List[Dict[str, str]]:
description=order.discount_name,
tax_included=True, # Voucher should be always applied as a gross amount
)
- charge_taxes_on_shipping = (
- Site.objects.get_current().settings.charge_taxes_on_shipping
- )
- if charge_taxes_on_shipping and order.shipping_method:
- append_line_to_data(
- data,
- quantity=1,
- amount=order.shipping_method.price.amount,
- tax_code=COMMON_CARRIER_CODE,
- item_code="Shipping",
- )
+ append_shipping_to_data(data, order.shipping_method)
return data
@@ -347,18 +344,23 @@ def generate_request_data_from_checkout(
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)
+ if response and "error" not in response:
+ cache.set(data_cache_key, (data, response), CACHE_TIME)
+ else:
+ # cache failed response to limit hits to avatax.
+ cache.set(data_cache_key, (data, response), 10)
+ return response
+
+
def get_cached_response_or_fetch(data, token_in_cache, force_refresh=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_cache
if taxes_need_new_fetch(data, token_in_cache) or force_refresh:
- transaction_url = urljoin(get_api_url(), "transactions/createoradjust")
- response = api_post_request(transaction_url, data)
- if response and "error" not in response:
- cache.set(data_cache_key, (data, response), CACHE_TIME)
- else:
- # cache failed response to limit hits to avatax.
- cache.set(data_cache_key, (data, response), 10)
+ response = _fetch_new_taxes_data(data, data_cache_key)
else:
_, response = cache.get(data_cache_key)
diff --git a/saleor/core/extensions/plugins/avatax/plugin.py b/saleor/core/extensions/plugins/avatax/plugin.py
index 48069592fb..1f1ce70ede 100644
--- a/saleor/core/extensions/plugins/avatax/plugin.py
+++ b/saleor/core/extensions/plugins/avatax/plugin.py
@@ -1,6 +1,6 @@
import logging
from decimal import Decimal
-from typing import TYPE_CHECKING, Any, List, Union
+from typing import TYPE_CHECKING, Any, Dict, List, Union
from urllib.parse import urljoin
from django.conf import settings
@@ -80,6 +80,20 @@ class AvataxPlugin(BasePlugin):
total -= voucher_amount
return max(total, zero_taxed_money(total.currency))
+ def _calculate_checkout_subtotal(
+ self, currency: str, lines: List[Dict]
+ ) -> TaxedMoney:
+ sub_tax = Decimal(0.0)
+ sub_net = Decimal(0.0)
+ for line in 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_subtotal(
self,
checkout: "Checkout",
@@ -99,17 +113,22 @@ class AvataxPlugin(BasePlugin):
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", []):
+ return self._calculate_checkout_subtotal(currency, response.get("lines", []))
+
+ def _calculate_checkout_shipping(
+ self, currency: str, lines: List[Dict], shipping_price: Money
+ ) -> TaxedMoney:
+ shipping_tax = Decimal(0.0)
+ shipping_net = shipping_price.amount
+ for line in lines:
if line["itemCode"] == "Shipping":
- continue
- sub_tax += Decimal(line["tax"])
- sub_net += Decimal(line.get("lineAmount", 0.0))
+ shipping_net = Decimal(line["lineAmount"])
+ shipping_tax = Decimal(line["tax"])
+ break
- 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)
+ 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 calculate_checkout_shipping(
self,
@@ -128,18 +147,10 @@ class AvataxPlugin(BasePlugin):
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)
+ return self._calculate_checkout_shipping(
+ currency, response.get("lines", []), shipping_price
+ )
def preprocess_order_creation(
self, checkout: "Checkout", discounts: List["DiscountInfo"], previous_value: Any
@@ -205,24 +216,27 @@ class AvataxPlugin(BasePlugin):
total = checkout_line.get_total(discounts)
return TaxedMoney(net=total, gross=total)
+ def _calculate_order_line_unit(self, order_line):
+ order = order_line.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)
+
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)
+ if _validate_order(order_line.order):
+ return self._calculate_order_line_unit(order_line)
return order_line.unit_price
def calculate_order_shipping(
diff --git a/saleor/core/extensions/plugins/vatlayer/__init__.py b/saleor/core/extensions/plugins/vatlayer/__init__.py
index 985709bbcf..b232ba816d 100644
--- a/saleor/core/extensions/plugins/vatlayer/__init__.py
+++ b/saleor/core/extensions/plugins/vatlayer/__init__.py
@@ -76,20 +76,24 @@ class TaxRateType:
DEFAULT_TAX_RATE_NAME = TaxRateType.STANDARD
+def _convert_to_naive_taxed_money(base, taxes, rate_name):
+ """Naively convert Money to TaxedMoney for consistency with price
+ handling logic across the codebase, passthrough other money types"""
+ if isinstance(base, Money):
+ return TaxedMoney(net=base, gross=base)
+ if isinstance(base, MoneyRange):
+ return TaxedMoneyRange(
+ apply_tax_to_price(taxes, rate_name, base.start),
+ apply_tax_to_price(taxes, rate_name, base.stop),
+ )
+ if isinstance(base, (TaxedMoney, TaxedMoneyRange)):
+ return base
+ raise TypeError("Unknown base for flat_tax: %r" % (base,))
+
+
def apply_tax_to_price(taxes, rate_name, base):
if not taxes or not rate_name:
- # Naively convert Money to TaxedMoney for consistency with price
- # handling logic across the codebase, passthrough other money types
- if isinstance(base, Money):
- return TaxedMoney(net=base, gross=base)
- if isinstance(base, MoneyRange):
- return TaxedMoneyRange(
- apply_tax_to_price(taxes, rate_name, base.start),
- apply_tax_to_price(taxes, rate_name, base.stop),
- )
- if isinstance(base, (TaxedMoney, TaxedMoneyRange)):
- return base
- raise TypeError("Unknown base for flat_tax: %r" % (base,))
+ return _convert_to_naive_taxed_money(base, taxes, rate_name)
if rate_name in taxes:
tax_to_apply = taxes[rate_name]["tax"]
diff --git a/saleor/core/extensions/plugins/vatlayer/plugin.py b/saleor/core/extensions/plugins/vatlayer/plugin.py
index cd30b5859d..9342a36705 100644
--- a/saleor/core/extensions/plugins/vatlayer/plugin.py
+++ b/saleor/core/extensions/plugins/vatlayer/plugin.py
@@ -212,7 +212,6 @@ class VatlayerPlugin(BasePlugin):
price: Money,
country: Country,
previous_value: TaxedMoney,
- **kwargs,
) -> TaxedMoney:
if self._skip_plugin(previous_value):
return previous_value