Skip to content

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

Merge branch 'master' into enable_extension_manager_for_taxes

Maciej Korycinskifa8b5fb2bace
diff --cc saleor/core/extensions/plugins/avatax/__init__.py
index be130fc0e8,a2a9edc0f4..3ad11801aa
--- a/saleor/core/extensions/plugins/avatax/__init__.py
+++ b/saleor/core/extensions/plugins/avatax/__init__.py
@@@ -18,6 -21,6 +18,7 @@@ if TYPE_CHECKING
logger = logging.getLogger(__name__)
META_FIELD = "avatax"
++META_NAMESPACE = "taxes"
CACHE_TIME = 60 * 60 # 1 hour
TAX_CODES_CACHE_TIME = 60 * 60 * 24 * 7 # 7 days
CACHE_KEY = "avatax_request_id_"
diff --cc saleor/core/extensions/plugins/avatax/plugin.py
index bbda77161b,0000000000..a24eda05f2
mode 100644,000000..100644
--- a/saleor/core/extensions/plugins/avatax/plugin.py
+++ b/saleor/core/extensions/plugins/avatax/plugin.py
@@@ -1,292 -1,0 +1,292 @@@
+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 ....taxes import TaxError, TaxType, zero_taxed_money
+from ...plugin import BasePlugin
+from . import (
+ META_FIELD,
++ META_NAMESPACE,
+ 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,
+)
+from .tasks import api_post_request_task
+
+if TYPE_CHECKING:
+ from .....checkout.models import Checkout, CheckoutLine
+ 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",
+ 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",
+ 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",
+ 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):
+ 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_task.delay(transaction_url, data)
+
+ def calculate_checkout_line_total(
+ self,
+ checkout_line: "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,
- }
++ tax_item = {"code": tax_code, "description": tax_description}
++ stored_tax_meta = obj.get_meta(namespace=META_NAMESPACE, client=META_FIELD)
++ stored_tax_meta.update(tax_item)
++ obj.store_meta(
++ namespace=META_NAMESPACE, client=META_FIELD, item=stored_tax_meta
++ )
++ obj.save()
+
+ 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, {})
++ tax = 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:
+ return previous_value
+ return False
+
+ def taxes_are_enabled(self, previous_value: bool) -> bool:
+ if not self._enabled:
+ return previous_value
+ return True
diff --cc saleor/core/extensions/plugins/vatlayer/plugin.py
index 32a2e5fb4c,0000000000..ff43a6b18c
mode 100644,000000..100644
--- a/saleor/core/extensions/plugins/vatlayer/plugin.py
+++ b/saleor/core/extensions/plugins/vatlayer/plugin.py
@@@ -1,259 -1,0 +1,266 @@@
+from typing import TYPE_CHECKING, Any, List, Union
+
+from django.conf import settings
+from django_countries.fields import Country
+from django_prices_vatlayer.utils import get_tax_rate_types
+from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
+
+from ....taxes import TaxType
+from ...plugin import BasePlugin
+from . import (
+ DEFAULT_TAX_RATE_NAME,
+ TaxRateType,
+ apply_tax_to_price,
+ get_taxed_shipping_price,
+ get_taxes_for_country,
+)
+
+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
+
+
+class VatlayerPlugin(BasePlugin):
+ META_FIELD = "vatlayer"
++ META_NAMESPACE = "taxes"
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._enabled = bool(settings.VATLAYER_ACCESS_KEY)
+ self._cached_taxes = {}
+
+ 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",
+ discounts: List["DiscountInfo"],
+ previous_value: TaxedMoney,
+ ) -> TaxedMoney:
+
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ zero_total = Money(0, currency=previous_value.currency)
+ taxed_zero = TaxedMoney(zero_total, zero_total)
+
+ return (
+ self.calculate_checkout_subtotal(checkout, discounts, previous_value)
+ + self.calculate_checkout_shipping(checkout, discounts, taxed_zero)
+ - checkout.discount_amount
+ )
+
+ def calculate_checkout_subtotal(
+ self,
+ checkout: "Checkout",
+ discounts: List["DiscountInfo"],
+ previous_value: TaxedMoney,
+ ) -> TaxedMoney:
+ """Calculate subtotal gross for checkout"""
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ address = checkout.shipping_address or checkout.billing_address
+ lines = checkout.lines.prefetch_related("variant__product__product_type")
+ zero_total = Money(0, currency=previous_value.currency)
+
+ lines_total = TaxedMoney(net=zero_total, gross=zero_total)
+ for line in lines:
+ price = line.variant.get_price(discounts)
+ lines_total += line.quantity * self.__apply_taxes_to_product(
+ line.variant.product, price, address.country if address else None
+ )
+ return lines_total
+
+ def _get_taxes_for_country(self, country: Country):
+ """Tries to fetch cached taxes on the plugin level. If the plugin doesn't have
+ cached taxes for a given country it will fetch it from cache or db"""
+ if not country:
+ country = Country(settings.DEFAULT_COUNTRY)
+ country_code = country.code
+ if country_code in self._cached_taxes:
+ return self._cached_taxes[country_code]
+ taxes = get_taxes_for_country(country)
+ self._cached_taxes[country_code] = taxes
+ return taxes
+
+ def calculate_checkout_shipping(
+ self,
+ checkout: "Checkout",
+ discounts: List["DiscountInfo"],
+ previous_value: TaxedMoney,
+ ) -> TaxedMoney:
+ """Calculate shipping gross for checkout"""
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ address = checkout.shipping_address or checkout.billing_address
+ taxes = None
+ if address:
+ taxes = self._get_taxes_for_country(address.country)
+ if not checkout.shipping_method:
+ return previous_value
+
+ return get_taxed_shipping_price(checkout.shipping_method.price, taxes)
+
+ def calculate_order_shipping(
+ self, order: "Order", previous_value: TaxedMoney
+ ) -> TaxedMoney:
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ address = order.shipping_address or order.billing_address
+ taxes = None
+ if address:
+ taxes = self._get_taxes_for_country(address.country)
+ if not order.shipping_method:
+ return previous_value
+ return get_taxed_shipping_price(order.shipping_method.price, taxes)
+
+ def calculate_checkout_line_total(
+ self,
+ checkout_line: "CheckoutLine",
+ discounts: List["DiscountInfo"],
+ previous_value: TaxedMoney,
+ ) -> TaxedMoney:
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ address = (
+ checkout_line.checkout.shipping_address
+ or checkout_line.checkout.billing_address
+ )
+ price = checkout_line.variant.get_price(discounts) * checkout_line.quantity
+ country = address.country if address else None
+ return self.__apply_taxes_to_product(
+ checkout_line.variant.product, price, country
+ )
+
+ def calculate_order_line_unit(
+ self, order_line: "OrderLine", previous_value: TaxedMoney
+ ) -> TaxedMoney:
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ address = order_line.order.shipping_address or order_line.order.billing_address
+ country = address.country if address else None
+ variant = order_line.variant
+ return self.__apply_taxes_to_product(
+ variant.product, order_line.unit_price_net, country
+ )
+
+ def get_tax_rate_type_choices(
+ self, previous_value: List["TaxType"]
+ ) -> List["TaxType"]:
+ if not self._enabled:
+ return previous_value
+
+ rate_types = get_tax_rate_types() + [DEFAULT_TAX_RATE_NAME]
+ choices = [
+ TaxType(code=rate_name, description=rate_name) for rate_name in rate_types
+ ]
+ # sort choices alphabetically by translations
+ return sorted(choices, key=lambda x: x.code)
+
+ def show_taxes_on_storefront(self, previous_value: bool) -> bool:
+ if not self._enabled:
+ return previous_value
+ return True
+
+ def taxes_are_enabled(self, previous_value: bool) -> bool:
+ if not self._enabled:
+ return previous_value
+ return True
+
+ def apply_taxes_to_shipping_price_range(
+ self, prices: MoneyRange, country: Country, previous_value: TaxedMoneyRange
+ ) -> TaxedMoneyRange:
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ taxes = self._get_taxes_for_country(country)
+ return get_taxed_shipping_price(prices, taxes)
+
+ def apply_taxes_to_shipping(
+ self, price: Money, shipping_address: "Address", previous_value: TaxedMoney
+ ) -> TaxedMoney:
+ if self._skip_plugin(previous_value):
+ return previous_value
+
+ taxes = self._get_taxes_for_country(shipping_address.country)
+ return get_taxed_shipping_price(price, taxes)
+
+ def apply_taxes_to_product(
+ self,
+ product: "Product",
+ price: Money,
+ country: Country,
+ previous_value: TaxedMoney,
+ **kwargs,
+ ) -> TaxedMoney:
+ if self._skip_plugin(previous_value):
+ return previous_value
+ return self.__apply_taxes_to_product(product, price, country)
+
+ def __apply_taxes_to_product(
+ self, product: "Product", price: Money, country: Country
+ ):
+ taxes = None
+ if country and product.charge_taxes:
+ taxes = self._get_taxes_for_country(country)
+
+ product_tax_rate = self.__get_tax_code_from_object_meta(product).code
+ tax_rate = (
+ product_tax_rate
+ or self.__get_tax_code_from_object_meta(product.product_type).code
+ )
+ return apply_tax_to_price(taxes, tax_rate, price)
+
+ 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
+
+ if tax_code not in dict(TaxRateType.CHOICES):
+ return previous_value
+
- if "taxes" not in obj.meta:
- obj.meta["taxes"] = {}
- obj.meta["taxes"][self.META_FIELD] = {"code": tax_code, "description": tax_code}
++ tax_item = {"code": tax_code, "description": tax_code}
++ stored_tax_meta = obj.get_meta(
++ namespace=self.META_NAMESPACE, client=self.META_FIELD
++ )
++ stored_tax_meta.update(tax_item)
++ obj.store_meta(
++ namespace=self.META_NAMESPACE, client=self.META_FIELD, item=stored_tax_meta
++ )
++ obj.save()
+ return previous_value
+
+ def get_tax_code_from_object_meta(
+ self, obj: Union["Product", "ProductType"], previous_value: "TaxType"
+ ) -> "TaxType":
+ if not self._enabled:
+ return previous_value
+ return self.__get_tax_code_from_object_meta(obj)
+
+ def __get_tax_code_from_object_meta(
+ self, obj: Union["Product", "ProductType"]
+ ) -> "TaxType":
- tax = obj.meta.get("taxes", {}).get(self.META_FIELD, {})
++ tax = obj.get_meta(namespace=self.META_NAMESPACE, client=self.META_FIELD)
+ return TaxType(code=tax.get("code", ""), description=tax.get("description", ""))
diff --cc saleor/graphql/checkout/types.py
index 67ffea8ab0,4b66065f3a..fa9b3355e9
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@@ -5,7 -6,15 +6,9 @@@ from graphql_jwt.decorators import perm
from ...checkout import models
from ...checkout.utils import get_valid_shipping_methods_for_checkout
from ...core.taxes import zero_taxed_money
-from ...core.taxes.interface import (
- calculate_checkout_line_total,
- calculate_checkout_shipping,
- calculate_checkout_subtotal,
- calculate_checkout_total,
-)
from ..core.connection import CountableDjangoObjectType
+ from ..core.resolvers import resolve_meta, resolve_private_meta
+ from ..core.types.meta import MetadataObjectType
from ..core.types.money import TaxedMoney
from ..giftcard.types import GiftCard
from ..payment.enums import PaymentGatewayEnum