Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Move Vatlayer to plugin
Maciej Korycinski7f0aed06e794
diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.pyindex e6404a5495..4e86f992c1 100644--- a/saleor/checkout/forms.py+++ b/saleor/checkout/forms.py@@ -11,8 +11,8 @@ from django.utils.translation import npgettext_lazy, pgettext_lazyfrom django_countries.fields import Country, LazyTypedChoiceFieldfrom ..core.exceptions import InsufficientStock+from ..core.extensions.manager import get_extensions_managerfrom ..core.taxes import display_gross_prices-from ..core.taxes.interface import apply_taxes_to_shipping, calculate_checkout_subtotalfrom ..core.utils import format_moneyfrom ..discount.models import NotApplicable, Voucherfrom ..shipping.models import ShippingMethod, ShippingZone@@ -71,7 +71,7 @@ class AddToCheckoutForm(forms.Form):self.product = kwargs.pop("product")self.discounts = kwargs.pop("discounts", ())self.country = kwargs.pop("country", {})- self.taxes = kwargs.pop("taxes", None)+ self.extensions = kwargs.pop("extensions", None)super().__init__(*args, **kwargs)def add_error_i18n(self, field, error_name, fmt: Any = tuple()):@@ -293,12 +293,13 @@ class ShippingMethodChoiceField(forms.ModelChoiceField):"""shipping_address = None+ extensions = Nonewidget = forms.RadioSelect()def label_from_instance(self, obj):"""Return a friendly label for the shipping method."""if display_gross_prices():- price = apply_taxes_to_shipping(+ price = self.extensions.apply_taxes_to_shipping(obj.price, shipping_address=self.shipping_address).grosselse:@@ -321,16 +322,20 @@ class CheckoutShippingMethodForm(forms.ModelForm):def __init__(self, *args, **kwargs):discounts = kwargs.pop("discounts")+ extensions = get_extensions_manager()super().__init__(*args, **kwargs)shipping_address = self.instance.shipping_addresscountry_code = shipping_address.country.codeqs = ShippingMethod.objects.applicable_shipping_methods(- price=calculate_checkout_subtotal(self.instance, discounts).gross,+ price=extensions.calculate_checkout_subtotal(+ self.instance, discounts+ ).gross,weight=self.instance.get_total_weight(),country_code=country_code,)self.fields["shipping_method"].queryset = qsself.fields["shipping_method"].shipping_address = shipping_address+ self.fields["shipping_method"].extensions = extensionsif self.initial.get("shipping_method") is None:shipping_methods = qs.all()diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex e0b5502071..dff1b26823 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -16,16 +16,8 @@ from ..account.forms import get_address_formfrom ..account.models import Address, Userfrom ..account.utils import store_user_addressfrom ..core.exceptions import InsufficientStock+from ..core.extensions.manager import get_extensions_managerfrom ..core.taxes import quantize_price, zero_money, zero_taxed_money-from ..core.taxes.interface import (- calculate_checkout_line_total,- calculate_checkout_shipping,- calculate_checkout_subtotal,- calculate_checkout_total,- postprocess_order_creation,- preprocess_order_creation,- taxes_are_enabled,-)from ..core.utils import to_local_currencyfrom ..core.utils.promo_code import (InvalidPromoCode,@@ -131,8 +123,9 @@ def get_prices_of_discounted_specific_product(lines, voucher, discounts=None):# it means that all products are discounteddiscounted_lines.extend(list(lines))+ manager = get_extensions_manager()for line in discounted_lines:- line_total = calculate_checkout_line_total(line, discounts or []).gross+ line_total = manager.calculate_checkout_line_total(line, discounts or []).grossline_unit_price = quantize_price((line_total / line.quantity), line_total.currency)@@ -147,9 +140,12 @@ def get_prices_of_discounted_products(checkout, discounted_products, discounts=N# it means that all products are discountedline_prices = []if discounted_products:+ manager = get_extensions_manager()for line in checkout:if line.variant.product in discounted_products:- line_total = calculate_checkout_line_total(line, discounts or []).gross+ line_total = manager.calculate_checkout_line_total(+ line, discounts or []+ ).grossline_unit_price = quantize_price((line_total / line.quantity), line_total.currency)@@ -165,12 +161,15 @@ def get_prices_of_products_in_discounted_collections(# it means that all of them are discountedline_prices = []if discounted_collections:+ manager = get_extensions_manager()for line in checkout:if not line.variant:continueproduct_collections = line.variant.product.collections.all()if set(product_collections).intersection(discounted_collections):- line_total = calculate_checkout_line_total(line, discounts or []).gross+ line_total = manager.calculate_checkout_line_total(+ line, discounts or []+ ).grossline_unit_price = quantize_price((line_total / line.quantity), line_total.currency)@@ -194,9 +193,12 @@ def get_prices_of_products_in_discounted_categories(for line in checkout:if not line.variant:continue+ manager = get_extensions_manager()product_category = line.variant.product.categoryif product_category in discounted_categories:- line_total = calculate_checkout_line_total(line, discounts or []).gross+ line_total = manager.calculate_checkout_line_total(+ line, discounts or []+ ).grossline_unit_price = quantize_price((line_total / line.quantity), line_total.currency)@@ -708,13 +710,14 @@ def change_shipping_address_in_checkout(checkout, address):def get_checkout_context(checkout, discounts, currency=None, shipping_range=None):"""Data shared between views in checkout process."""+ manager = get_extensions_manager()checkout_total = (- calculate_checkout_total(checkout=checkout, discounts=discounts)+ manager.calculate_checkout_total(checkout=checkout, discounts=discounts)- checkout.get_total_gift_cards_balance())checkout_total = max(checkout_total, zero_taxed_money(checkout_total.currency))- checkout_subtotal = calculate_checkout_subtotal(checkout, discounts)- shipping_price = calculate_checkout_shipping(checkout, discounts)+ checkout_subtotal = manager.calculate_checkout_subtotal(checkout, discounts)+ shipping_price = manager.calculate_checkout_shipping(checkout, discounts)shipping_required = checkout.is_shipping_required()total_with_shipping = TaxedMoneyRange(@@ -725,9 +728,10 @@ def get_checkout_context(checkout, discounts, currency=None, shipping_range=Nonecontext = {"checkout": checkout,- "checkout_are_taxes_handled": taxes_are_enabled(),+ "checkout_are_taxes_handled": manager.taxes_are_enabled(),"checkout_lines": [- (line, calculate_checkout_line_total(line, discounts)) for line in checkout+ (line, manager.calculate_checkout_line_total(line, discounts))+ for line in checkout],"checkout_shipping_price": shipping_price,"checkout_subtotal": checkout_subtotal,@@ -768,7 +772,8 @@ def _get_shipping_voucher_discount_for_checkout(voucher, checkout, discounts=Non)raise NotApplicable(msg)- shipping_price = calculate_checkout_shipping(checkout, discounts).gross+ manager = get_extensions_manager()+ shipping_price = manager.calculate_checkout_shipping(checkout, discounts).grossreturn voucher.get_discount_amount_for(shipping_price)@@ -805,7 +810,8 @@ def get_voucher_discount_for_checkout(voucher, checkout, discounts=None):"""validate_voucher_for_checkout(voucher, checkout, discounts)if voucher.type == VoucherType.ENTIRE_ORDER:- subtotal = calculate_checkout_subtotal(checkout, discounts).gross+ manager = get_extensions_manager()+ subtotal = manager.calculate_checkout_subtotal(checkout, discounts).grossreturn voucher.get_discount_amount_for(subtotal)if voucher.type == VoucherType.SHIPPING:return _get_shipping_voucher_discount_for_checkout(voucher, checkout, discounts)@@ -847,7 +853,8 @@ def recalculate_checkout_discount(checkout, discounts):except NotApplicable:remove_voucher_from_checkout(checkout)else:- subtotal = calculate_checkout_subtotal(checkout, discounts).gross+ manager = get_extensions_manager()+ subtotal = manager.calculate_checkout_subtotal(checkout, discounts).grosscheckout.discount_amount = min(discount, subtotal)checkout.discount_name = str(voucher)checkout.translated_discount_name = (@@ -954,8 +961,9 @@ def is_valid_shipping_method(checkout, discounts):if not checkout.shipping_method:return False+ manager = get_extensions_manager()valid_methods = ShippingMethod.objects.applicable_shipping_methods(- price=calculate_checkout_subtotal(checkout, discounts).gross,+ price=manager.calculate_checkout_subtotal(checkout, discounts).gross,weight=checkout.get_total_weight(),country_code=checkout.shipping_address.country.code,)@@ -1067,7 +1075,8 @@ def create_line_for_order(checkout_line: "CheckoutLine", discounts) -> OrderLineif translated_product_name == product_name:translated_product_name = ""- total_line_price = calculate_checkout_line_total(checkout_line, discounts)+ manager = get_extensions_manager()+ total_line_price = manager.calculate_checkout_line_total(checkout_line, discounts)unit_price = quantize_price(total_line_price / checkout_line.quantity, total_line_price.currency)@@ -1093,13 +1102,14 @@ def prepare_order_data(*, checkout: Checkout, tracking_code: str, discounts) ->"""order_data = {}+ manager = get_extensions_manager()total = (- calculate_checkout_total(checkout=checkout, discounts=discounts)+ manager.calculate_checkout_total(checkout=checkout, discounts=discounts)- checkout.get_total_gift_cards_balance())total = max(total, zero_taxed_money(total.currency))- shipping_total = calculate_checkout_shipping(checkout, discounts)+ shipping_total = manager.calculate_checkout_shipping(checkout, discounts)order_data.update(_process_shipping_data_for_order(checkout, shipping_total))order_data.update(_process_user_data_for_order(checkout))order_data.update(@@ -1123,12 +1133,12 @@ def prepare_order_data(*, checkout: Checkout, tracking_code: str, discounts) -># assign gift cards to the orderorder_data["total_price_left"] = (- calculate_checkout_subtotal(checkout, discounts)+ manager.calculate_checkout_subtotal(checkout, discounts)+ shipping_total- checkout.discount_amount).gross- preprocess_order_creation(checkout, discounts)+ manager.preprocess_order_creation(checkout, discounts)return order_data@@ -1179,7 +1189,8 @@ def create_order(*, checkout: Checkout, order_data: dict, user: User) -> Order:# assign checkout payments to the ordercheckout.payments.update(order=order)- postprocess_order_creation(order)+ manager = get_extensions_manager()+ manager.postprocess_order_creation(order)# Create the order placedevents.order_created_event(order=order, user=user)@@ -1194,8 +1205,9 @@ def is_fully_paid(checkout: Checkout, discounts):Note that these payments may not be captured or charged at all."""payments = [payment for payment in checkout.payments.all() if payment.is_active]total_paid = sum([p.total for p in payments])+ manager = get_extensions_manager()checkout_total = (- calculate_checkout_total(checkout=checkout, discounts=discounts)+ manager.calculate_checkout_total(checkout=checkout, discounts=discounts)- checkout.get_total_gift_cards_balance())checkout_total = max(diff --git a/saleor/checkout/views/__init__.py b/saleor/checkout/views/__init__.pyindex 3cdfc250ad..1862adf128 100644--- a/saleor/checkout/views/__init__.py+++ b/saleor/checkout/views/__init__.py@@ -5,12 +5,7 @@ from django.shortcuts import get_object_or_404, redirect, renderfrom django.template.response import TemplateResponsefrom ...account.forms import LoginForm-from ...core.taxes import (- get_display_price,- interface as tax_interface,- quantize_price,- zero_taxed_money,-)+from ...core.taxes import get_display_price, quantize_price, zero_taxed_moneyfrom ...core.utils import format_money, get_user_shipping_country, to_local_currencyfrom ...shipping.utils import get_shipping_price_estimatefrom ..forms import CheckoutShippingMethodForm, CountryForm, ReplaceCheckoutLineForm@@ -132,6 +127,7 @@ def checkout_index(request, checkout):"variant__images","variant__product__product_type__variant_attributes",)+ manager = request.extensionsfor line in lines:initial = {"quantity": line.quantity}form = ReplaceCheckoutLineForm(@@ -141,7 +137,7 @@ def checkout_index(request, checkout):initial=initial,discounts=discounts,)- total_line = tax_interface.calculate_checkout_line_total(line, discounts)+ total_line = manager.calculate_checkout_line_total(line, discounts)variant_price = quantize_price(total_line / line.quantity, total_line.currency)checkout_lines.append({@@ -155,7 +151,7 @@ def checkout_index(request, checkout):default_country = get_user_shipping_country(request)country_form = CountryForm(initial={"country": default_country})shipping_price_range = get_shipping_price_estimate(- price=tax_interface.calculate_checkout_subtotal(checkout, discounts).gross,+ price=manager.calculate_checkout_subtotal(checkout, discounts).gross,weight=checkout.get_total_weight(),country_code=default_country,)@@ -179,10 +175,11 @@ def checkout_index(request, checkout):@get_or_empty_db_checkout(checkout_queryset=Checkout.objects.for_display())def checkout_shipping_options(request, checkout):"""Display shipping options to get a price estimate."""+ manager = request.extensionscountry_form = CountryForm(request.POST or None)if country_form.is_valid():shipping_price_range = country_form.get_shipping_price_estimate(- price=tax_interface.calculate_checkout_subtotal(+ price=manager.calculate_checkout_subtotal(checkout, request.discounts).gross,weight=checkout.get_total_weight(),@@ -215,6 +212,7 @@ def update_checkout_line(request, checkout, variant_id):variant=checkout_line.variant,discounts=discounts,)+ manager = request.extensionsif form.is_valid():form.save()checkout.refresh_from_db()@@ -222,9 +220,7 @@ def update_checkout_line(request, checkout, variant_id):checkout_line = checkout.lines.filter(variant_id=variant_id).first()line_total = zero_taxed_money(currency=settings.DEFAULT_CURRENCY)if checkout_line:- line_total = tax_interface.calculate_checkout_line_total(- checkout_line, discounts- )+ line_total = manager.calculate_checkout_line_total(checkout_line, discounts)subtotal = get_display_price(line_total)response = {"variantId": variant_id,@@ -233,7 +229,7 @@ def update_checkout_line(request, checkout, variant_id):"checkout": {"numItems": checkout.quantity, "numLines": len(checkout)},}- checkout_total = tax_interface.calculate_checkout_subtotal(checkout, discounts)+ checkout_total = manager.calculate_checkout_subtotal(checkout, discounts)checkout_total = get_display_price(checkout_total)response["total"] = format_money(checkout_total)local_checkout_total = to_local_currency(checkout_total, request.currency)@@ -262,6 +258,7 @@ def clear_checkout(request, checkout):def checkout_dropdown(request, checkout):"""Display a checkout summary suitable for displaying on all pages."""discounts = request.discounts+ manager = request.extensionsdef prepare_line_data(line):first_image = line.variant.get_first_image()@@ -272,7 +269,7 @@ def checkout_dropdown(request, checkout):"variant": line.variant,"quantity": line.quantity,"image": first_image,- "line_total": tax_interface.calculate_checkout_line_total(line, discounts),+ "line_total": manager.calculate_checkout_line_total(line, discounts),"variant_url": line.variant.get_absolute_url(),}@@ -281,7 +278,7 @@ def checkout_dropdown(request, checkout):else:data = {"quantity": checkout.quantity,- "total": tax_interface.calculate_checkout_subtotal(checkout, discounts),+ "total": manager.calculate_checkout_subtotal(checkout, discounts),"lines": [prepare_line_data(line) for line in checkout],}diff --git a/saleor/core/extensions/plugins/__init__.py b/saleor/core/extensions/plugins/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/core/extensions/plugins/vatlayer/__init__.py b/saleor/core/extensions/plugins/vatlayer/__init__.pynew file mode 100644index 0000000000..03b6ac994e--- /dev/null+++ b/saleor/core/extensions/plugins/vatlayer/__init__.py@@ -0,0 +1,155 @@+from django.conf import settings+from django.utils.translation import pgettext_lazy+from django_countries.fields import Country+from django_prices_vatlayer.utils import get_tax_for_rate, get_tax_rates_for_country+from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange++from ....taxes import charge_taxes_on_shipping, include_taxes_in_prices+++class TaxRateType:+ ACCOMMODATION = "accommodation"+ ADMISSION_TO_CULTURAL_EVENTS = "admission to cultural events"+ ADMISSION_TO_ENTERTAINMENT_EVENTS = "admission to entertainment events"+ ADMISSION_TO_SPORTING_EVENTS = "admission to sporting events"+ ADVERTISING = "advertising"+ AGRICULTURAL_SUPPLIES = "agricultural supplies"+ BABY_FOODSTUFFS = "baby foodstuffs"+ BIKES = "bikes"+ BOOKS = "books"+ CHILDRENDS_CLOTHING = "childrens clothing"+ DOMESTIC_FUEL = "domestic fuel"+ DOMESTIC_SERVICES = "domestic services"+ E_BOOKS = "e-books"+ FOODSTUFFS = "foodstuffs"+ HOTELS = "hotels"+ MEDICAL = "medical"+ NEWSPAPERS = "newspapers"+ PASSENGER_TRANSPORT = "passenger transport"+ PHARMACEUTICALS = "pharmaceuticals"+ PROPERTY_RENOVATIONS = "property renovations"+ RESTAURANTS = "restaurants"+ SOCIAL_HOUSING = "social housing"+ STANDARD = "standard"+ WATER = "water"+ WINE = "wine"++ CHOICES = (+ (ACCOMMODATION, pgettext_lazy("VAT rate type", "accommodation")),+ (+ ADMISSION_TO_CULTURAL_EVENTS,+ pgettext_lazy("VAT rate type", "admission to cultural events"),+ ),+ (+ ADMISSION_TO_ENTERTAINMENT_EVENTS,+ pgettext_lazy("VAT rate type", "admission to entertainment events"),+ ),+ (+ ADMISSION_TO_SPORTING_EVENTS,+ pgettext_lazy("VAT rate type", "admission to sporting events"),+ ),+ (ADVERTISING, pgettext_lazy("VAT rate type", "advertising")),+ (+ AGRICULTURAL_SUPPLIES,+ pgettext_lazy("VAT rate type", "agricultural supplies"),+ ),+ (BABY_FOODSTUFFS, pgettext_lazy("VAT rate type", "baby foodstuffs")),+ (BIKES, pgettext_lazy("VAT rate type", "bikes")),+ (BOOKS, pgettext_lazy("VAT rate type", "books")),+ (CHILDRENDS_CLOTHING, pgettext_lazy("VAT rate type", "childrens clothing")),+ (DOMESTIC_FUEL, pgettext_lazy("VAT rate type", "domestic fuel")),+ (DOMESTIC_SERVICES, pgettext_lazy("VAT rate type", "domestic services")),+ (E_BOOKS, pgettext_lazy("VAT rate type", "e-books")),+ (FOODSTUFFS, pgettext_lazy("VAT rate type", "foodstuffs")),+ (HOTELS, pgettext_lazy("VAT rate type", "hotels")),+ (MEDICAL, pgettext_lazy("VAT rate type", "medical")),+ (NEWSPAPERS, pgettext_lazy("VAT rate type", "newspapers")),+ (PASSENGER_TRANSPORT, pgettext_lazy("VAT rate type", "passenger transport")),+ (PHARMACEUTICALS, pgettext_lazy("VAT rate type", "pharmaceuticals")),+ (PROPERTY_RENOVATIONS, pgettext_lazy("VAT rate type", "property renovations")),+ (RESTAURANTS, pgettext_lazy("VAT rate type", "restaurants")),+ (SOCIAL_HOUSING, pgettext_lazy("VAT rate type", "social housing")),+ (STANDARD, pgettext_lazy("VAT rate type", "standard")),+ (WATER, pgettext_lazy("VAT rate type", "water")),+ (WINE, pgettext_lazy("VAT rate type", "wine")),+ )+++DEFAULT_TAX_RATE_NAME = TaxRateType.STANDARD+++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,))++ if rate_name in taxes:+ tax_to_apply = taxes[rate_name]["tax"]+ else:+ tax_to_apply = taxes[DEFAULT_TAX_RATE_NAME]["tax"]++ keep_gross = include_taxes_in_prices()+ return tax_to_apply(base, keep_gross=keep_gross)+++def get_taxes_for_country(country):+ tax_rates = get_tax_rates_for_country(country.code)+ if tax_rates is None:+ return None++ taxes = {+ DEFAULT_TAX_RATE_NAME: {+ "value": tax_rates["standard_rate"],+ "tax": get_tax_for_rate(tax_rates),+ }+ }+ if tax_rates["reduced_rates"]:+ taxes.update(+ {+ rate_name: {+ "value": tax_rates["reduced_rates"][rate_name],+ "tax": get_tax_for_rate(tax_rates, rate_name),+ }+ for rate_name in tax_rates["reduced_rates"]+ }+ )+ return taxes+++def get_taxes_for_address(address):+ """Return proper taxes for address or default country."""+ if address is not None:+ country = address.country+ else:+ country = Country(settings.DEFAULT_COUNTRY)++ return get_taxes_for_country(country)+++def get_tax_rate_by_name(rate_name, taxes=None):+ """Return value of tax rate for current taxes."""+ if not taxes or not rate_name:+ tax_rate = 0+ elif rate_name in taxes:+ tax_rate = taxes[rate_name]["value"]+ else:+ tax_rate = taxes[DEFAULT_TAX_RATE_NAME]["value"]++ return tax_rate+++def get_taxed_shipping_price(shipping_price, taxes):+ """Calculate shipping price based on settings and taxes."""+ if not charge_taxes_on_shipping():+ taxes = None+ return apply_tax_to_price(taxes, DEFAULT_TAX_RATE_NAME, shipping_price)diff --git a/saleor/core/extensions/plugins/vatlayer/plugin.py b/saleor/core/extensions/plugins/vatlayer/plugin.pynew file mode 100644index 0000000000..5b60616a70--- /dev/null+++ b/saleor/core/extensions/plugins/vatlayer/plugin.py@@ -0,0 +1,246 @@+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_address,+ 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"++ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self._enabled = bool(settings.VATLAYER_ACCESS_KEY)++ 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, price+ )+ return lines_total++ 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 = get_taxes_for_address(address)+ 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 = get_taxes_for_address(address)+ 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, previous_value+ )++ 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, previous_value+ )++ 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 = None+ if country:+ taxes = 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 = 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++ taxes = kwargs.get("taxes")+ if country and not taxes:+ # FIXME After we introduce plugin architecture, taxes will be cached on the+ # plugin level and there will be no need to pass it from view functions.+ # This is only temporary approach to limit redis and db hits+ taxes = get_taxes_for_country(country)+ if not product.charge_taxes:+ taxes = None+ 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 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}+ 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, {})+ return TaxType(code=tax.get("code", ""), description=tax.get("description", ""))diff --git a/saleor/core/middleware.py b/saleor/core/middleware.pyindex 310fb95415..0a904021b7 100644--- a/saleor/core/middleware.py+++ b/saleor/core/middleware.py@@ -118,10 +118,10 @@ def extensions(get_response):"""Assign extensions manager"""def _get_manager():- return get_extensions_manager()+ return get_extensions_manager(plugins=settings.PLUGINS)def middleware(request):- request.extensions = SimpleLazyObject(_get_manager)+ request.extensions = SimpleLazyObject(lambda: _get_manager())return get_response(request)return middlewarediff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex a80754e10a..a8d37dcce9 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -53,7 +53,7 @@ from ...product.thumbnails import (create_product_thumbnails,)from ...shipping.models import ShippingMethod, ShippingMethodType, ShippingZone-from ..taxes import interface as tax_interface+from ..extensions.manager import get_extensions_managerfake = Factory.create()@@ -378,8 +378,9 @@ def create_order_lines(order, discounts, how_many=10):)ProductVariant.objects.bulk_update(variants, ["quantity", "quantity_allocated"])lines = OrderLine.objects.bulk_create(lines)+ manager = get_extensions_manager()for line in lines:- unit_price = tax_interface.calculate_order_line_unit(line)+ unit_price = manager.calculate_order_line_unit(line)line.unit_price_net = unit_price.netline.unit_price_gross = unit_price.grossline.tax_rate = unit_price.tax / unit_price.net@@ -420,9 +421,10 @@ def create_fake_order(discounts, max_order_lines=5):"user_email": get_email(address.first_name, address.last_name),}+ manager = get_extensions_manager()shipping_method = ShippingMethod.objects.order_by("?").first()shipping_price = shipping_method.price- shipping_price = tax_interface.apply_taxes_to_shipping(shipping_price, address)+ shipping_price = manager.apply_taxes_to_shipping(shipping_price, address)order_data.update({"shipping_method_name": shipping_method.name, "shipping_price": shipping_price})diff --git a/saleor/core/views.py b/saleor/core/views.pyindex 2b53a3a4f9..046e3b1d54 100644--- a/saleor/core/views.py+++ b/saleor/core/views.py@@ -22,7 +22,7 @@ def home(request):discounts=request.discounts,country=request.country,local_currency=request.currency,- taxes=request.taxes,+ extensions=request.extensions,))webpage_schema = get_webpage_schema(request)diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex ca70f1f02d..d2322f249d 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -11,7 +11,8 @@ from ...account.i18n import (from ...account.models import Userfrom ...checkout.forms import QuantityFieldfrom ...core.exceptions import InsufficientStock-from ...core.taxes import interface as tax_interface, zero_taxed_money+from ...core.extensions.manager import get_extensions_manager+from ...core.taxes import zero_taxed_moneyfrom ...discount.models import Voucherfrom ...discount.utils import decrease_voucher_usage, increase_voucher_usagefrom ...order import OrderStatus, events@@ -211,9 +212,9 @@ class OrderShippingForm(forms.ModelForm):def save(self, commit=True):method = self.instance.shipping_methodself.instance.shipping_method_name = method.name- self.instance.shipping_price = tax_interface.calculate_order_shipping(- self.instance- )++ manager = get_extensions_manager()+ self.instance.shipping_price = manager.calculate_order_shipping(self.instance)recalculate_order(self.instance)return super().save(commit)diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex e48b2cc348..a27edb0006 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -9,8 +9,8 @@ from django.utils.text import slugifyfrom django.utils.translation import pgettext_lazyfrom mptt.forms import TreeNodeChoiceField+from ...core.extensions.manager import get_extensions_managerfrom ...core.taxes import include_taxes_in_prices-from ...core.taxes.interface import get_tax_from_object_meta, get_tax_rate_type_choicesfrom ...core.weight import WeightFieldfrom ...product.models import (Attribute,@@ -106,8 +106,9 @@ class ProductTypeForm(forms.ModelForm):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)+ manager = get_extensions_manager()self.fields["tax_rate"].choices = [- (tax.code, tax.description) for tax in get_tax_rate_type_choices()+ (tax.code, tax.description) for tax in manager.get_tax_rate_type_choices()]unassigned_attrs_q = Q(product_type__isnull=True, product_variant_type__isnull=True@@ -277,10 +278,11 @@ class ProductForm(forms.ModelForm, AttributesMixin):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)+ manager = get_extensions_manager()product_type = self.instance.product_type- product_tax_rate = get_tax_from_object_meta(self.instance).code+ product_tax_rate = manager.get_tax_code_from_object_meta(self.instance).codeself.initial["tax_rate"] = (- product_tax_rate or get_tax_from_object_meta(product_type).code+ product_tax_rate or manager.get_tax_code_from_object_meta(product_type).code)self.available_attributes = product_type.product_attributes.prefetch_related("values"@@ -299,7 +301,7 @@ class ProductForm(forms.ModelForm, AttributesMixin):extra_attrs={"data-bind": self["name"].auto_id})self.fields["tax_rate"].choices = [- (tax.code, tax.description) for tax in get_tax_rate_type_choices()+ (tax.code, tax.description) for tax in manager.get_tax_rate_type_choices()]if include_taxes_in_prices():self.fields["price"].label = pgettext_lazy(diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.pyindex 3822e507bf..1fb1962cec 100644--- a/saleor/dashboard/product/views.py+++ b/saleor/dashboard/product/views.py@@ -8,7 +8,6 @@ from django.template.response import TemplateResponsefrom django.utils.translation import npgettext_lazy, pgettext_lazyfrom django.views.decorators.http import require_POST-from ...core.taxes import interface as tax_interfacefrom ...core.utils import get_paginator_itemsfrom ...product.models import (Attribute,@@ -56,7 +55,7 @@ def product_details(request, pk):product,discounts=request.discounts,country=request.country,- taxes=request.taxes,+ extensions=request.extensions,)sale_price = availability.price_range_undiscounteddiscounted_price = availability.price_range@@ -314,7 +313,7 @@ def variant_details(request, product_pk, variant_pk):images = variant.images.all()margin = get_margin_for_variant(variant)- discounted_price = tax_interface.apply_taxes_to_product(+ discounted_price = request.extensions.apply_taxes_to_product(variant.product, variant.get_price(discounts=request.discounts), request.country).grossctx = {diff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex 059c519779..1c6137e523 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -5,8 +5,8 @@ from typing import Iterablefrom django.db.models import Ffrom django.utils.translation import pgettext+from ..core.extensions.manager import get_extensions_managerfrom ..core.taxes import zero_money-from ..core.taxes.interface import calculate_checkout_subtotalfrom . import DiscountInfofrom .models import NotApplicable, Sale, VoucherCustomer@@ -85,7 +85,8 @@ def calculate_discounted_price(product, price, discounts: Iterable[DiscountInfo]def validate_voucher_for_checkout(voucher, checkout, discounts):- subtotal = calculate_checkout_subtotal(checkout, discounts)+ manager = get_extensions_manager()+ subtotal = manager.calculate_checkout_subtotal(checkout, discounts)customer_email = checkout.get_customer_email()validate_voucher(voucher, subtotal.gross, checkout.quantity, customer_email)diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex d8362d0732..1a3819d2e8 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -23,8 +23,8 @@ from ...checkout.utils import ()from ...core import analyticsfrom ...core.exceptions import InsufficientStock+from ...core.extensions.manager import get_extensions_managerfrom ...core.taxes.errors import TaxError-from ...core.taxes.interface import calculate_checkout_subtotalfrom ...discount import models as voucher_modelfrom ...payment import PaymentErrorfrom ...payment.interface import AddressData@@ -54,8 +54,10 @@ def clean_shipping_method(checkout, method, discounts, country_code=None, remove"shipping address.")+ manger = get_extensions_manager()+ price = manger.calculate_checkout_subtotal(checkout, discounts).gross.amountvalid_methods = ShippingMethodModel.objects.applicable_shipping_methods(- price=calculate_checkout_subtotal(checkout, discounts).gross.amount,+ price=price,weight=checkout.get_total_weight(),country_code=country_code or checkout.shipping_address.country.code,)diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex 7dd16c6263..9d4fdc3001 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -4,12 +4,6 @@ from django.conf import settingsfrom ...checkout import modelsfrom ...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 CountableDjangoObjectTypefrom ..core.types.money import TaxedMoneyfrom ..giftcard.types import GiftCard@@ -36,7 +30,7 @@ class CheckoutLine(CountableDjangoObjectType):@staticmethoddef resolve_total_price(self, info):- return calculate_checkout_line_total(+ return info.context.extensions.calculate_checkout_line_total(checkout_line=self, discounts=info.context.discounts)@@ -122,20 +116,22 @@ class Checkout(CountableDjangoObjectType):@staticmethoddef resolve_total_price(root: models.Checkout, info):taxed_total = (- calculate_checkout_total(checkout=root, discounts=info.context.discounts)+ info.context.extensions.calculate_checkout_total(+ checkout=root, discounts=info.context.discounts+ )- root.get_total_gift_cards_balance())return max(taxed_total, zero_taxed_money())@staticmethoddef resolve_subtotal_price(root: models.Checkout, info):- return calculate_checkout_subtotal(+ return info.context.extensions.calculate_checkout_subtotal(checkout=root, discounts=info.context.discounts)@staticmethoddef resolve_shipping_price(root: models.Checkout, info):- return calculate_checkout_shipping(+ return info.context.extensions.calculate_checkout_shipping(checkout=root, discounts=info.context.discounts)@@ -145,7 +141,7 @@ class Checkout(CountableDjangoObjectType):@staticmethoddef resolve_available_shipping_methods(root: models.Checkout, info):- price = calculate_checkout_subtotal(+ price = info.context.extensions.calculate_checkout_subtotal(checkout=root, discounts=info.context.discounts)return applicable_shipping_methods(root, price.gross.amount)diff --git a/saleor/graphql/core/schema.py b/saleor/graphql/core/schema.pyindex ec29797bce..1008a056de 100644--- a/saleor/graphql/core/schema.py+++ b/saleor/graphql/core/schema.py@@ -1,7 +1,6 @@import grapheneimport graphql_jwt-from ...core.taxes import interface as tax_interfacefrom .mutations import CreateToken, VerifyTokenfrom .types.common import TaxType@@ -17,8 +16,9 @@ class CoreQueries(graphene.ObjectType):TaxType, description="List of all tax rates available from tax gateway")- def resolve_tax_types(self, _info):+ def resolve_tax_types(self, info):+ manager = info.context.extensionsreturn [TaxType(description=tax.description, tax_code=tax.code)- for tax in tax_interface.get_tax_rate_type_choices()+ for tax in manager.get_tax_rate_type_choices()]diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 122b6c8cb8..a856029319 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -2,7 +2,7 @@ import graphenefrom django.core.exceptions import ValidationErrorfrom ....account.models import User-from ....core.taxes import interface as tax_interface, zero_taxed_money+from ....core.taxes import zero_taxed_moneyfrom ....order import events, modelsfrom ....order.utils import cancel_order, recalculate_orderfrom ....payment import CustomPaymentChoices, PaymentError@@ -172,7 +172,7 @@ class OrderUpdateShipping(BaseMutation):clean_order_update_shipping(order, method)order.shipping_method = method- order.shipping_price = tax_interface.calculate_order_shipping(order)+ order.shipping_price = info.context.extensions.calculate_order_shipping(order)order.shipping_method_name = method.nameorder.save(update_fields=[diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex 82f7615a06..7e6b19233c 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -3,7 +3,6 @@ from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom ...core.taxes import zero_taxed_money-from ...core.taxes.interface import calculate_checkout_totalfrom ...core.utils import get_client_ipfrom ...payment import PaymentError, modelsfrom ...payment.utils import (@@ -79,8 +78,11 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):raise ValidationError({"billing_address": "No billing address associated with this checkout."})+checkout_total = (- calculate_checkout_total(checkout, discounts=info.context.discounts)+ info.context.extensions.calculate_checkout_total(+ checkout, discounts=info.context.discounts+ )- checkout.get_total_gift_cards_balance())checkout_total = max(checkout_total, zero_taxed_money(checkout_total.currency))diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 1a9d31c2c8..2ccc45bc5c 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -6,8 +6,6 @@ from django.db import transactionfrom django.template.defaultfilters import slugifyfrom graphene.types import InputObjectType-from ....core.taxes import interface as tax_interface-from ....core.taxes.vatlayer import interface as vatlayer_interfacefrom ....product import modelsfrom ....product.tasks import update_variants_namesfrom ....product.thumbnails import (@@ -425,11 +423,11 @@ class ProductCreate(ModelMutation):# FIXME tax_rate logic should be dropped after we remove tax_rate from inputtax_rate = cleaned_input.pop("tax_rate", "")if tax_rate:- vatlayer_interface.assign_tax_to_object_meta(instance, tax_rate)+ info.context.extensions.assign_tax_code_to_object_meta(instance, tax_rate)tax_code = cleaned_input.pop("tax_code", "")if tax_code:- tax_interface.assign_tax_to_object_meta(instance, tax_code)+ info.context.extensions.assign_tax_code_to_object_meta(instance, tax_code)if attributes and product_type:qs = product_type.product_attributes.prefetch_related("values")@@ -702,11 +700,17 @@ class ProductTypeCreate(ModelMutation):# FIXME tax_rate logic should be dropped after we remove tax_rate from inputtax_rate = cleaned_input.pop("tax_rate", "")if tax_rate:- vatlayer_interface.assign_tax_to_object_meta(instance, tax_rate)+ if "taxes" not in instance.meta:+ instance.meta["taxes"] = {}+ instance.meta["taxes"]["vatlayer"] = {+ "code": tax_rate,+ "description": tax_rate,+ }+ info.context.extensions.assign_tax_code_to_object_meta(instance, tax_rate)tax_code = cleaned_input.pop("tax_code", "")if tax_code:- tax_interface.assign_tax_to_object_meta(instance, tax_code)+ info.context.extensions.assign_tax_code_to_object_meta(instance, tax_code)return cleaned_inputdiff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex 3c2dca5dfc..a7684cc65d 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -5,8 +5,6 @@ from graphene import relayfrom graphql.error import GraphQLErrorfrom graphql_jwt.decorators import permission_required-from ....core.taxes import interface as tax_interface-from ....core.taxes.vatlayer import interface as vatlayer_interfacefrom ....product import modelsfrom ....product.templatetags.product_images import (get_product_image_thumbnail,@@ -289,7 +287,7 @@ class ProductVariant(CountableDjangoObjectType):context.discounts,context.country,context.currency,- taxes=context.taxes,+ extensions=context.extensions,)return VariantPricingInfo(**availability._asdict())@@ -454,12 +452,14 @@ class Product(CountableDjangoObjectType):@staticmethoddef resolve_tax_rate(root: models.ProductType, info, **_kwargs):# FIXME this resolver should be dropped after we drop tax_rate from API- tax_rate = vatlayer_interface.get_tax_from_object_meta(root).code- return tax_rate or None+ if not hasattr(root, "meta"):+ return None+ tax = root.meta.get("taxes", {}).get("vatlayer", {})+ return tax.get("code")@staticmethod- def resolve_tax_type(root: models.Product, _info):- tax_data = tax_interface.get_tax_from_object_meta(root)+ def resolve_tax_type(root: models.Product, info):+ tax_data = info.context.extensions.get_tax_code_from_object_meta(root)return TaxType(tax_code=tax_data.code, description=tax_data.description)@staticmethod@@ -495,7 +495,11 @@ class Product(CountableDjangoObjectType):def resolve_pricing(root: models.Product, info):context = info.contextavailability = get_product_availability(- root, context.discounts, context.country, context.currency, context.taxes+ root,+ context.discounts,+ context.country,+ context.currency,+ context.extensions,)return ProductPricingInfo(**availability._asdict())@@ -517,8 +521,8 @@ class Product(CountableDjangoObjectType):)def resolve_price(root: models.Product, info):price_range = root.get_price_range(info.context.discounts)- price = tax_interface.apply_taxes_to_product(- root, price_range.start, info.context.country, taxes=info.context.taxes+ price = info.context.extensions.apply_taxes_to_product(+ root, price_range.start, info.context.country)return price.net@@ -609,15 +613,17 @@ class ProductType(CountableDjangoObjectType):]@staticmethod- def resolve_tax_type(root: models.ProductType, _info):- tax_data = tax_interface.get_tax_from_object_meta(root)+ def resolve_tax_type(root: models.ProductType, info):+ tax_data = info.context.extensions.get_tax_code_from_object_meta(root)return TaxType(tax_code=tax_data.code, description=tax_data.description)@staticmethoddef resolve_tax_rate(root: models.ProductType, info, **_kwargs):# FIXME this resolver should be dropped after we drop tax_rate from API- tax_rate = vatlayer_interface.get_tax_from_object_meta(root).code- return tax_rate or None+ if not hasattr(root, "meta"):+ return None+ tax = root.meta.get("taxes", {}).get("vatlayer", {})+ return tax.get("code")@staticmethod@gql_optimizer.resolver_hints(prefetch_related="product_attributes")diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex e031e9db71..905ba66963 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -8,8 +8,8 @@ from prices import Money, TaxedMoneyfrom ..account.utils import store_user_addressfrom ..checkout import AddressType+from ..core.extensions.manager import get_extensions_managerfrom ..core.taxes import zero_money-from ..core.taxes.interface import calculate_order_line_unit, calculate_order_shippingfrom ..core.weight import zero_weightfrom ..dashboard.order.utils import get_voucher_discount_for_orderfrom ..discount.models import NotApplicable@@ -153,6 +153,7 @@ def recalculate_order_weight(order):def update_order_prices(order, discounts):"""Update prices in order with given discounts and proper taxes."""+ manager = get_extensions_manager()for line in order:if line.variant:unit_price = line.variant.get_price(discounts)@@ -160,7 +161,7 @@ def update_order_prices(order, discounts):line.unit_price_gross = unit_priceline.save(update_fields=["unit_price_net", "unit_price_gross"])- price = calculate_order_line_unit(line)+ price = manager.calculate_order_line_unit(line)if price != line.unit_price:line.unit_price = priceif price.tax and price.net:@@ -168,7 +169,7 @@ def update_order_prices(order, discounts):line.save()if order.shipping_method:- order.shipping_price = calculate_order_shipping(order)+ order.shipping_price = manager.calculate_order_shipping(order)order.save()recalculate_order(order)@@ -293,8 +294,8 @@ def add_variant_to_order(unit_price_gross=unit_price,variant=variant,)-- unit_price = calculate_order_line_unit(line)+ manager = get_extensions_manager()+ unit_price = manager.calculate_order_line_unit(line)line.unit_price_net = unit_price.netline.unit_price_gross = unit_price.grossline.tax_rate = unit_price.tax / unit_price.netdiff --git a/saleor/product/forms.py b/saleor/product/forms.pyindex 3f13219ea6..745c0b16a9 100644--- a/saleor/product/forms.py+++ b/saleor/product/forms.py@@ -7,7 +7,6 @@ from django_prices.templatetags.prices_i18n import amountfrom ..checkout.forms import AddToCheckoutFormfrom ..core.taxes import display_gross_prices-from ..core.taxes.interface import apply_taxes_to_productclass VariantChoiceField(forms.ModelChoiceField):@@ -15,11 +14,12 @@ class VariantChoiceField(forms.ModelChoiceField):country = Nonedisplay_gross = Truetaxes = None+ extensions = Nonedef label_from_instance(self, obj):variant_label = smart_text(obj)- price = apply_taxes_to_product(- obj.product, obj.get_price(self.discounts), self.country, taxes=self.taxes+ price = self.extensions.apply_taxes_to_product(+ obj.product, obj.get_price(self.discounts), self.country)price = price.gross if self.display_gross else price.netlabel = pgettext_lazy(@@ -27,12 +27,12 @@ class VariantChoiceField(forms.ModelChoiceField):) % {"variant_label": variant_label, "price": amount(price)}return label- def update_field_data(self, variants, discounts, country, taxes=None):+ def update_field_data(self, variants, discounts, country, extensions=None):"""Initialize variant picker metadata."""self.queryset = variantsself.discounts = discountsself.country = country- self.taxes = taxes+ self.extensions = extensionsself.empty_label = Noneself.display_gross = display_gross_prices()images_map = {@@ -54,7 +54,7 @@ class ProductForm(AddToCheckoutForm):shipping_address = self.checkout.shipping_addresscountry = shipping_address.country if shipping_address else self.countryvariant_field.update_field_data(- self.product.variants.all(), self.discounts, country, self.taxes+ self.product.variants.all(), self.discounts, country, self.extensions)def get_variant(self, cleaned_data):diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.pyindex 44e302ad72..7d1cf49149 100644--- a/saleor/product/utils/__init__.py+++ b/saleor/product/utils/__init__.py@@ -71,7 +71,7 @@ def handle_checkout_form(request, product, create_checkout=False):data=request.POST or None,discounts=request.discounts,country=request.country,- taxes=request.taxes,+ extensions=request.extensions,)return form, checkoutdiff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.pyindex a62c9b45a1..316f0f0020 100644--- a/saleor/product/utils/availability.py+++ b/saleor/product/utils/availability.py@@ -7,7 +7,7 @@ from prices import TaxedMoneyRangefrom saleor.graphql.core.types import MoneyRangefrom saleor.product.models import Product, ProductVariant-from ...core.taxes.interface import apply_taxes_to_product+from ...core.extensions.manager import get_extensions_managerfrom ...core.utils import to_local_currencyfrom ...discount import DiscountInfofrom .. import ProductAvailabilityStatus, VariantAvailabilityStatus@@ -40,13 +40,13 @@ VariantAvailability = namedtuple(def products_with_availability(- products, discounts, country, local_currency, taxes=None+ products, discounts, country, local_currency, extensions):for product in products:yield (product,get_product_availability(- product, discounts, country, local_currency, taxes=taxes+ product, discounts, country, local_currency, extensions=extensions),)@@ -117,25 +117,27 @@ def get_product_availability(discounts: Iterable[DiscountInfo] = None,country=None,local_currency=None,- taxes=None,+ extensions=None,) -> ProductAvailability:+ if not extensions:+ extensions = get_extensions_manager()discounted_net_range = product.get_price_range(discounts=discounts)undiscounted_net_range = product.get_price_range()discounted = TaxedMoneyRange(- start=apply_taxes_to_product(- product, discounted_net_range.start, country, taxes=taxes+ start=extensions.apply_taxes_to_product(+ product, discounted_net_range.start, country),- stop=apply_taxes_to_product(- product, discounted_net_range.stop, country, taxes=taxes+ stop=extensions.apply_taxes_to_product(+ product, discounted_net_range.stop, country),)undiscounted = TaxedMoneyRange(- start=apply_taxes_to_product(- product, undiscounted_net_range.start, country, taxes=taxes+ start=extensions.apply_taxes_to_product(+ product, undiscounted_net_range.start, country),- stop=apply_taxes_to_product(- product, undiscounted_net_range.stop, country, taxes=taxes+ stop=extensions.apply_taxes_to_product(+ product, undiscounted_net_range.stop, country),)@@ -162,14 +164,16 @@ def get_variant_availability(discounts: Iterable[DiscountInfo] = None,country=None,local_currency=None,- taxes=None,+ extensions=None,) -> VariantAvailability:- discounted = apply_taxes_to_product(- variant.product, variant.get_price(discounts=discounts), country, taxes=taxes+ if not extensions:+ extensions = get_extensions_manager()+ discounted = extensions.apply_taxes_to_product(+ variant.product, variant.get_price(discounts=discounts), country)- undiscounted = apply_taxes_to_product(- variant.product, variant.get_price(), country, taxes=taxes+ undiscounted = extensions.apply_taxes_to_product(+ variant.product, variant.get_price(), country)discount = _get_total_discount(undiscounted, discounted)diff --git a/saleor/product/utils/variants_picker.py b/saleor/product/utils/variants_picker.pyindex c89b979a70..4cd8d641f0 100644--- a/saleor/product/utils/variants_picker.py+++ b/saleor/product/utils/variants_picker.py@@ -3,8 +3,8 @@ from typing import Iterablefrom django_prices.templatetags import prices_i18n+from ...core.extensions.manager import get_extensions_managerfrom ...core.taxes import display_gross_prices-from ...core.taxes.interface import apply_taxes_to_product, show_taxes_on_storefrontfrom ...core.utils import to_local_currencyfrom ...discount import DiscountInfofrom ...seo.schema.product import variant_json_ld@@ -14,12 +14,14 @@ from .availability import get_product_availabilitydef get_variant_picker_data(product,discounts: Iterable[DiscountInfo] = None,- taxes=None,+ extensions=None,local_currency=None,country=None,):+ if not extensions:+ extensions = get_extensions_manager()availability = get_product_availability(- product, discounts, country, local_currency, taxes+ product, discounts, country, local_currency, extensions)variants = product.variants.all()data = {"variantAttributes": [], "variants": []}@@ -30,11 +32,11 @@ def get_variant_picker_data(filter_available_variants = defaultdict(list)for variant in variants:- price = apply_taxes_to_product(- variant.product, variant.get_price(discounts), country, taxes=taxes+ price = extensions.apply_taxes_to_product(+ variant.product, variant.get_price(discounts), country)- price_undiscounted = apply_taxes_to_product(- variant.product, variant.get_price(), country, taxes=taxes+ price_undiscounted = extensions.apply_taxes_to_product(+ variant.product, variant.get_price(), country)if local_currency:price_local_currency = to_local_currency(price, local_currency)@@ -78,7 +80,7 @@ def get_variant_picker_data(})- product_price = apply_taxes_to_product(product, product.price, country, taxes=taxes)+ product_price = extensions.apply_taxes_to_product(product, product.price, country)tax_rates = 0if product_price.tax and product_price.net:tax_rates = int((product_price.tax / product_price.net) * 100)@@ -96,7 +98,7 @@ def get_variant_picker_data(}data["priceDisplay"] = {"displayGross": display_gross_prices(),- "handleTaxes": show_taxes_on_storefront(),+ "handleTaxes": extensions.show_taxes_on_storefront(),}return datadiff --git a/saleor/product/views.py b/saleor/product/views.pyindex cb8951adc7..5c83a25894 100644--- a/saleor/product/views.py+++ b/saleor/product/views.py@@ -80,10 +80,15 @@ def product_details(request, slug, product_id, form=None):discounts=request.discounts,country=request.country,local_currency=request.currency,+ extensions=request.extensions,)product_images = get_product_images(product)variant_picker_data = get_variant_picker_data(- product, request.discounts, request.taxes, request.currency, request.country+ product,+ request.discounts,+ request.extensions,+ request.currency,+ request.country,)product_attributes = get_product_attributes_data(product)# show_variant_picker determines if variant picker is used or select inputdiff --git a/saleor/search/views.py b/saleor/search/views.pyindex b415672b7f..07d45f9fae 100644--- a/saleor/search/views.py+++ b/saleor/search/views.py@@ -25,7 +25,7 @@ def evaluate_search_query(form, request):discounts=request.discounts,country=request.country,local_currency=request.currency,- taxes=request.taxes,+ extensions=request.extensions,)diff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.pyindex 73c1992918..10f52e0e48 100644--- a/saleor/shipping/utils.py+++ b/saleor/shipping/utils.py@@ -2,7 +2,7 @@ from django.db.models import Qfrom django.utils.translation import pgettext_lazyfrom prices import MoneyRange-from ..core.taxes import interface as tax_interface+from ..core.extensions.manager import get_extensions_managerfrom ..core.weight import convert_weight, get_default_weight_unit@@ -17,7 +17,8 @@ def get_shipping_price_estimate(price, weight, country_code):if not shipping_methods:returnprices = MoneyRange(start=min(shipping_methods), stop=max(shipping_methods))- return tax_interface.apply_taxes_to_shipping_price_range(prices, country_code)+ manager = get_extensions_manager()+ return manager.apply_taxes_to_shipping_price_range(prices, country_code)def applicable_weight_based_methods(weight, qs):diff --git a/tests/api/test_product.py b/tests/api/test_product.pyindex 9624faab25..e77b2b82c8 100644--- a/tests/api/test_product.py+++ b/tests/api/test_product.py@@ -11,7 +11,8 @@ from django.utils.text import slugifyfrom graphql_relay import to_global_idfrom prices import Money-from saleor.core.taxes import TaxType, interface as tax_interface+from saleor.core.extensions.manager import ExtensionsManager+from saleor.core.taxes import TaxTypefrom saleor.graphql.core.enums import ReportingPeriodfrom saleor.graphql.product.enums import StockAvailabilityfrom saleor.graphql.product.types.products import resolve_attribute_list@@ -744,8 +745,9 @@ def test_create_product(# Mock tax interface with fake response from tax gatewaymonkeypatch.setattr(- "saleor.graphql.product.types.products.tax_interface.get_tax_from_object_meta",- lambda x: TaxType(description="", code=product_tax_rate),+ ExtensionsManager,+ "get_tax_code_from_object_meta",+ lambda self, x: TaxType(description="", code=product_tax_rate),)# Default attribute defined in product_type fixture@@ -1065,8 +1067,9 @@ def test_update_product(# Mock tax interface with fake response from tax gatewaymonkeypatch.setattr(- "saleor.graphql.product.types.products.tax_interface.get_tax_from_object_meta",- lambda x: TaxType(description="", code=product_tax_rate),+ ExtensionsManager,+ "get_tax_code_from_object_meta",+ lambda self, x: TaxType(description="", code=product_tax_rate),)variables = {@@ -1262,14 +1265,9 @@ def test_product_type_query(monkeypatch,):monkeypatch.setattr(- "saleor.graphql.product.types.products."- "vatlayer_interface.get_tax_from_object_meta",- lambda x: TaxType(code="standard", description=""),- )- monkeypatch.setattr(- "saleor.graphql.product.types.products."- "tax_interface.get_tax_from_object_meta",- lambda x: TaxType(code="123", description="Standard Taxes"),+ ExtensionsManager,+ "get_tax_code_from_object_meta",+ lambda self, x: TaxType(code="123", description="Standard Taxes"),)query = """query getProductType($id: ID!) {@@ -1306,7 +1304,6 @@ def test_product_type_query(content = get_graphql_content(response)data = content["data"]assert data["productType"]["products"]["totalCount"] == no_products- assert data["productType"]["taxRate"] == "STANDARD"assert data["productType"]["taxType"]["taxCode"] == "123"assert data["productType"]["taxType"]["description"] == "Standard Taxes"@@ -1315,11 +1312,8 @@ def test_product_type_create_mutation(staff_api_client, product_type, permission_manage_products, monkeypatch, settings):settings.VATLAYER_ACCESS_KEY = "test"- monkeypatch.setattr(- "saleor.graphql.product.types.products."- "vatlayer_interface.get_tax_from_object_meta",- lambda x: TaxType(code="standard", description=""),- )+ settings.PLUGINS = ["saleor.core.extensions.plugins.vatlayer.plugin.VatlayerPlugin"]+ manager = ExtensionsManager(plugins=settings.PLUGINS)query = """mutation createProductType($name: String!,@@ -1372,7 +1366,7 @@ def test_product_type_create_mutation(variables = {"name": product_type_name,"hasVariants": has_variants,- "taxCode": "STANDARD",+ "taxCode": "wine","isShippingRequired": require_shipping,"productAttributes": product_attributes_ids,"variantAttributes": variant_attributes_ids,@@ -1403,8 +1397,8 @@ def test_product_type_create_mutation()new_instance = ProductType.objects.latest("pk")- tax_code = tax_interface.get_tax_from_object_meta(new_instance).code- assert tax_code == "standard"+ tax_code = manager.get_tax_code_from_object_meta(new_instance).code+ assert tax_code == "wine"def test_product_type_update_mutation(diff --git a/tests/api/test_variant_pricing.py b/tests/api/test_variant_pricing.pyindex 45be7360a7..594bdac665 100644--- a/tests/api/test_variant_pricing.py+++ b/tests/api/test_variant_pricing.py@@ -2,6 +2,7 @@ from unittest.mock import Mockfrom prices import Money, TaxedMoney+from saleor.core.extensions.manager import ExtensionsManagerfrom saleor.product.models import ProductVariantfrom saleor.product.utils.availability import get_variant_availabilityfrom tests.api.utils import get_graphql_content@@ -102,8 +103,7 @@ def test_get_variant_pricing_not_on_sale(api_client, product):def test_variant_pricing(variant: ProductVariant, monkeypatch, settings):taxed_price = TaxedMoney(Money("10.0", "USD"), Money("12.30", "USD"))monkeypatch.setattr(- "saleor.product.utils.availability.apply_taxes_to_product",- Mock(return_value=taxed_price),+ ExtensionsManager, "apply_taxes_to_product", Mock(return_value=taxed_price))pricing = get_variant_availability(variant)diff --git a/tests/extensions/__init__.py b/tests/extensions/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/extensions/plugins/__init__.py b/tests/extensions/plugins/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/taxes/conftest.py b/tests/extensions/plugins/conftest.pysimilarity index 95%rename from tests/taxes/conftest.pyrename to tests/extensions/plugins/conftest.pyindex 9382290ce6..442280a6f3 100644--- a/tests/taxes/conftest.py+++ b/tests/extensions/plugins/conftest.py@@ -46,6 +46,7 @@ def taxes(tax_rates):@pytest.fixturedef vatlayer(db, settings, tax_rates, taxes):settings.VATLAYER_ACCESS_KEY = "enablevatlayer"+ settings.PLUGINS = ["saleor.core.extensions.plugins.vatlayer.plugin.VatlayerPlugin"]VAT.objects.create(country_code="PL", data=tax_rates)tax_rates_2 = {diff --git a/tests/taxes/test_vatlayer.py b/tests/extensions/plugins/test_vatlayer.pysimilarity index 99%rename from tests/taxes/test_vatlayer.pyrename to tests/extensions/plugins/test_vatlayer.pyindex 90a81daec4..ee69c00571 100644--- a/tests/taxes/test_vatlayer.py+++ b/tests/extensions/plugins/test_vatlayer.py@@ -7,7 +7,7 @@ from django_countries.fields import Countryfrom django_prices_vatlayer.models import VATfrom prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange-from saleor.core.taxes.vatlayer import (+from saleor.core.extensions.plugins.vatlayer import (DEFAULT_TAX_RATE_NAME,apply_tax_to_price,get_tax_rate_by_name,diff --git a/tests/settings.py b/tests/settings.pyindex b83b7fe874..b4c8d0898f 100644--- a/tests/settings.py+++ b/tests/settings.py@@ -41,3 +41,5 @@ MAX_CHECKOUT_LINE_QUANTITY = 50PASSWORD_HASHERS = ["tests.dummy_password_hasher.DummyHasher"]++EXTENSIONS_MANAGER = "saleor.core.extensions.manager.ExtensionsManager"diff --git a/tests/test_checkout.py b/tests/test_checkout.pyindex 6bc585d9b0..54c2c956bb 100644--- a/tests/test_checkout.py+++ b/tests/test_checkout.py@@ -30,6 +30,7 @@ from saleor.checkout.utils import (remove_voucher_from_checkout,)from saleor.core.exceptions import InsufficientStock+from saleor.core.extensions.manager import ExtensionsManagerfrom saleor.core.taxes import zero_money, zero_taxed_moneyfrom saleor.core.taxes.interface import calculate_checkout_subtotal, taxes_are_enabledfrom saleor.discount import DiscountValueType, VoucherType@@ -1047,7 +1048,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(monkeypatcsubtotal = TaxedMoney(net=Money(100, "USD"), gross=Money(100, "USD"))shipping_total = TaxedMoney(net=Money(10, "USD"), gross=Money(10, "USD"))monkeypatch.setattr(- "saleor.discount.utils.calculate_checkout_subtotal", Mock(return_value=subtotal)+ ExtensionsManager, "calculate_checkout_subtotal", Mock(return_value=subtotal))checkout = Mock(get_subtotal=Mock(return_value=subtotal),@@ -1183,8 +1184,10 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(def test_get_discount_for_checkout_product_voucher_not_applicable(monkeypatch):discounts = []+monkeypatch.setattr(- "saleor.discount.utils.calculate_checkout_subtotal",+ ExtensionsManager,+ "calculate_checkout_subtotal",Mock(return_value=TaxedMoney(net=Money("1", "USD"), gross=Money("1", "USD"))),)monkeypatch.setattr(@@ -1208,7 +1211,8 @@ def test_get_discount_for_checkout_product_voucher_not_applicable(monkeypatch):def test_get_discount_for_checkout_collection_voucher_not_applicable(monkeypatch):discounts = []monkeypatch.setattr(- "saleor.discount.utils.calculate_checkout_subtotal",+ ExtensionsManager,+ "calculate_checkout_subtotal",Mock(return_value=TaxedMoney(net=Money("1", "USD"), gross=Money("1", "USD"))),)monkeypatch.setattr(diff --git a/tests/test_product.py b/tests/test_product.pyindex 73530cc0dd..6786b4c5b7 100644--- a/tests/test_product.py+++ b/tests/test_product.py@@ -470,7 +470,7 @@ def test_product_filter_sorted_by_wrong_parameter(authorized_client, product, cadef test_get_variant_picker_data_proper_variant_count(product):data = get_variant_picker_data(- product, discounts=None, taxes=None, local_currency=None+ product, discounts=None, extensions=None, local_currency=None)assert len(data["variantAttributes"][0]["values"]) == 1diff --git a/tests/test_product_availability.py b/tests/test_product_availability.pyindex b963c92a01..b5f3c1f4fb 100644--- a/tests/test_product_availability.py+++ b/tests/test_product_availability.py@@ -3,6 +3,7 @@ from unittest.mock import Mockfrom prices import Money, TaxedMoney, TaxedMoneyRange+from saleor.core.extensions.manager import ExtensionsManagerfrom saleor.product import ProductAvailabilityStatus, VariantAvailabilityStatus, modelsfrom saleor.product.utils.availability import (get_product_availability,@@ -74,8 +75,7 @@ def test_variant_availability_status(unavailable_product):def test_availability(product, monkeypatch, settings):taxed_price = TaxedMoney(Money("10.0", "USD"), Money("12.30", "USD"))monkeypatch.setattr(- "saleor.product.utils.availability.apply_taxes_to_product",- Mock(return_value=taxed_price),+ ExtensionsManager, "apply_taxes_to_product", Mock(return_value=taxed_price))availability = get_product_availability(product)taxed_price_range = TaxedMoneyRange(start=taxed_price, stop=taxed_price)