Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
[RFC] Support tax exemption for checkouts and orders (#10344)
SzymJa5c3dd97b5c8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4ab6a123e1..7e865c343b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,9 @@ All notable, unreleased changes to this project will be documented in this file.### Other changes- Reference attribute linking to product variants - #10468 by @IKarbowiak+### GraphQL API++- Add `taxExemptionManage` mutation - #10344 by @SzymJ# 3.7.0@@ -45,7 +48,6 @@ All notable, unreleased changes to this project will be documented in this file.- Add support for `bcrypt` password hashes - #10346 by @pkucmus- Add the ability to set taxes configuration per channel in the Avatax plugin - #10445 by @mociepka-# 3.6.0### Breaking changesdiff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.pyindex 94bbc837af..b54d05eeae 100644--- a/saleor/checkout/calculations.py+++ b/saleor/checkout/calculations.py@@ -5,15 +5,18 @@ from django.conf import settingsfrom django.utils import timezonefrom prices import Money, TaxedMoney+from ..checkout import base_calculationsfrom ..core.prices import quantize_pricefrom ..core.taxes import TaxData, zero_taxed_moneyfrom ..discount import DiscountInfo+from ..site.models import Sitefrom .models import Checkoutif TYPE_CHECKING:from ..account.models import Addressfrom ..plugins.manager import PluginsManager+ from ..site.models import SiteSettingsfrom .fetch import CheckoutInfo, CheckoutLineInfo@@ -24,6 +27,7 @@ def checkout_shipping_price(lines: Iterable["CheckoutLineInfo"],address: Optional["Address"],discounts: Optional[Iterable[DiscountInfo]] = None,+ site_settings: Optional["SiteSettings"] = None) -> "TaxedMoney":"""Return checkout shipping price.@@ -36,6 +40,7 @@ def checkout_shipping_price(lines=lines,address=address,discounts=discounts,+ site_settings=site_settings,)return quantize_price(checkout_info.checkout.shipping_price, currency)@@ -69,6 +74,7 @@ def checkout_subtotal(lines: Iterable["CheckoutLineInfo"],address: Optional["Address"],discounts: Optional[Iterable[DiscountInfo]] = None,+ site_settings: Optional["SiteSettings"] = None) -> "TaxedMoney":"""Return the total cost of all the checkout lines, taxes included.@@ -81,6 +87,7 @@ def checkout_subtotal(lines=lines,address=address,discounts=discounts,+ site_settings=site_settings,)return quantize_price(checkout_info.checkout.subtotal, currency)@@ -91,6 +98,7 @@ def calculate_checkout_total_with_gift_cards(lines: Iterable["CheckoutLineInfo"],address: Optional["Address"],discounts: Optional[Iterable[DiscountInfo]] = None,+ site_settings: Optional["SiteSettings"] = None,) -> "TaxedMoney":total = (checkout_total(@@ -99,6 +107,7 @@ def calculate_checkout_total_with_gift_cards(lines=lines,address=address,discounts=discounts,+ site_settings=site_settings,)- checkout_info.checkout.get_total_gift_cards_balance())@@ -113,6 +122,7 @@ def checkout_total(lines: Iterable["CheckoutLineInfo"],address: Optional["Address"],discounts: Optional[Iterable[DiscountInfo]] = None,+ site_settings: Optional["SiteSettings"] = None) -> "TaxedMoney":"""Return the total cost of the checkout.@@ -128,6 +138,7 @@ def checkout_total(lines=lines,address=address,discounts=discounts,+ site_settings=site_settings,)return quantize_price(checkout_info.checkout.total, currency)@@ -154,6 +165,7 @@ def checkout_line_total(lines: Iterable["CheckoutLineInfo"],checkout_line_info: "CheckoutLineInfo",discounts: Iterable[DiscountInfo] = [],+ site_settings: Optional["SiteSettings"] = None) -> TaxedMoney:"""Return the total price of provided line, taxes included.@@ -167,6 +179,7 @@ def checkout_line_total(lines=lines,address=address,discounts=discounts,+ site_settings=site_settings,)checkout_line = _find_checkout_line_info(lines, checkout_line_info).linereturn quantize_price(checkout_line.total_price, currency)@@ -229,6 +242,7 @@ def fetch_checkout_prices_if_expired(address: Optional["Address"] = None,discounts: Optional[Iterable["DiscountInfo"]] = None,force_update: bool = False,+ site_settings: "SiteSettings" = None,) -> Tuple["CheckoutInfo", Iterable["CheckoutLineInfo"]]:"""Fetch checkout prices with taxes.@@ -239,20 +253,30 @@ def fetch_checkout_prices_if_expired(last price update is greater than settings.CHECKOUT_PRICES_TTL."""checkout = checkout_info.checkout++ if site_settings is None:+ site_settings = Site.objects.get_current().settings+if not force_update and checkout.price_expiration > timezone.now():return checkout_info, lines- # Taxes are applied to the discounted prices- _apply_tax_data_from_plugins(- checkout, manager, checkout_info, lines, address, discounts- )+ if checkout.tax_exemption and not site_settings.include_taxes_in_prices:+ _get_checkout_base_prices(checkout, checkout_info, lines, discounts)+ else:+ # Taxes are applied to the discounted prices+ _apply_tax_data_from_plugins(+ checkout, manager, checkout_info, lines, address, discounts+ )- tax_data = manager.get_taxes_for_checkout(- checkout_info,- lines,- )- if tax_data:- _apply_tax_data_from_app(checkout, lines, tax_data)+ tax_data = manager.get_taxes_for_checkout(+ checkout_info,+ lines,+ )+ if tax_data:+ _apply_tax_data_from_app(checkout, lines, tax_data)++ if checkout.tax_exemption and site_settings.include_taxes_in_prices:+ _exempt_taxes_in_checkout(checkout, lines)checkout.price_expiration = (timezone.now() + settings.CHECKOUT_PRICES_TTL # type: ignore@@ -288,6 +312,18 @@ def fetch_checkout_prices_if_expired(return checkout_info, lines+def _exempt_taxes_in_checkout(checkout, lines_info):+ checkout.total_gross_amount = checkout.total_net_amount+ checkout.subtotal_gross_amount = checkout.subtotal_net_amount+ checkout.shipping_price_gross_amount = checkout.shipping_price_net_amount+ checkout.shipping_tax_rate = Decimal("0.00")++ for line_info in lines_info:+ total_price_net_amount = line_info.line.total_price_net_amount+ line_info.line.total_price_gross_amount = total_price_net_amount+ line_info.line.tax_rate = Decimal("0.00")++def _calculate_checkout_total(checkout, currency):total = checkout.subtotal + checkout.shipping_pricereturn quantize_price(@@ -390,3 +426,59 @@ def _apply_tax_data_from_plugins(checkout.total = manager.calculate_checkout_total(checkout_info, lines, address, discounts)+++def _get_checkout_base_prices(+ checkout: "Checkout",+ checkout_info: "CheckoutInfo",+ lines: Iterable["CheckoutLineInfo"],+ discounts: Optional[Iterable[DiscountInfo]] = None,+) -> None:+ if not discounts:+ discounts = []++ currency = checkout_info.checkout.currency++ for line_info in lines:+ line = line_info.line++ total_price_default = base_calculations.calculate_base_line_total_price(+ line_info,+ checkout_info.channel,+ discounts,+ )+ line.total_price = quantize_price(+ TaxedMoney(net=total_price_default, gross=total_price_default), currency+ )++ unit_price_default = base_calculations.calculate_base_line_unit_price(+ line_info, checkout_info.channel, discounts+ )+ unit_price = quantize_price(+ TaxedMoney(net=unit_price_default, gross=unit_price_default), currency+ )++ line.tax_rate = base_calculations.base_tax_rate(unit_price)++ shipping_price_default = base_calculations.base_checkout_delivery_price(+ checkout_info, lines+ )+ checkout.shipping_price = quantize_price(+ TaxedMoney(shipping_price_default, shipping_price_default), currency+ )++ checkout.shipping_tax_rate = base_calculations.base_tax_rate(+ checkout.shipping_price+ )++ subtotal_default = sum(+ [line_info.line.total_price for line_info in lines], zero_taxed_money(currency)+ )+ checkout.subtotal = subtotal_default++ total_default = base_calculations.base_checkout_total(+ checkout_info, discounts, lines+ )+ checkout.total = quantize_price(+ TaxedMoney(net=total_default, gross=total_default), currency+ )diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex cce57ab3d0..142f76882d 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -509,6 +509,7 @@ def _create_order(origin=OrderOrigin.CHECKOUT,channel=checkout_info.channel,should_refresh_prices=False,+ tax_exemption=checkout_info.checkout.tax_exemption,)if checkout.discount:# store voucher as a fixed value as it this the simplest solution for now.@@ -756,8 +757,12 @@ def complete_checkout(for thread race.:raises ValidationError"""+ if site_settings is None:+ site_settings = Site.objects.get_current().settings- fetch_checkout_prices_if_expired(checkout_info, manager, lines, discounts)+ fetch_checkout_prices_if_expired(+ checkout_info, manager, lines, discounts=discounts, site_settings=site_settings+ )checkout = checkout_info.checkoutchannel_slug = checkout_info.channel.slug@@ -772,9 +777,6 @@ def complete_checkout(payment=payment,)- if site_settings is None:- site_settings = Site.objects.get_current().settings-try:order_data = _get_order_data(manager, checkout_info, lines, discounts, site_settings@@ -1085,6 +1087,7 @@ def _create_order_from_checkout(private_metadata=checkout_info.checkout.private_metadata,redirect_url=checkout_info.checkout.redirect_url,should_refresh_prices=False,+ tax_exemption=checkout_info.checkout.tax_exemption,**_process_shipping_data_for_order(checkout_info, shipping_total, manager, checkout_lines_info),diff --git a/saleor/checkout/migrations/0053_checkout_tax_exemption.py b/saleor/checkout/migrations/0053_checkout_tax_exemption.pynew file mode 100644index 0000000000..851a8d52b4--- /dev/null+++ b/saleor/checkout/migrations/0053_checkout_tax_exemption.py@@ -0,0 +1,25 @@+# Generated by Django 3.2.14 on 2022-08-03 09:03++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("checkout", "0052_alter_checkoutline_currency"),+ ]++ operations = [+ migrations.AddField(+ model_name="checkout",+ name="tax_exemption",+ field=models.BooleanField(default=False),+ ),+ migrations.RunSQL(+ """+ ALTER TABLE checkout_checkout ALTER COLUMN tax_exemption SET DEFAULT+ false;+ """,+ migrations.RunSQL.noop,+ ),+ ]diff --git a/saleor/checkout/migrations/0054_alter_checkout_options.py b/saleor/checkout/migrations/0054_alter_checkout_options.pynew file mode 100644index 0000000000..5235c9fa6d--- /dev/null+++ b/saleor/checkout/migrations/0054_alter_checkout_options.py@@ -0,0 +1,58 @@+# Generated by Django 3.2.15 on 2022-08-26 08:14++from django.apps import apps as registry+from django.db import migrations+from django.db.models.signals import post_migrate+++def assign_permissions(apps, schema_editor):+ def on_migrations_complete(sender=None, **kwargs):+ Permission = apps.get_model("auth", "Permission")+ App = apps.get_model("app", "App")+ Group = apps.get_model("auth", "Group")++ manage_taxes = Permission.objects.filter(+ codename="manage_taxes", content_type__app_label="checkout"+ ).first()++ manage_checkouts = Permission.objects.filter(+ codename="manage_checkouts", content_type__app_label="checkout"+ ).first()++ apps_qs = App.objects.filter(+ permissions=manage_checkouts,+ )+ for app in apps_qs.iterator():+ app.permissions.add(manage_taxes)++ groups = Group.objects.filter(+ permissions=manage_checkouts,+ )+ for group in groups.iterator():+ group.permissions.add(manage_taxes)++ sender = registry.get_app_config("checkout")+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)+++class Migration(migrations.Migration):++ dependencies = [+ ("checkout", "0053_checkout_tax_exemption"),+ ]++ operations = [+ migrations.AlterModelOptions(+ name="checkout",+ options={+ "ordering": ("-last_change", "pk"),+ "permissions": (+ ("manage_checkouts", "Manage checkouts"),+ ("handle_checkouts", "Handle checkouts"),+ ("handle_taxes", "Handle taxes"),+ ("manage_taxes", "Manage taxes"),+ ),+ },+ ),+ migrations.RunPython(assign_permissions, migrations.RunPython.noop),+ ]diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex e68369ae54..6956128851 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -159,12 +159,15 @@ class Checkout(ModelWithMetadata):max_length=35, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE)+ tax_exemption = models.BooleanField(default=False)+class Meta(ModelWithMetadata.Meta):ordering = ("-last_change", "pk")permissions = ((CheckoutPermissions.MANAGE_CHECKOUTS.codename, "Manage checkouts"),(CheckoutPermissions.HANDLE_CHECKOUTS.codename, "Handle checkouts"),(CheckoutPermissions.HANDLE_TAXES.codename, "Handle taxes"),+ (CheckoutPermissions.MANAGE_TAXES.codename, "Manage taxes"),)def __iter__(self):diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.pyindex 81f4f88238..6b73428d13 100644--- a/saleor/checkout/tests/test_calculations.py+++ b/saleor/checkout/tests/test_calculations.py@@ -9,6 +9,11 @@ from prices import Money, TaxedMoneyfrom ...core.prices import quantize_pricefrom ...core.taxes import TaxData, TaxLineData, zero_taxed_money+from ...plugins.manager import get_plugins_manager+from ..base_calculations import (+ base_checkout_delivery_price,+ calculate_base_line_total_price,+)from ..calculations import _apply_tax_data_from_app, fetch_checkout_prices_if_expiredfrom ..fetch import CheckoutLineInfo, fetch_checkout_info, fetch_checkout_lines@@ -199,3 +204,124 @@ def test_fetch_checkout_prices_if_expired_webhooks_success(for checkout_line, tax_line in zip(checkout_with_items.lines.all(), tax_data.lines):assert checkout_line.total_price == get_taxed_money(tax_line, "total", currency)assert checkout_line.tax_rate == tax_line.tax_rate / 100+++@freeze_time("2020-12-12 12:00:00")+def test_fetch_checkout_prices_when_tax_exemption_and_include_taxes_in_prices(+ checkout_with_items_and_shipping, settings, site_settings+):+ """Test tax exemption when taxes are included in prices.++ Use PluginSample to test tax exemption.+ PluginSample always return same values of calculated taxes:++ shipping_price_net_amount = 50+ shipping_price_gross_amount = 63.20++ Each line is treated as line with 3 units where unite gross value = 12.30 and net+ value = 10+ """+ # given+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]+ manager = get_plugins_manager()++ checkout = checkout_with_items_and_shipping+ checkout.price_expiration = timezone.now()+ checkout.tax_exemption = True+ checkout.save(update_fields=["price_expiration", "tax_exemption"])++ currency = checkout.currency++ discounts = []+ lines_info, _ = fetch_checkout_lines(checkout)++ fetch_kwargs = {+ "checkout_info": fetch_checkout_info(checkout, lines_info, discounts, manager),+ "manager": manager,+ "lines": lines_info,+ "site_settings": site_settings,+ "address": checkout.shipping_address or checkout.billing_address,+ "discounts": discounts,+ }++ # when+ fetch_checkout_prices_if_expired(**fetch_kwargs)+ checkout.refresh_from_db()++ # then++ one_line_total_price = TaxedMoney(+ net=Money("30.0", currency), gross=Money("30.0", currency)+ )+ all_lines_total_price = len(lines_info) * one_line_total_price+ shipping_price = TaxedMoney(+ net=Money("50.0", currency), gross=Money("50.0", currency)+ )++ for line in checkout.lines.all():+ assert line.total_price == one_line_total_price+ assert line.tax_rate == 0++ assert checkout.shipping_price == shipping_price+ assert checkout.shipping_tax_rate == 0++ assert checkout.total == shipping_price + all_lines_total_price+ assert checkout.subtotal == all_lines_total_price+++@freeze_time("2020-12-12 12:00:00")+def test_fetch_checkout_prices_when_tax_exemption_and_not_include_taxes_in_prices(+ checkout_with_items_and_shipping, settings, site_settings+):+ """Test tax exemption when taxes are not included in prices.++ When Checkout.tax_exemption = True and SiteSettings.include_taxes_in_prices = False+ tax plugins should be ignored and only net prices should be calculated and returned.+ """+ # given+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]+ manager = get_plugins_manager()++ checkout = checkout_with_items_and_shipping+ checkout.price_expiration = timezone.now()+ checkout.tax_exemption = True+ checkout.save(update_fields=["price_expiration", "tax_exemption"])+ site_settings.include_taxes_in_prices = False+ site_settings.save(update_fields=["include_taxes_in_prices"])+ currency = checkout.currency++ discounts = []+ lines_info, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines_info, discounts, manager)+ fetch_kwargs = {+ "checkout_info": checkout_info,+ "manager": manager,+ "lines": lines_info,+ "site_settings": site_settings,+ "address": checkout.shipping_address or checkout.billing_address,+ "discounts": discounts,+ }++ # when+ fetch_checkout_prices_if_expired(**fetch_kwargs)+ checkout.refresh_from_db()++ # then+ one_line_total_prices = [+ calculate_base_line_total_price(line_info, checkout_info.channel, discounts)+ for line_info in lines_info+ ]+ all_lines_total_price = sum(one_line_total_prices, zero_taxed_money(currency))+ shipping_price = base_checkout_delivery_price(checkout_info, lines_info)+ shipping_price = quantize_price(+ TaxedMoney(shipping_price, shipping_price), currency+ )++ for line in checkout.lines.all():+ assert line.tax_rate == 0++ assert checkout.shipping_price == shipping_price+ assert checkout.shipping_tax_rate == 0++ assert checkout.total == shipping_price + all_lines_total_price+ assert checkout.subtotal == all_lines_total_pricediff --git a/saleor/core/permissions/enums.py b/saleor/core/permissions/enums.pyindex 2ef7005825..48e7e58c9d 100644--- a/saleor/core/permissions/enums.py+++ b/saleor/core/permissions/enums.py@@ -46,6 +46,7 @@ class CheckoutPermissions(BasePermissionEnum):MANAGE_CHECKOUTS = "checkout.manage_checkouts"HANDLE_CHECKOUTS = "checkout.handle_checkouts"HANDLE_TAXES = "checkout.handle_taxes"+ MANAGE_TAXES = "checkout.manage_taxes"class OrderPermissions(BasePermissionEnum):@@ -84,6 +85,7 @@ class SitePermissions(BasePermissionEnum):PERMISSIONS_ENUMS = [AccountPermissions,AppPermission,+ CheckoutPermissions,ChannelPermissions,DiscountPermissions,PluginsPermissions,@@ -97,7 +99,6 @@ PERMISSIONS_ENUMS = [ProductTypePermissions,ShippingPermissions,SitePermissions,- CheckoutPermissions,]diff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex ee3191e899..5f52217b35 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -23,6 +23,7 @@ from .plugins.schema import PluginsMutations, PluginsQueriesfrom .product.schema import ProductMutations, ProductQueriesfrom .shipping.schema import ShippingMutations, ShippingQueriesfrom .shop.schema import ShopMutations, ShopQueries+from .tax.schema import TaxMutationsfrom .translations.schema import TranslationQueriesfrom .warehouse.schema import StockQueries, WarehouseMutations, WarehouseQueriesfrom .webhook.schema import WebhookMutations, WebhookQueries@@ -78,6 +79,7 @@ class Mutation(ProductMutations,ShippingMutations,ShopMutations,+ TaxMutations,WarehouseMutations,WebhookMutations,):diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.pyindex 9cbe71dd56..9aab1d3722 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py@@ -236,6 +236,7 @@ def test_checkout_complete(checkout.billing_address = addresscheckout.store_value_in_metadata(items={"accepted": "true"})checkout.store_value_in_private_metadata(items={"accepted": "false"})+ checkout.tax_exemption = Truecheckout.save()checkout_line = checkout.lines.first()diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex 69cad29aec..b34466955e 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -26,6 +26,7 @@ from ..core.connection import CountableConnectionfrom ..core.descriptions import (ADDED_IN_31,ADDED_IN_34,+ ADDED_IN_38,DEPRECATED_IN_3X_FIELD,PREVIEW_FEATURE,)@@ -225,13 +226,10 @@ class CheckoutLine(ModelObjectType):lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(checkout.token)+ site = load_site(info.context)def calculate_line_total_price(data):- (- discounts,- checkout_info,- lines,- ) = data+ (discounts, checkout_info, lines, site) = datafor line_info in lines:if line_info.line.pk == root.pk:return calculations.checkout_line_total(@@ -240,16 +238,13 @@ class CheckoutLine(ModelObjectType):lines=lines,checkout_line_info=line_info,discounts=discounts,+ site_settings=site.settings,)return None- return Promise.all(- [- discounts,- checkout_info,- lines,- ]- ).then(calculate_line_total_price)+ return Promise.all([discounts, checkout_info, lines, site]).then(+ calculate_line_total_price+ )return (CheckoutByTokenLoader(info.context)@@ -415,6 +410,14 @@ class Checkout(ModelObjectType):description="The price of the checkout before shipping, with taxes included.",required=True,)+ tax_exemption = graphene.Boolean(+ description=(+ "Returns True if checkout has to be exempt from taxes."+ + ADDED_IN_38+ + PREVIEW_FEATURE+ ),+ required=True,+ )token = graphene.Field(UUID, description="The checkout's token.", required=True)total_price = graphene.Field(TaxedMoney,@@ -529,13 +532,14 @@ class Checkout(ModelObjectType):# TODO: We should optimize it in/after PR#5819def resolve_total_price(root: models.Checkout, info):def calculate_total_price(data):- address, lines, checkout_info, discounts = data+ address, lines, checkout_info, discounts, site = datataxed_total = calculations.calculate_checkout_total_with_gift_cards(manager=info.context.plugins,checkout_info=checkout_info,lines=lines,address=address,discounts=discounts,+ site_settings=site.settings,)return max(taxed_total, zero_taxed_money(root.currency))@@ -548,7 +552,8 @@ class Checkout(ModelObjectType):discounts = DiscountsByDateTimeLoader(info.context).load(info.context.request_time)- return Promise.all([address, lines, checkout_info, discounts]).then(+ site = load_site(info.context)+ return Promise.all([address, lines, checkout_info, discounts, site]).then(calculate_total_price)@@ -557,13 +562,14 @@ class Checkout(ModelObjectType):# TODO: We should optimize it in/after PR#5819def resolve_subtotal_price(root: models.Checkout, info):def calculate_subtotal_price(data):- address, lines, checkout_info, discounts = data+ address, lines, checkout_info, discounts, site = datareturn calculations.checkout_subtotal(manager=info.context.plugins,checkout_info=checkout_info,lines=lines,address=address,discounts=discounts,+ site_settings=site.settings,)address_id = root.shipping_address_id or root.billing_address_id@@ -575,7 +581,9 @@ class Checkout(ModelObjectType):discounts = DiscountsByDateTimeLoader(info.context).load(info.context.request_time)- return Promise.all([address, lines, checkout_info, discounts]).then(+ site = load_site(info.context)++ return Promise.all([address, lines, checkout_info, discounts, site]).then(calculate_subtotal_price)@@ -584,13 +592,14 @@ class Checkout(ModelObjectType):# TODO: We should optimize it in/after PR#5819def resolve_shipping_price(root: models.Checkout, info):def calculate_shipping_price(data):- address, lines, checkout_info, discounts = data+ address, lines, checkout_info, discounts, site = datareturn calculations.checkout_shipping_price(manager=info.context.plugins,checkout_info=checkout_info,lines=lines,address=address,discounts=discounts,+ site_settings=site.settings,)address = (@@ -603,7 +612,9 @@ class Checkout(ModelObjectType):discounts = DiscountsByDateTimeLoader(info.context).load(info.context.request_time)- return Promise.all([address, lines, checkout_info, discounts]).then(+ site = load_site(info.context)++ return Promise.all([address, lines, checkout_info, discounts, site]).then(calculate_shipping_price)diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex e92784f7c9..08de4d74dc 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -63,6 +63,7 @@ from ..core.connection import CountableConnectionfrom ..core.descriptions import (ADDED_IN_31,ADDED_IN_34,+ ADDED_IN_38,DEPRECATED_IN_3X_FIELD,PREVIEW_FEATURE,)@@ -877,6 +878,14 @@ class Order(ModelObjectType):description=("The charge status of the order." + ADDED_IN_34 + PREVIEW_FEATURE),required=True,)+ tax_exemption = graphene.Boolean(+ description=(+ "Returns True if order has to be exempt from taxes."+ + ADDED_IN_38+ + PREVIEW_FEATURE+ ),+ required=True,+ )transactions = NonNullList(TransactionItem,description=(diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 7b31925e21..3b3f5996c5 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2258,6 +2258,10 @@ enum PermissionEnum {IMPERSONATE_USERMANAGE_APPSMANAGE_OBSERVABILITY+ MANAGE_CHECKOUTS+ HANDLE_CHECKOUTS+ HANDLE_TAXES+ MANAGE_TAXESMANAGE_CHANNELSMANAGE_DISCOUNTSMANAGE_PLUGINS@@ -2272,9 +2276,6 @@ enum PermissionEnum {MANAGE_SHIPPINGMANAGE_SETTINGSMANAGE_TRANSLATIONS- MANAGE_CHECKOUTS- HANDLE_CHECKOUTS- HANDLE_TAXES}"""@@ -7902,6 +7903,15 @@ type Checkout implements Node & ObjectWithMetadata {"""The price of the checkout before shipping, with taxes included."""subtotalPrice: TaxedMoney!+ """+ Returns True if checkout has to be exempt from taxes.++ Added in Saleor 3.8.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ taxExemption: Boolean!+"""The checkout's token."""token: UUID!@@ -8521,6 +8531,15 @@ type Order implements Node & ObjectWithMetadata {"""chargeStatus: OrderChargeStatusEnum!+ """+ Returns True if order has to be exempt from taxes.++ Added in Saleor 3.8.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ taxExemption: Boolean!+"""List of transactions for the order. Requires one of the following permissions: MANAGE_ORDERS, HANDLE_PAYMENTS.@@ -10957,6 +10976,23 @@ type Mutation {shippingZoneIds: [ID!]!): WarehouseShippingZoneUnassign+ """+ Exempt checkout or order from charging the taxes. When tax exemption is enabled, taxes won't be charged for the checkout or order. Taxes may still be calculated in cases when product prices are entered with the tax included and the net price needs to be known.++ Added in Saleor 3.8.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.++ Requires one of the following permissions: MANAGE_TAXES.+ """+ taxExemptionManage(+ """ID of the Checkout or Order object."""+ id: ID!++ """Determines if a taxes should be exempt."""+ taxExemption: Boolean!+ ): TaxExemptionManage+"""Creates a new staff notification recipient.@@ -14728,6 +14764,43 @@ type WarehouseShippingZoneUnassign {warehouse: Warehouse}+"""+Exempt checkout or order from charging the taxes. When tax exemption is enabled, taxes won't be charged for the checkout or order. Taxes may still be calculated in cases when product prices are entered with the tax included and the net price needs to be known.++Added in Saleor 3.8.++Note: this API is currently in Feature Preview and can be subject to changes at later point.++Requires one of the following permissions: MANAGE_TAXES.+"""+type TaxExemptionManage {+ taxableObject: TaxSourceObject+ errors: [TaxExemptionManageError!]!+}++union TaxSourceObject = Checkout | Order++type TaxExemptionManageError {+ """+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.+ """+ field: String++ """The error message."""+ message: String++ """The error code."""+ code: TaxExemptionManageErrorCode!+}++"""An enumeration."""+enum TaxExemptionManageErrorCode {+ GRAPHQL_ERROR+ INVALID+ NOT_FOUND+ NOT_EDITABLE_ORDER+}+"""Creates a new staff notification recipient.@@ -24197,8 +24270,6 @@ type TaxableObject {channel: Channel!}-union TaxSourceObject = Checkout | Order-"""Taxable object discount."""type TaxableObjectDiscount {"""The name of the discount."""diff --git a/saleor/graphql/tax/__init__.py b/saleor/graphql/tax/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/graphql/tax/mutations/__init__.py b/saleor/graphql/tax/mutations/__init__.pynew file mode 100644index 0000000000..18003473b9--- /dev/null+++ b/saleor/graphql/tax/mutations/__init__.py@@ -0,0 +1,5 @@+# flake8: noqa: F401++from .tax_exemption_manage import TaxExemptionManage++__all__ = ["TaxExemptionManage"]diff --git a/saleor/graphql/tax/mutations/tax_exemption_manage.py b/saleor/graphql/tax/mutations/tax_exemption_manage.pynew file mode 100644index 0000000000..5c2b789028--- /dev/null+++ b/saleor/graphql/tax/mutations/tax_exemption_manage.py@@ -0,0 +1,105 @@+import graphene+from django.core.exceptions import ValidationError++from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from ....checkout.models import Checkout+from ....checkout.utils import invalidate_checkout_prices+from ....core.permissions import CheckoutPermissions+from ....graphql.core.mutations import BaseMutation+from ....order import ORDER_EDITABLE_STATUS+from ....order.models import Order+from ....tax import error_codes+from ...core.descriptions import ADDED_IN_38, PREVIEW_FEATURE+from ...core.types import Error+from ...core.types.taxes import TaxSourceObject+from ...discount.dataloaders import load_discounts++TaxExemptionManageErrorCode = graphene.Enum.from_enum(+ error_codes.TaxExemptionManageErrorCode+)+++class TaxExemptionManageError(Error):+ code = TaxExemptionManageErrorCode(description="The error code.", required=True)+++class TaxExemptionManage(BaseMutation):+ taxable_object = graphene.Field(TaxSourceObject)++ class Arguments:+ id = graphene.ID(+ description="ID of the Checkout or Order object.", required=True+ )+ tax_exemption = graphene.Boolean(+ description="Determines if a taxes should be exempt.", required=True+ )++ class Meta:+ description = (+ "Exempt checkout or order from charging the taxes. When tax exemption is "+ "enabled, taxes won't be charged for the checkout or order. Taxes may "+ "still be calculated in cases when product prices are entered with the "+ "tax included and the net price needs to be known."+ + ADDED_IN_38+ + PREVIEW_FEATURE+ )+ error_type_class = TaxExemptionManageError+ permissions = (CheckoutPermissions.MANAGE_TAXES,)++ @classmethod+ def validate_input(cls, info, data):+ obj = cls.get_node_or_error(info, data["id"])+ if not isinstance(obj, (Order, Checkout)):+ code = error_codes.TaxExemptionManageErrorCode.NOT_FOUND.value+ message = "Invalid object ID. Only Checkout and Order ID's are accepted."+ raise ValidationError({"id": ValidationError(code=code, message=message)})++ @classmethod+ def validate_order_status(cls, order):+ if order.status not in ORDER_EDITABLE_STATUS:+ code = error_codes.TaxExemptionManageErrorCode.NOT_EDITABLE_ORDER.value+ message = (+ "Tax exemption can be manage only on orders in "+ f"{ORDER_EDITABLE_STATUS} statuses."+ )+ raise ValidationError(code=code, message=message)++ @classmethod+ def get_object(cls, info, object_global_id):+ obj = graphene.Node.get_node_from_global_id(info, object_global_id)+ return obj++ @classmethod+ def _invalidate_checkout_prices(cls, info, checkout):+ discounts = load_discounts(info.context)++ checkout_info = fetch_checkout_info(+ checkout, [], discounts, info.context.plugins+ )+ lines_info, _ = fetch_checkout_lines(checkout)+ invalidate_checkout_prices(+ checkout_info,+ lines_info,+ info.context.plugins,+ discounts,+ save=False,+ )++ @classmethod+ def perform_mutation(cls, _root, info, **data):+ cls.validate_input(info, data)+ obj = cls.get_object(info, data["id"])+ obj.tax_exemption = data["tax_exemption"]++ if isinstance(obj, Checkout):+ cls._invalidate_checkout_prices(info, obj)+ obj.save(update_fields=["tax_exemption", "price_expiration", "last_change"])++ if isinstance(obj, Order):+ cls.validate_order_status(obj)+ obj.should_refresh_prices = True+ obj.save(+ update_fields=["tax_exemption", "should_refresh_prices", "updated_at"]+ )++ return TaxExemptionManage(taxable_object=obj)diff --git a/saleor/graphql/tax/schema.py b/saleor/graphql/tax/schema.pynew file mode 100644index 0000000000..4f56cf5f7c--- /dev/null+++ b/saleor/graphql/tax/schema.py@@ -0,0 +1,7 @@+import graphene++from .mutations import TaxExemptionManage+++class TaxMutations(graphene.ObjectType):+ tax_exemption_manage = TaxExemptionManage.Field()diff --git a/saleor/graphql/tax/tests/__init__.py b/saleor/graphql/tax/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/graphql/tax/tests/mutations/__init__.py b/saleor/graphql/tax/tests/mutations/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/graphql/tax/tests/mutations/test_tax_exemption_manage.py b/saleor/graphql/tax/tests/mutations/test_tax_exemption_manage.pynew file mode 100644index 0000000000..32de144a0a--- /dev/null+++ b/saleor/graphql/tax/tests/mutations/test_tax_exemption_manage.py@@ -0,0 +1,140 @@+import graphene+from django.utils import timezone+from freezegun import freeze_time++from .....order import OrderStatus+from .....tax.error_codes import TaxExemptionManageErrorCode+from ....tests.utils import get_graphql_content++TAX_EXEMPTION_MUTATION = """+ mutation manageTaxExemption($id: ID!, $taxExemption: Boolean!) {+ taxExemptionManage(id: $id, taxExemption: $taxExemption) {+ taxableObject {+ ...on Checkout {+ id+ taxExemption+ },+ ...on Order {+ id+ taxExemption+ }+ }+ errors {+ field+ code+ message+ }+ }+ }+"""+++@freeze_time("2022-05-12 12:00:00")+def test_tax_exemption_manage_for_checkout_as_staff(+ staff_api_client, checkout, permission_manage_taxes+):+ # given+ global_id = graphene.Node.to_global_id("Checkout", checkout.token)+ variables = {"id": global_id, "taxExemption": True}++ # when+ response = staff_api_client.post_graphql(+ TAX_EXEMPTION_MUTATION, variables, permissions=[permission_manage_taxes]+ )+ content = get_graphql_content(response)+ data = content["data"]["taxExemptionManage"]+ checkout.refresh_from_db()++ # then+ assert data["taxableObject"]["id"] == global_id+ assert data["taxableObject"]["taxExemption"]+ assert checkout.price_expiration == timezone.now()+++@freeze_time("2022-05-12 12:00:00")+def test_tax_exemption_manage_for_checkout_as_app(+ app_api_client, checkout, permission_manage_taxes+):+ # given+ global_id = graphene.Node.to_global_id("Checkout", checkout.token)+ variables = {"id": global_id, "taxExemption": True}++ # when+ response = app_api_client.post_graphql(+ TAX_EXEMPTION_MUTATION, variables, permissions=[permission_manage_taxes]+ )+ content = get_graphql_content(response)+ data = content["data"]["taxExemptionManage"]+ checkout.refresh_from_db()++ # then+ assert data["taxableObject"]["id"] == global_id+ assert data["taxableObject"]["taxExemption"]+ assert checkout.price_expiration == timezone.now()+++def test_tax_exemption_manage_for_order(+ staff_api_client, order_unconfirmed, permission_manage_taxes+):+ # given+ assert not order_unconfirmed.should_refresh_prices+ global_id = graphene.Node.to_global_id("Order", order_unconfirmed.id)+ variables = {"id": global_id, "taxExemption": True}++ # when+ response = staff_api_client.post_graphql(+ TAX_EXEMPTION_MUTATION, variables, permissions=[permission_manage_taxes]+ )+ content = get_graphql_content(response)+ data = content["data"]["taxExemptionManage"]+ order_unconfirmed.refresh_from_db()++ # then+ assert data["taxableObject"]["id"] == global_id+ assert data["taxableObject"]["taxExemption"]+ assert order_unconfirmed.should_refresh_prices+++def test_tax_exemption_manage_return_error_when_invalid_object_id(+ staff_api_client, product, permission_manage_taxes+):+ # given+ global_id = graphene.Node.to_global_id("Product", product.id)+ variables = {"id": global_id, "taxExemption": True}++ # when+ response = staff_api_client.post_graphql(+ TAX_EXEMPTION_MUTATION, variables, permissions=[permission_manage_taxes]+ )+ content = get_graphql_content(response)+ data = content["data"]["taxExemptionManage"]++ # then+ assert data["errors"][0]["field"] == "id"+ assert data["errors"][0]["code"] == TaxExemptionManageErrorCode.NOT_FOUND.name+ assert not data["taxableObject"]+++def test_tax_exemption_manage_return_error_when_invalid_order_status(+ staff_api_client, order, permission_manage_taxes+):+ # given+ order.status = OrderStatus.FULFILLED+ order.save(update_fields=["status"])++ global_id = graphene.Node.to_global_id("Order", order.id)+ variables = {"id": global_id, "taxExemption": True}++ # when+ response = staff_api_client.post_graphql(+ TAX_EXEMPTION_MUTATION, variables, permissions=[permission_manage_taxes]+ )+ content = get_graphql_content(response)+ data = content["data"]["taxExemptionManage"]++ # then+ assert data["errors"]+ assert not data["taxableObject"]+ assert (+ data["errors"][0]["code"] == TaxExemptionManageErrorCode.NOT_EDITABLE_ORDER.name+ )diff --git a/saleor/order/calculations.py b/saleor/order/calculations.pyindex 8fa309a568..b599fbb38b 100644--- a/saleor/order/calculations.py+++ b/saleor/order/calculations.py@@ -1,17 +1,23 @@from decimal import Decimal-from typing import Iterable, Optional, Tuple+from typing import TYPE_CHECKING, Iterable, Optional, Tuplefrom django.db import transactionfrom django.db.models import prefetch_related_objectsfrom prices import Money, TaxedMoney+from ..checkout import base_calculationsfrom ..core.prices import quantize_pricefrom ..core.taxes import TaxData, TaxError, zero_taxed_money+from ..order import base_calculations as base_order_calculationsfrom ..plugins.manager import PluginsManager+from ..site.models import Sitefrom . import ORDER_EDITABLE_STATUSfrom .interface import OrderTaxedPricesDatafrom .models import Order, OrderLine+if TYPE_CHECKING:+ from ..site.models import SiteSettings+def _recalculate_order_prices(manager: PluginsManager, order: Order, lines: Iterable[OrderLine]@@ -61,6 +67,66 @@ def _recalculate_order_prices(order.total = manager.calculate_order_total(order, lines)+def _get_order_base_prices(order, lines):+ currency = order.currency+ undiscounted_subtotal = zero_taxed_money(currency)++ for line in lines:+ variant = line.variant+ if variant:+ try:+ line_unit_default = OrderTaxedPricesData(+ undiscounted_price=TaxedMoney(+ line.undiscounted_base_unit_price,+ line.undiscounted_base_unit_price,+ ),+ price_with_discounts=TaxedMoney(+ line.base_unit_price,+ line.base_unit_price,+ ),+ )+ line_unit_default.price_with_discounts = quantize_price(+ line_unit_default.price_with_discounts, currency+ )+ line_unit_default.undiscounted_price = quantize_price(+ line_unit_default.undiscounted_price, currency+ )++ line.undiscounted_unit_price = line_unit_default.undiscounted_price+ line.unit_price = line_unit_default.price_with_discounts++ line_total = base_order_calculations.base_order_line_total(line)+ line_total.price_with_discounts = quantize_price(+ line_total.price_with_discounts, currency+ )+ line_total.undiscounted_price = quantize_price(+ line_total.undiscounted_price, currency+ )++ line.undiscounted_total_price = line_total.undiscounted_price+ undiscounted_subtotal += line_total.undiscounted_price+ line.total_price = line_total.price_with_discounts++ line.tax_rate = base_calculations.base_tax_rate(line.unit_price)+ except TaxError:+ pass++ try:+ shipping_price = base_order_calculations.base_order_shipping(order)+ order.shipping_price = quantize_price(+ TaxedMoney(net=shipping_price, gross=shipping_price),+ shipping_price.currency,+ )+ order.shipping_tax_rate = base_calculations.base_tax_rate(order.shipping_price)+ except TaxError:+ pass++ order.undiscounted_total = undiscounted_subtotal + order.shipping_price++ total = base_order_calculations.base_order_total(order, lines)+ order.total = quantize_price(TaxedMoney(total, total), currency)++def _apply_tax_data(order: Order, lines: Iterable[OrderLine], tax_data: TaxData) -> None:@@ -99,6 +165,7 @@ def fetch_order_prices_if_expired(manager: PluginsManager,lines: Optional[Iterable[OrderLine]] = None,force_update: bool = False,+ site_settings: "SiteSettings" = None,) -> Tuple[Order, Optional[Iterable[OrderLine]]]:"""Fetch order prices with taxes.@@ -114,6 +181,9 @@ def fetch_order_prices_if_expired(if not force_update and not order.should_refresh_prices:return order, lines+ if site_settings is None:+ site_settings = Site.objects.get_current().settings+if lines is None:lines = list(order.lines.select_related("variant__product__product_type"))else:@@ -121,14 +191,20 @@ def fetch_order_prices_if_expired(order.should_refresh_prices = False- _recalculate_order_prices(manager, order, lines)+ if order.tax_exemption and not site_settings.include_taxes_in_prices:+ _get_order_base_prices(order, lines)+ else:+ _recalculate_order_prices(manager, order, lines)- tax_data = manager.get_taxes_for_order(order)+ tax_data = manager.get_taxes_for_order(order)- with transaction.atomic(savepoint=False):if tax_data:_apply_tax_data(order, lines, tax_data)+ if order.tax_exemption and site_settings.include_taxes_in_prices:+ _exempt_taxes_in_order(order, lines)++ with transaction.atomic(savepoint=False):order.save(update_fields=["total_net_amount",@@ -158,6 +234,24 @@ def fetch_order_prices_if_expired(return order, lines+def _exempt_taxes_in_order(order, lines):+ order.total_gross_amount = order.total_net_amount+ order.undiscounted_total_gross_amount = order.undiscounted_total_net_amount+ order.shipping_price_gross_amount = order.shipping_price_net_amount+ order.shipping_tax_rate = Decimal("0.00")++ for line in lines:+ total_price_net_amount = line.total_price_net_amount+ unit_price_net_amount = line.unit_price_net_amount+ undiscounted_unit_price_net_amount = line.undiscounted_unit_price_net_amount+ undiscounted_total_price_net_amount = line.undiscounted_total_price_net_amount+ line.unit_price_gross_amount = unit_price_net_amount+ line.undiscounted_unit_price_gross_amount = undiscounted_unit_price_net_amount+ line.total_price_gross_amount = total_price_net_amount+ line.undiscounted_total_price_gross_amount = undiscounted_total_price_net_amount+ line.tax_rate = Decimal("0.00")++def _find_order_line(lines: Optional[Iterable[OrderLine]],order_line: OrderLine,diff --git a/saleor/order/migrations/0156_order_tax_exemption.py b/saleor/order/migrations/0156_order_tax_exemption.pynew file mode 100644index 0000000000..2bb0ebf758--- /dev/null+++ b/saleor/order/migrations/0156_order_tax_exemption.py@@ -0,0 +1,25 @@+# Generated by Django 3.2.14 on 2022-08-03 09:03++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("order", "0155_order_should_refresh_prices"),+ ]++ operations = [+ migrations.AddField(+ model_name="order",+ name="tax_exemption",+ field=models.BooleanField(default=False),+ ),+ migrations.RunSQL(+ """+ ALTER TABLE order_order ALTER COLUMN tax_exemption SET DEFAULT+ false;+ """,+ migrations.RunSQL.noop,+ ),+ ]diff --git a/saleor/order/models.py b/saleor/order/models.pyindex d056c4226a..375c8326fc 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -291,6 +291,8 @@ class Order(ModelWithMetadata):search_vector = SearchVectorField(blank=True, null=True)# this field is used only for draft/unconfirmed ordersshould_refresh_prices = models.BooleanField(default=True)+ tax_exemption = models.BooleanField(default=False)+objects = models.Manager.from_queryset(OrderQueryset)()class Meta:diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.pyindex 03e4c28ef2..405b56eda1 100644--- a/saleor/order/tests/test_calculations.py+++ b/saleor/order/tests/test_calculations.py@@ -9,6 +9,7 @@ from ...core.prices import quantize_pricefrom ...core.taxes import TaxData, TaxError, TaxLineData, zero_taxed_moneyfrom ...plugins.manager import get_plugins_managerfrom .. import OrderStatus, calculations+from ..base_calculations import base_order_shippingfrom ..interface import OrderTaxedPricesData@@ -406,11 +407,16 @@ def get_taxed_money(obj: Union[TaxData, TaxLineData],attr: Literal["unit", "total", "subtotal", "shipping_price"],currency: str,+ exempt_taxes: bool = False,) -> TaxedMoney:- return TaxedMoney(- Money(getattr(obj, f"{attr}_net_amount"), currency),- Money(getattr(obj, f"{attr}_gross_amount"), currency),- )+ net_value = Money(getattr(obj, f"{attr}_net_amount"), currency)++ if exempt_taxes:+ gross_value = net_value+ else:+ gross_value = Money(getattr(obj, f"{attr}_gross_amount"), currency)++ return TaxedMoney(net_value, gross_value)def get_order_priced_taxes_data(@@ -550,6 +556,154 @@ def test_fetch_order_prices_if_expired_recalculate_all_prices(assert order_with_lines.total == subtotal + shipping_price+def test_fetch_order_prices_when_tax_exemption_and_include_taxes_in_prices(+ plugins_manager,+ fetch_kwargs,+ order_with_lines,+ tax_data,+):+ """Test tax exemption when taxes are included in prices.++ When Order.tax_exemption = True and SiteSettings.include_taxes_in_prices = True+ taxes should be calculated by plugins and net prices returned.+ """+ # given+ currency = order_with_lines.currency+ discount_amount = Decimal("3.00")+ order_with_lines.discounts.create(+ value=discount_amount,+ amount_value=discount_amount,+ currency=order_with_lines.currency,+ )+ order_with_lines.total_net_amount = Decimal("0.00")+ order_with_lines.total_gross_amount = Decimal("0.00")+ order_with_lines.undiscounted_total_net_amount = Decimal("0.00")+ order_with_lines.undiscounted_total_gross_amount = Decimal("0.00")+ order_with_lines.tax_exemption = True+ order_with_lines.save()+ plugins_manager.get_taxes_for_order = Mock(return_value=tax_data)++ # when+ calculations.fetch_order_prices_if_expired(**fetch_kwargs)++ # then+ order_with_lines.refresh_from_db()+ shipping_price = get_taxed_money(+ tax_data, "shipping_price", currency, exempt_taxes=True+ )+ assert order_with_lines.shipping_price == shipping_price+ assert order_with_lines.shipping_tax_rate == Decimal("0.00")+ subtotal = zero_taxed_money(currency)+ undiscounted_subtotal = zero_taxed_money(currency)++ for order_line, tax_line in zip(order_with_lines.lines.all(), tax_data.lines):+ line_total = get_taxed_money(tax_line, "total", currency, exempt_taxes=True)+ subtotal += line_total+ undiscounted_subtotal += order_line.undiscounted_total_price+ assert order_line.total_price == line_total+ assert order_line.unit_price == line_total / order_line.quantity+ assert order_line.tax_rate == Decimal("0.00")++ assert (+ order_with_lines.undiscounted_total+ == undiscounted_subtotal + shipping_price.net+ )+ assert order_with_lines.total == subtotal + shipping_price+++def test_fetch_order_prices_when_tax_exemption_and_not_include_taxes_in_prices(+ plugins_manager, fetch_kwargs, order_with_lines, tax_data, site_settings+):+ """Test tax exemption when taxes are not included in prices.++ When Order.tax_exemption = True and SiteSettings.include_taxes_in_prices = False+ tax plugins should be ignored and only net prices should be calculated and returned.+ """+ # given+ currency = order_with_lines.currency+ discount_amount = Decimal("3.00")+ discount_as_money = Money(discount_amount, currency)+ order_with_lines.discounts.create(+ value=discount_amount,+ amount_value=discount_amount,+ currency=order_with_lines.currency,+ )+ order_with_lines.total_net_amount = Decimal("0.00")+ order_with_lines.total_gross_amount = Decimal("0.00")+ order_with_lines.undiscounted_total_net_amount = Decimal("0.00")+ order_with_lines.undiscounted_total_gross_amount = Decimal("0.00")+ order_with_lines.tax_exemption = True+ order_with_lines.save()++ site_settings.include_taxes_in_prices = False+ site_settings.save(update_fields=["include_taxes_in_prices"])++ plugins_manager.get_taxes_for_order = Mock(return_value=tax_data)++ # when+ calculations.fetch_order_prices_if_expired(**fetch_kwargs)++ # then+ order_with_lines.refresh_from_db()++ subtotal = zero_taxed_money(currency)+ undiscounted_subtotal = zero_taxed_money(currency)+ shipping_price = base_order_shipping(order_with_lines)+ shipping_price = quantize_price(+ TaxedMoney(+ shipping_price,+ shipping_price,+ ),+ currency,+ )++ assert order_with_lines.shipping_price == shipping_price+ assert order_with_lines.shipping_tax_rate == Decimal("0.00")++ for order_line in order_with_lines.lines.all():+ line_price_with_discounts = quantize_price(+ TaxedMoney(+ order_line.base_unit_price,+ order_line.base_unit_price,+ ),+ currency,+ )+ undiscounted_line_price = quantize_price(+ TaxedMoney(+ order_line.undiscounted_base_unit_price,+ order_line.undiscounted_base_unit_price,+ ),+ currency,+ )++ line_total = line_price_with_discounts * order_line.quantity+ undiscounted_total_price = undiscounted_line_price * order_line.quantity++ subtotal += line_total+ undiscounted_subtotal += order_line.undiscounted_total_price++ assert order_line.total_price == line_total+ assert order_line.undiscounted_total_price == undiscounted_total_price+ assert order_line.unit_price == line_total / order_line.quantity+ assert order_line.tax_rate == Decimal("0.00")++ assert (+ order_with_lines.undiscounted_total+ == undiscounted_subtotal + shipping_price.net+ )+ assert order_with_lines.total == (+ subtotal+ + shipping_price+ - quantize_price(+ TaxedMoney(+ discount_as_money,+ discount_as_money,+ ),+ currency,+ )+ )++def test_fetch_order_prices_if_expired_prefetch(fetch_kwargs, order_lines):# whencalculations.fetch_order_prices_if_expired(**fetch_kwargs)diff --git a/saleor/payment/gateways/stripe/tests/test_plugin.py b/saleor/payment/gateways/stripe/tests/test_plugin.pyindex fc55139ae4..99a54d1274 100644--- a/saleor/payment/gateways/stripe/tests/test_plugin.py+++ b/saleor/payment/gateways/stripe/tests/test_plugin.py@@ -7,6 +7,7 @@ from stripe.error import AuthenticationError, StripeErrorfrom stripe.stripe_object import StripeObjectfrom .....plugins.models import PluginConfiguration+from .....site.models import Sitefrom .... import TransactionKindfrom ....interface import GatewayResponse, PaymentMethodInfo, StorePaymentMethodEnumfrom ....utils import (@@ -956,9 +957,13 @@ def test_process_payment_with_disabled_order_auto_confirmation(mocked_payment_intent,stripe_plugin,payment_stripe_for_checkout,- site_settings,channel_USD,):++ site_settings = Site.objects.get_current().settings+ site_settings.automatically_confirm_all_new_orders = False+ site_settings.save(update_fields=["automatically_confirm_all_new_orders"])+payment_intent = Mock()mocked_payment_intent.return_value = payment_intentclient_secret = "client-secret"@@ -976,8 +981,7 @@ def test_process_payment_with_disabled_order_auto_confirmation(payment_info = create_payment_information(payment_stripe_for_checkout,)- site_settings.automatically_confirm_all_new_orders = False- site_settings.save()+response = plugin.process_payment(payment_info, None)assert response.is_success is Truediff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 1e8a4e0583..1c6932f162 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -268,7 +268,7 @@ class PluginsManager(PaymentInterface):total = sum(line_totals, zero_taxed_money(currency))return quantize_price(total,- checkout_info.checkout.currency,+ currency,)def calculate_checkout_shipping(@@ -398,8 +398,8 @@ class PluginsManager(PaymentInterface):discounts,channel_slug=checkout_info.channel.slug,)- currency = checkout_info.checkout.currency- return quantize_price(line_total, currency)++ return quantize_price(line_total, checkout_info.checkout.currency)def calculate_order_line_total(self,@@ -409,6 +409,8 @@ class PluginsManager(PaymentInterface):product: "Product",) -> OrderTaxedPricesData:default_value = base_order_calculations.base_order_line_total(order_line)+ currency = order_line.currency+line_total = self.__run_method_on_plugins("calculate_order_line_total",default_value,@@ -418,7 +420,7 @@ class PluginsManager(PaymentInterface):product,channel_slug=order.channel.slug,)- currency = order_line.currency+line_total.price_with_discounts = quantize_price(line_total.price_with_discounts, currency)@@ -449,8 +451,7 @@ class PluginsManager(PaymentInterface):discounts,channel_slug=checkout_info.channel.slug,)- currency = checkout_info.checkout.currency- return quantize_price(unit_price, currency)+ return quantize_price(unit_price, checkout_info.checkout.currency)def calculate_order_line_unit(self,diff --git a/saleor/settings.py b/saleor/settings.pyindex d7cbc1fe9d..db9e957945 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -239,6 +239,7 @@ INSTALLED_APPS = ["saleor.warehouse","saleor.webhook","saleor.app",+ "saleor.tax","saleor.thumbnail","saleor.schedulers",# External appsdiff --git a/saleor/tax/__init__.py b/saleor/tax/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/tax/error_codes.py b/saleor/tax/error_codes.pynew file mode 100644index 0000000000..7aa2e20469--- /dev/null+++ b/saleor/tax/error_codes.py@@ -0,0 +1,8 @@+from enum import Enum+++class TaxExemptionManageErrorCode(Enum):+ GRAPHQL_ERROR = "graphql_error"+ INVALID = "invalid"+ NOT_FOUND = "not_found"+ NOT_EDITABLE_ORDER = "not_editable_order"diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 3862342263..e2dfb2c01f 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -323,6 +323,13 @@ def checkout_with_item(checkout, product):return checkout+def checkout_with_item_and_tax_exemption(checkout_with_item):+ checkout_with_item.tax_exemption = True+ checkout_with_item.save(update_fields=["tax_exemption"])+ return checkout_with_item++@pytest.fixturedef checkout_with_same_items_in_multiple_lines(checkout, product):variant = product.variants.first()@@ -1960,6 +1967,11 @@ def permission_manage_observability():return Permission.objects.get(codename="manage_observability")+def permission_manage_taxes():+ return Permission.objects.get(codename="manage_taxes")++@pytest.fixturedef product_type(color_attribute, size_attribute):product_type = ProductType.objects.create(