Skip to content

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

Add order shipping tax rate (#6678)

Iga Karbowiak693eb302968c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6502b93f1b..142448556f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Drop authorization keys API - #6631 by @maarcingebala
- Add metadata to menu and menu item - #6648 by @tomaszszymanski129
- Get tax rate from plugins - #6649 by @IKarbowiak
+- Add order shipping tax rate - #6678 by @IKarbowiak
# 2.11.1
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index fb925a9939..e6339ebcc9 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -83,11 +83,11 @@ def base_checkout_line_total(
return TaxedMoney(net=price, gross=price)
-def base_tax_rate(unit_price: TaxedMoney):
+def base_tax_rate(price: TaxedMoney):
tax_rate = Decimal("0.0")
# The condition will return False when unit_price.gross is 0.0
- if not isinstance(unit_price, Decimal) and unit_price.gross:
- tax_rate = unit_price.tax / unit_price.net
+ if not isinstance(price, Decimal) and price.gross:
+ tax_rate = price.tax / price.net
return tax_rate
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index a8fda6c8c2..80b826c666 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -285,6 +285,9 @@ def _prepare_order_data(
shipping_total = manager.calculate_checkout_shipping(
checkout, lines, address, discounts
)
+ shipping_tax_rate = manager.get_checkout_shipping_tax_rate(
+ checkout, lines, address, discounts, shipping_total
+ )
order_data.update(
_process_shipping_data_for_order(checkout, shipping_total, manager, lines)
)
@@ -294,6 +297,7 @@ def _prepare_order_data(
"language_code": get_language(),
"tracking_client_id": checkout.tracking_code or "",
"total": taxed_total,
+ "shipping_tax_rate": shipping_tax_rate,
}
)
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 037968bc01..550e97923b 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -259,7 +259,11 @@ class OrderUpdateShipping(BaseMutation):
clean_order_update_shipping(order, method)
order.shipping_method = method
- order.shipping_price = info.context.plugins.calculate_order_shipping(order)
+ shipping_price = info.context.plugins.calculate_order_shipping(order)
+ order.shipping_price = shipping_price
+ order.shipping_tax_rate = info.context.plugins.get_order_shipping_tax_rate(
+ order, shipping_price
+ )
order.shipping_method_name = method.name
order.save(
update_fields=[
@@ -268,6 +272,7 @@ class OrderUpdateShipping(BaseMutation):
"shipping_method_name",
"shipping_price_net_amount",
"shipping_price_gross_amount",
+ "shipping_tax_rate",
]
)
update_order_prices(order, info.context.discounts)
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 61926b25d6..42de451855 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -1,5 +1,6 @@
import uuid
from datetime import date, timedelta
+from decimal import Decimal
from unittest.mock import ANY, MagicMock, Mock, call, patch
import graphene
@@ -254,6 +255,7 @@ query OrdersQuery {
amount
}
}
+ shippingTaxRate
lines {
id
}
@@ -297,10 +299,23 @@ query OrdersQuery {
def test_order_query(
staff_api_client, permission_manage_orders, fulfilled_order, shipping_zone
):
+ # given
order = fulfilled_order
+ net = Money(amount=Decimal("10"), currency="USD")
+ gross = Money(amount=net.amount * Decimal(1.23), currency="USD").quantize()
+ shipping_price = TaxedMoney(net=net, gross=gross)
+ order.shipping_price = shipping_price
+ shipping_tax_rate = Decimal("0.23")
+ order.shipping_tax_rate = shipping_tax_rate
+ order.save()
+
staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
response = staff_api_client.post_graphql(ORDERS_QUERY)
content = get_graphql_content(response)
+
+ # then
order_data = content["data"]["orders"]["edges"][0]["node"]
assert order_data["number"] == str(order.pk)
assert order_data["channel"]["slug"] == order.channel.slug
@@ -316,7 +331,8 @@ def test_order_query(
expected_price = Money(
amount=str(order_data["shippingPrice"]["gross"]["amount"]), currency="USD"
)
- assert expected_price == order.shipping_price.gross
+ assert expected_price == shipping_price.gross
+ assert order_data["shippingTaxRate"] == float(shipping_tax_rate)
assert len(order_data["lines"]) == order.lines.count()
fulfillment = order.fulfillments.first().fulfillment_order
fulfillment_order = order_data["fulfillments"][0]["fulfillmentOrder"]
@@ -3421,6 +3437,42 @@ def test_order_update_shipping(
assert order.shipping_method == shipping_method
assert order.shipping_price_net == shipping_price.net
assert order.shipping_price_gross == shipping_price.gross
+ assert order.shipping_tax_rate == Decimal("0.0")
+ assert order.shipping_method_name == shipping_method.name
+
+
+def test_order_update_shipping_tax_included(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ shipping_method,
+ staff_user,
+ vatlayer,
+):
+ order = order_with_lines
+ address = order_with_lines.shipping_address
+ address.country = "DE"
+ address.save()
+
+ query = ORDER_UPDATE_SHIPPING_QUERY
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ variables = {"order": order_id, "shippingMethod": method_id}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderUpdateShipping"]
+ assert data["order"]["id"] == order_id
+
+ order.refresh_from_db()
+ shipping_total = shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).get_total()
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.shipping_method == shipping_method
+ assert order.shipping_price_gross == shipping_total
+ assert order.shipping_tax_rate == Decimal("0.19")
assert order.shipping_method_name == shipping_method.name
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index b1f5d2710a..fcbc52b846 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -439,6 +439,7 @@ class Order(CountableDjangoObjectType):
"shipping_method",
"shipping_method_name",
"shipping_price",
+ "shipping_tax_rate",
"status",
"token",
"tracking_client_id",
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 2c4b65384e..df3b87fb46 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2817,6 +2817,7 @@ type Order implements Node & ObjectWithMetadata {
shippingMethodName: String
channel: Channel!
shippingPrice: TaxedMoney
+ shippingTaxRate: Float!
token: String!
voucher: Voucher
giftCards: [GiftCard]
diff --git a/saleor/order/migrations/0096_order_shipping_tax_rate.py b/saleor/order/migrations/0096_order_shipping_tax_rate.py
new file mode 100644
index 0000000000..400ca4a8ae
--- /dev/null
+++ b/saleor/order/migrations/0096_order_shipping_tax_rate.py
@@ -0,0 +1,22 @@
+# Generated by Django 3.1.3 on 2020-12-29 11:26
+
+from decimal import Decimal
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0095_auto_20201229_1014"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="order",
+ name="shipping_tax_rate",
+ field=models.DecimalField(
+ decimal_places=4, default=Decimal("0.0"), max_digits=5
+ ),
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index fc9c11ac28..9b0deb232b 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -137,6 +137,9 @@ class Order(ModelWithMetadata):
gross_amount_field="shipping_price_gross_amount",
currency_field="currency",
)
+ shipping_tax_rate = models.DecimalField(
+ max_digits=5, decimal_places=4, default=Decimal("0.0")
+ )
token = models.CharField(max_length=36, unique=True, blank=True)
# Token of a checkout instance that this order was created from
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index b48a24b627..4a1139ffc9 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -420,10 +420,49 @@ def test_update_order_prices(order_with_lines):
assert line_1.unit_price == price_1
assert line_2.unit_price == price_2
assert order_with_lines.shipping_price == shipping_price
+ assert order_with_lines.shipping_tax_rate == Decimal("0.0")
total = line_1.total_price + line_2.total_price + shipping_price
assert order_with_lines.total == total
+def test_update_order_prices_tax_included(order_with_lines, vatlayer):
+ channel = order_with_lines.channel
+ address = order_with_lines.shipping_address
+ address.country = "DE"
+ address.save()
+
+ line_1 = order_with_lines.lines.first()
+ variant_1 = line_1.variant
+ product_1 = variant_1.product
+ variant_channel_listing_1 = variant_1.channel_listings.get(channel=channel)
+ price_1 = variant_1.get_price(
+ product_1, [], channel, variant_channel_listing_1, None
+ )
+
+ line_2 = order_with_lines.lines.last()
+ variant_2 = line_2.variant
+ product_2 = variant_2.product
+ variant_channel_listing_2 = variant_2.channel_listings.get(channel=channel)
+ price_2 = variant_2.get_price(
+ product_2, [], channel, variant_channel_listing_2, None
+ )
+
+ shipping_price = order_with_lines.shipping_method.channel_listings.get(
+ channel_id=order_with_lines.channel_id
+ ).price
+
+ update_order_prices(order_with_lines, None)
+
+ line_1.refresh_from_db()
+ line_2.refresh_from_db()
+ assert line_1.unit_price.gross == price_1
+ assert line_2.unit_price.gross == price_2
+ assert order_with_lines.shipping_price.gross == shipping_price
+ assert order_with_lines.shipping_tax_rate == Decimal("0.19")
+ total = line_1.total_price + line_2.total_price + order_with_lines.shipping_price
+ assert order_with_lines.total == total
+
+
def _calculate_order_weight_from_lines(order):
weight = zero_weight()
for line in order:
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 46d46c73b0..0eed926d30 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -142,11 +142,16 @@ def update_order_prices(order, discounts):
line.save()
if order.shipping_method:
- order.shipping_price = manager.calculate_order_shipping(order)
+ shipping_price = manager.calculate_order_shipping(order)
+ order.shipping_price = shipping_price
+ order.shipping_tax_rate = manager.get_order_shipping_tax_rate(
+ order, shipping_price
+ )
order.save(
update_fields=[
"shipping_price_net_amount",
"shipping_price_gross_amount",
+ "shipping_tax_rate",
"currency",
]
)
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index 58bc2f82cf..821b86ce6a 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -431,7 +431,7 @@ class AvataxPlugin(BasePlugin):
discounts: Iterable[DiscountInfo],
previous_value: Decimal,
) -> Decimal:
- return self._get_tax_rate(
+ return self._get_unit_tax_rate(
checkout, previous_value, False, discounts, [checkout_line_info.line]
)
@@ -442,9 +442,28 @@ class AvataxPlugin(BasePlugin):
address: Optional["Address"],
previous_value: Decimal,
) -> Decimal:
- return self._get_tax_rate(order, previous_value, True)
+ return self._get_unit_tax_rate(order, previous_value, True)
- def _get_tax_rate(
+ def get_checkout_shipping_tax_rate(
+ self,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLineInfo"],
+ address: Optional["Address"],
+ discounts: Iterable[DiscountInfo],
+ previous_value: Decimal,
+ ):
+ return self._get_shipping_tax_rate(
+ checkout,
+ previous_value,
+ False,
+ discounts,
+ [line_info.line for line_info in lines],
+ )
+
+ def get_order_shipping_tax_rate(self, order: "Order", previous_value: Decimal):
+ return self._get_shipping_tax_rate(order, previous_value, True)
+
+ def _get_unit_tax_rate(
self,
instance: Union["Order", "Checkout"],
base_rate: Decimal,
@@ -452,8 +471,49 @@ class AvataxPlugin(BasePlugin):
discounts: Optional[Iterable[DiscountInfo]] = None,
checkout_lines: Iterable["CheckoutLine"] = [],
):
- if self._skip_plugin(base_rate):
+ response = self._get_tax_data(
+ instance, base_rate, is_order, discounts, checkout_lines
+ )
+ if response is None:
+ return base_rate
+ rate = None
+ response_summary = response.get("summary")
+ if response_summary:
+ rate = Decimal(response_summary[0].get("rate", 0.0))
+ return rate or base_rate
+
+ def _get_shipping_tax_rate(
+ self,
+ instance: Union["Order", "Checkout"],
+ base_rate: Decimal,
+ is_order: bool,
+ discounts: Optional[Iterable[DiscountInfo]] = None,
+ checkout_lines: Iterable["CheckoutLine"] = [],
+ ):
+ response = self._get_tax_data(
+ instance, base_rate, is_order, discounts, checkout_lines
+ )
+ if response is None:
return base_rate
+ lines_data = response.get("lines", [])
+ for line in lines_data:
+ if line["itemCode"] == "Shipping":
+ line_details = line.get("details")
+ if not line_details:
+ return
+ return Decimal(line_details[0].get("rate", 0.0))
+ return base_rate
+
+ def _get_tax_data(
+ self,
+ instance: Union["Order", "Checkout"],
+ base_rate: Decimal,
+ is_order: bool,
+ discounts: Optional[Iterable[DiscountInfo]] = None,
+ checkout_lines: Iterable["CheckoutLine"] = [],
+ ):
+ if self._skip_plugin(base_rate):
+ return None
valid = (
_validate_order(instance) # type: ignore
@@ -462,7 +522,7 @@ class AvataxPlugin(BasePlugin):
)
if not valid:
- return base_rate
+ return None
response = (
get_order_tax_data(instance, self.config, False) # type: ignore
@@ -470,14 +530,9 @@ class AvataxPlugin(BasePlugin):
else get_checkout_tax_data(instance, discounts, self.config) # type: ignore
)
if not response or "error" in response:
- return base_rate
+ return None
- rate = None
- response_summary = response.get("summary")
- if response_summary:
- rate = Decimal(response_summary[0].get("rate", 0.0))
-
- return rate or base_rate
+ return response
def assign_tax_code_to_object_meta(
self,
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index 1db6186920..d546c2d8d8 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -495,6 +495,13 @@ AVALARA_TAX_DATA = {
"paymentDate": "2020-12-28",
"status": "Temporary",
"type": "SalesOrder",
+ "lines": [
+ {
+ "itemCode": "3456",
+ "details": [{"taxType": "Sales", "rate": 0.055, "tax": 2.03}],
+ },
+ {"itemCode": "Shipping", "details": [{"rate": 0.08, "tax": 1.5}]},
+ ],
"summary": [
{
"country": "US",
@@ -717,6 +724,271 @@ def test_get_order_line_tax_rate_error_in_response(
assert tax_rate == Decimal("0.25")
+def test_get_checkout_shipping_tax_rate(
+ monkeypatch, checkout_with_item, address, plugin_configuration, shipping_zone
+):
+ # given
+ plugin_configuration()
+ monkeypatch.setattr(
+ "saleor.plugins.avatax.plugin.get_checkout_tax_data",
+ lambda *_: AVALARA_TAX_DATA,
+ )
+ shipping_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
+
+ manager = get_plugins_manager(plugins=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+ line = checkout_with_item.lines.first()
+
+ checkout_with_item.shipping_address = address
+ checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
+
+ variant = line.variant
+ checkout_line_info = CheckoutLineInfo(
+ line=line,
+ variant=variant,
+ channel_listing=variant.channel_listings.first(),
+ product=variant.product,
+ collections=[],
+ )
+
+ # when
+ tax_rate = manager.get_checkout_shipping_tax_rate(
+ checkout_with_item,
+ [checkout_line_info],
+ checkout_with_item.shipping_address,
+ [],
+ shipping_price,
+ )
+
+ # then
+ assert tax_rate == Decimal("0.08")
+
+
+def test_get_checkout_shipping_tax_rate_checkout_not_valid_default_value_returned(
+ monkeypatch, checkout_with_item, address, plugin_configuration
+):
+ # given
+ plugin_configuration()
+ monkeypatch.setattr(
+ "saleor.plugins.avatax.plugin.get_checkout_tax_data",
+ lambda *_: AVALARA_TAX_DATA,
+ )
+ shipping_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
+
+ manager = get_plugins_manager(plugins=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+ line = checkout_with_item.lines.first()
+
+ checkout_with_item.shipping_address = address
+ checkout_with_item.save(update_fields=["shipping_address"])
+
+ variant = line.variant
+ checkout_line_info = CheckoutLineInfo(
+ line=line,
+ variant=variant,
+ channel_listing=variant.channel_listings.first(),
+ product=variant.product,
+ collections=[],
+ )
+
+ # when
+ tax_rate = manager.get_checkout_shipping_tax_rate(
+ checkout_with_item,
+ [checkout_line_info],
+ checkout_with_item.shipping_address,
+ [],
+ shipping_price,
+ )
+
+ # then
+ assert tax_rate == Decimal("0.25")
+
+
+def test_get_checkout_shipping_tax_rate_error_in_response(
+ monkeypatch, checkout_with_item, address, plugin_configuration, shipping_zone
+):
+ # given
+ plugin_configuration()
+ monkeypatch.setattr(
+ "saleor.plugins.avatax.plugin.get_checkout_tax_data",
+ lambda *_: {"error": "Example error"},
+ )
+ shipping_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
+
+ manager = get_plugins_manager(plugins=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+ line = checkout_with_item.lines.first()
+
+ checkout_with_item.shipping_address = address
+ checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
+
+ variant = line.variant
+ checkout_line_info = CheckoutLineInfo(
+ line=line,
+ variant=variant,
+ channel_listing=variant.channel_listings.first(),
+ product=variant.product,
+ collections=[],
+ )
+
+ # when
+ tax_rate = manager.get_checkout_shipping_tax_rate(
+ checkout_with_item,
+ [checkout_line_info],
+ checkout_with_item.shipping_address,
+ [],
+ shipping_price,
+ )
+
+ # then
+ assert tax_rate == Decimal("0.25")
+
+
+def test_get_checkout_shipping_tax_rate_skip_plugin(
+ monkeypatch, checkout_with_item, address, plugin_configuration, shipping_zone
+):
+ # given
+ plugin_configuration()
+ monkeypatch.setattr(
+ "saleor.plugins.avatax.plugin.get_checkout_tax_data",
+ lambda *_: {"error": "Example error"},
+ )
+ monkeypatch.setattr(
+ "saleor.plugins.avatax.plugin.AvataxPlugin._skip_plugin", lambda *_: True,
+ )
+ shipping_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
+
+ manager = get_plugins_manager(plugins=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+ line = checkout_with_item.lines.first()
+
+ checkout_with_item.shipping_address = address
+ checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
+
+ variant = line.variant
+ checkout_line_info = CheckoutLineInfo(
+ line=line,
+ variant=variant,
+ channel_listing=variant.channel_listings.first(),
+ product=variant.product,
+ collections=[],
+ )
+
+ # when
+ tax_rate = manager.get_checkout_shipping_tax_rate(
+ checkout_with_item,
+ [checkout_line_info],
+ checkout_with_item.shipping_address,
+ [],
+ shipping_price,
+ )
+
+ # then
+ assert tax_rate == Decimal("0.25")
+
+
+def test_get_order_shipping_tax_rate(
+ monkeypatch, order_line, shipping_zone, plugin_configuration
+):
+ # given
+ order = order_line.order
+ plugin_configuration()
+ monkeypatch.setattr(
+ "saleor.plugins.avatax.plugin.get_order_tax_data", lambda *_: AVALARA_TAX_DATA
+ )
+ shipping_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
+
+ manager = get_plugins_manager(plugins=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+
+ method = shipping_zone.shipping_methods.get()
+ order.shipping_address = order.billing_address.get_copy()
+ order.shipping_method_name = method.name
+ order.shipping_method = method
+ order.save()
+
+ # when
+ tax_rate = manager.get_order_shipping_tax_rate(order, shipping_price)
+
+ # then
+ assert tax_rate == Decimal("0.08")
+
+
+def test_get_order_shipping_tax_rate_order_not_valid_default_value_returned(
+ monkeypatch, order_line, shipping_zone, plugin_configuration
+):
+ # given
+ order = order_line.order
+ plugin_configuration()
+ monkeypatch.setattr(
+ "saleor.plugins.avatax.plugin.get_order_tax_data", lambda *_: AVALARA_TAX_DATA
+ )
+ shipping_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
+
+ manager = get_plugins_manager(plugins=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+
+ # when
+ tax_rate = manager.get_order_shipping_tax_rate(order, shipping_price)
+
+ # then
+ assert tax_rate == Decimal("0.25")
+
+
+def test_get_order_shipping_tax_rate_error_in_response(
+ monkeypatch, order_line, shipping_zone, plugin_configuration
+):
+ # given
+ order = order_line.order
+ plugin_configuration()
+ monkeypatch.setattr(
+ "saleor.plugins.avatax.plugin.get_order_tax_data",
+ lambda *_: {"error": "Example error"},
+ )
+ shipping_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
+
+ manager = get_plugins_manager(plugins=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+
+ method = shipping_zone.shipping_methods.get()
+ order.shipping_address = order.billing_address.get_copy()
+ order.shipping_method_name = method.name
+ order.shipping_method = method
+ order.save()
+
+ # when
+ tax_rate = manager.get_order_shipping_tax_rate(order, shipping_price)
+
+ # then
+ assert tax_rate == Decimal("0.25")
+
+
+def test_get_order_shipping_tax_rate_skip_plugin(
+ monkeypatch, order_line, shipping_zone, plugin_configuration
+):
+ # given
+ order = order_line.order
+ plugin_configuration()
+ monkeypatch.setattr(
+ "saleor.plugins.avatax.plugin.get_order_tax_data",
+ lambda *_: {"error": "Example error"},
+ )
+ monkeypatch.setattr(
+ "saleor.plugins.avatax.plugin.AvataxPlugin._skip_plugin", lambda *_: True,
+ )
+ shipping_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
+
+ manager = get_plugins_manager(plugins=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+
+ method = shipping_zone.shipping_methods.get()
+ order.shipping_address = order.billing_address.get_copy()
+ order.shipping_method_name = method.name
+ order.shipping_method = method
+ order.save()
+
+ # when
+ tax_rate = manager.get_order_shipping_tax_rate(order, shipping_price)
+
+ # then
+ assert tax_rate == Decimal("0.25")
+
+
def test_get_plugin_configuration(settings):
settings.PLUGINS = ["saleor.plugins.avatax.plugin.AvataxPlugin"]
manager = get_plugins_manager()
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index c576f7342e..d0f12cece1 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -186,6 +186,38 @@ class BasePlugin:
"""
return NotImplemented
+ def get_checkout_line_tax_rate(
+ self,
+ checkout: "Checkout",
+ checkout_line_info: "CheckoutLineInfo",
+ address: Optional["Address"],
+ discounts: Iterable["DiscountInfo"],
+ previous_value: Decimal,
+ ) -> Decimal:
+ return NotImplemented
+
+ def get_order_line_tax_rate(
+ self,
+ order: "Order",
+ product: "Product",
+ address: Optional["Address"],
+ previous_value: Decimal,
+ ) -> Decimal:
+ return NotImplemented
+
+ def get_checkout_shipping_tax_rate(
+ self,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLineInfo"],
+ address: Optional["Address"],
+ discounts: Iterable["DiscountInfo"],
+ previous_value: Decimal,
+ ):
+ return NotImplemented
+
+ def get_order_shipping_tax_rate(self, order: "Order", previous_value: Decimal):
+ return NotImplemented
+
def get_tax_rate_type_choices(
self, previous_value: List["TaxType"]
) -> List["TaxType"]:
@@ -445,25 +477,6 @@ class BasePlugin:
) -> List["CustomerSource"]:
return NotImplemented
- def get_checkout_line_tax_rate(
- self,
- checkout: "Checkout",
- checkout_line_info: "CheckoutLineInfo",
- address: Optional["Address"],
- discounts: Iterable["DiscountInfo"],
- previous_value: Decimal,
- ) -> Decimal:
- return NotImplemented
-
- def get_order_line_tax_rate(
- self,
- order: "Order",
- product: "Product",
- address: Optional["Address"],
- previous_value: Decimal,
- ) -> Decimal:
- return NotImplemented
-
def get_client_token(self, token_config, previous_value):
return NotImplemented
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index f39f695f41..bc04219999 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -209,6 +209,30 @@ class PluginsManager(PaymentInterface):
order.currency,
)
+ def get_checkout_shipping_tax_rate(
+ self,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLineInfo"],
+ address: Optional["Address"],
+ discounts: Iterable[DiscountInfo],
+ shipping_price: TaxedMoney,
+ ):
+ default_value = base_calculations.base_tax_rate(shipping_price)
+ return self.__run_method_on_plugins(
+ "get_checkout_shipping_tax_rate",
+ default_value,
+ checkout,
+ lines,
+ address,
+ discounts,
+ ).quantize(Decimal(".0001"))
+
+ def get_order_shipping_tax_rate(self, order: "Order", shipping_price: TaxedMoney):
+ default_value = base_calculations.base_tax_rate(shipping_price)
+ return self.__run_method_on_plugins(
+ "get_order_shipping_tax_rate", default_value, order
+ ).quantize(Decimal(".0001"))
+
def calculate_checkout_line_total(
self,
checkout: "Checkout",
@@ -273,6 +297,36 @@ class PluginsManager(PaymentInterface):
order_line.currency,
)
+ def get_checkout_line_tax_rate(
+ self,
+ checkout: "Checkout",
+ checkout_line_info: "CheckoutLineInfo",
+ address: Optional["Address"],
+ discounts: Iterable[DiscountInfo],
+ unit_price: TaxedMoney,
+ ) -> Decimal:
+ default_value = base_calculations.base_tax_rate(unit_price)
+ return self.__run_method_on_plugins(
+ "get_checkout_line_tax_rate",
+ default_value,
+ checkout,
+ checkout_line_info,
+ address,
+ discounts,
+ ).quantize(Decimal(".0001"))
+
+ def get_order_line_tax_rate(
+ self,
+ order: "Order",
+ product: "Product",
+ address: Optional["Address"],
+ unit_price: TaxedMoney,
+ ) -> Decimal:
+ default_value = base_calculations.base_tax_rate(unit_price)
+ return self.__run_method_on_plugins(
+ "get_order_line_tax_rate", default_value, order, product, address
+ ).quantize(Decimal(".0001"))
+
def get_tax_rate_type_choices(self) -> List[TaxType]:
default_value: list = []
return self.__run_method_on_plugins("get_tax_rate_type_choices", default_value)
@@ -481,36 +535,6 @@ class PluginsManager(PaymentInterface):
)
raise Exception(f"Payment plugin {gateway} is inaccessible!")
- def get_checkout_line_tax_rate(
- self,
- checkout: "Checkout",
- checkout_line_info: "CheckoutLineInfo",
- address: Optional["Address"],
- discounts: Iterable[DiscountInfo],
- unit_price: TaxedMoney,
- ) -> Decimal:
- default_value = base_calculations.base_tax_rate(unit_price)
- return self.__run_method_on_plugins(
- "get_checkout_line_tax_rate",
- default_value,
- checkout,
- checkout_line_info,
- address,
- discounts,
- ).quantize(Decimal(".0001"))
-
- def get_order_line_tax_rate(
- self,
- order: "Order",
- product: "Product",
- address: Optional["Address"],
- unit_price: TaxedMoney,
- ) -> Decimal:
- default_value = base_calculations.base_tax_rate(unit_price)
- return self.__run_method_on_plugins(
- "get_order_line_tax_rate", default_value, order, product, address
- ).quantize(Decimal(".0001"))
-
def get_active_plugins(self, plugins=None) -> List["BasePlugin"]:
if plugins is None:
plugins = self.plugins
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index 43f72643aa..4b86a1ef17 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -154,6 +154,19 @@ class PluginSample(BasePlugin):
) -> Decimal:
return Decimal("0.080").quantize(Decimal(".01"))
+ def get_checkout_shipping_tax_rate(
+ self,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLineInfo"],
+ address: Optional["Address"],
+ discounts: Iterable["DiscountInfo"],
+ previous_value: Decimal,
+ ):
+ return Decimal("0.080").quantize(Decimal(".01"))
+
+ def get_order_shipping_tax_rate(self, order: "Order", previous_value: Decimal):
+ return Decimal("0.080").quantize(Decimal(".01"))
+
class PluginInactive(BasePlugin):
PLUGIN_ID = "plugin.inactive"
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 18436bfd1e..1d71b60034 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -211,6 +211,88 @@ def test_manager_get_order_line_tax_rate_no_plugins(
assert tax_rate == expected_tax_rate
+def test_manager_get_checkout_shipping_tax_rate_sample_plugin(
+ checkout_with_item, discount_info
+):
+ line = checkout_with_item.lines.all()[0]
+ plugins = ["saleor.plugins.tests.sample_plugins.PluginSample"]
+ shipping_price = TaxedMoney(Money(12, "USD"), Money(14, "USD"))
+
+ variant = line.variant
+ checkout_line_info = CheckoutLineInfo(
+ line=line,
+ variant=variant,
+ channel_listing=variant.channel_listings.first(),
+ product=variant.product,
+ collections=[],
+ )
+
+ tax_rate = PluginsManager(plugins=plugins).get_checkout_shipping_tax_rate(
+ checkout_with_item,
+ [checkout_line_info],
+ checkout_with_item.shipping_address,
+ [discount_info],
+ shipping_price,
+ )
+ assert tax_rate == Decimal("0.08")
+
+
+ "shipping_price, expected_tax_rate",
+ [
+ (TaxedMoney(Money(12, "USD"), Money(14, "USD")), Decimal("0.1667")),
+ (Decimal("0.0"), Decimal("0.0")),
+ ],
+)
+def test_manager_get_checkout_shipping_tax_rate_no_plugins(
+ checkout_with_item, discount_info, shipping_price, expected_tax_rate
+):
+ line = checkout_with_item.lines.all()[0]
+ variant = line.variant
+ checkout_line_info = CheckoutLineInfo(
+ line=line,
+ variant=variant,
+ channel_listing=variant.channel_listings.first(),
+ product=variant.product,
+ collections=[],
+ )
+ tax_rate = PluginsManager(plugins=[]).get_checkout_shipping_tax_rate(
+ checkout_with_item,
+ [checkout_line_info],
+ checkout_with_item.shipping_address,
+ [discount_info],
+ shipping_price,
+ )
+ assert tax_rate == expected_tax_rate
+
+
+def test_manager_get_order_shipping_tax_rate_sample_plugin(order_with_lines):
+ order = order_with_lines
+ plugins = ["saleor.plugins.tests.sample_plugins.PluginSample"]
+ shipping_price = TaxedMoney(Money(12, "USD"), Money(14, "USD"))
+ tax_rate = PluginsManager(plugins=plugins).get_order_shipping_tax_rate(
+ order, shipping_price,
+ )
+ assert tax_rate == Decimal("0.08")
+
+
+ "shipping_price, expected_tax_rate",
+ [
+ (TaxedMoney(Money(12, "USD"), Money(14, "USD")), Decimal("0.1667")),
+ (Decimal("0.0"), Decimal("0.0")),
+ ],
+)
+def test_manager_get_order_shipping_tax_rate_no_plugins(
+ order_with_lines, shipping_price, expected_tax_rate
+):
+ order = order_with_lines
+ tax_rate = PluginsManager(plugins=[]).get_order_shipping_tax_rate(
+ order, shipping_price,
+ )
+ assert tax_rate == expected_tax_rate
+
+
@pytest.mark.parametrize(
"plugins, total_line_price, quantity",
[
diff --git a/saleor/plugins/vatlayer/plugin.py b/saleor/plugins/vatlayer/plugin.py
index 907bd38ca3..a0419acce4 100644
--- a/saleor/plugins/vatlayer/plugin.py
+++ b/saleor/plugins/vatlayer/plugin.py
@@ -206,6 +206,65 @@ class VatlayerPlugin(BasePlugin):
variant.product, order_line.unit_price, country
)
+ def get_checkout_line_tax_rate(
+ self,
+ checkout: "Checkout",
+ checkout_line_info: "CheckoutLineInfo",
+ address: Optional["Address"],
+ discounts: Iterable["DiscountInfo"],
+ previous_value: Decimal,
+ ) -> Decimal:
+ return self._get_tax_rate(checkout_line_info.product, address, previous_value)
+
+ def get_order_line_tax_rate(
+ self,
+ order: "Order",
+ product: "Product",
+ address: Optional["Address"],
+ previous_value: Decimal,
+ ) -> Decimal:
+ return self._get_tax_rate(product, address, previous_value)
+
+ def _get_tax_rate(
+ self, product: "Product", address: Optional["Address"], previous_value: Decimal
+ ):
+ if self._skip_plugin(previous_value):
+ return previous_value
+ country = address.country if address else None
+ taxes, tax_rate = self.__get_tax_data_for_product(product, country)
+ if not taxes or not tax_rate:
+ return previous_value
+ tax = taxes.get(tax_rate) or taxes.get(DEFAULT_TAX_RATE_NAME)
+ # tax value is given in precentage so it need be be converted into decimal value
+ return Decimal(tax["value"] / 100)
+
+ def get_checkout_shipping_tax_rate(
+ self,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLineInfo"],
+ address: Optional["Address"],
+ discounts: Iterable["DiscountInfo"],
+ previous_value: Decimal,
+ ):
+ return self._get_shipping_tax_rate(address, previous_value)
+
+ def get_order_shipping_tax_rate(self, order: "Order", previous_value: Decimal):
+ address = order.shipping_address or order.billing_address
+ return self._get_shipping_tax_rate(address, previous_value)
+
+ def _get_shipping_tax_rate(
+ self, address: Optional["Address"], previous_value: Decimal
+ ):
+ if self._skip_plugin(previous_value):
+ return previous_value
+ country = address.country if address else None
+ taxes = self._get_taxes_for_country(country)
+ if not taxes:
+ return previous_value
+ tax = taxes.get(DEFAULT_TAX_RATE_NAME)
+ # tax value is given in precentage so it need be be converted into decimal value
+ return Decimal(tax["value"] / 100)
+
def get_tax_rate_type_choices(
self, previous_value: List["TaxType"]
) -> List["TaxType"]:
@@ -335,38 +394,6 @@ class VatlayerPlugin(BasePlugin):
fetch_rates(self.config.access_key)
return True
- def get_checkout_line_tax_rate(
- self,
- checkout: "Checkout",
- checkout_line_info: "CheckoutLineInfo",
- address: Optional["Address"],
- discounts: Iterable["DiscountInfo"],
- previous_value: Decimal,
- ) -> Decimal:
- return self._get_tax_rate(checkout_line_info.product, address, previous_value)
-
- def get_order_line_tax_rate(
- self,
- order: "Order",
- product: "Product",
- address: Optional["Address"],
- previous_value: Decimal,
- ) -> Decimal:
- return self._get_tax_rate(product, address, previous_value)
-
- def _get_tax_rate(
- self, product: "Product", address: Optional["Address"], previous_value: Decimal
- ):
- if self._skip_plugin(previous_value):
- return previous_value
- country = address.country if address else None
- taxes, tax_rate = self.__get_tax_data_for_product(product, country)
- if not taxes or not tax_rate:
- return previous_value
- tax = taxes.get(tax_rate) or taxes.get(DEFAULT_TAX_RATE_NAME)
- # tax value is given in precentage so it need be be converted into decimal value
- return Decimal(tax["value"] / 100)
-
@classmethod
def validate_plugin_configuration(cls, plugin_configuration: "PluginConfiguration"):
"""Validate if provided configuration is correct."""
diff --git a/saleor/plugins/vatlayer/tests/test_vatlayer.py b/saleor/plugins/vatlayer/tests/test_vatlayer.py
index 3c48eeb485..2416229af1 100644
--- a/saleor/plugins/vatlayer/tests/test_vatlayer.py
+++ b/saleor/plugins/vatlayer/tests/test_vatlayer.py
@@ -660,3 +660,200 @@ def test_get_order_line_tax_rate_order_no_address_given(
tax_rate = manager.get_order_line_tax_rate(order, product, None, unit_price)
assert tax_rate == Decimal("0.25")
+
+
+def test_get_checkout_shipping_tax_rate(
+ site_settings, vatlayer, checkout_with_item, address, shipping_zone,
+):
+ manager = get_plugins_manager(
+ plugins=["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
+ )
+ checkout_with_item.shipping_address = address
+ checkout_with_item.save()
+ checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.save()
+
+ line = checkout_with_item.lines.first()
+ product = line.variant.product
+ manager.assign_tax_code_to_object_meta(product, "standard")
+ product.save()
+
+ site_settings.include_taxes_in_prices = True
+ site_settings.save()
+
+ unit_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
+
+ variant = line.variant
+ checkout_line_info = CheckoutLineInfo(
+ line=line,
+ variant=variant,
+ channel_listing=variant.channel_listings.first(),
+ product=variant.product,
+ collections=[],
+ )
+
+ tax_rate = manager.get_checkout_shipping_tax_rate(
+ checkout_with_item,
+ [checkout_line_info],
+ checkout_with_item.shipping_address,
+ [],
+ unit_price,
+ )
+ assert tax_rate == Decimal("0.230")
+
+
+def test_get_checkout_shipping_tax_rate_no_address(
+ site_settings, vatlayer, checkout_with_item,
+):
+ manager = get_plugins_manager(
+ plugins=["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
+ )
+
+ line = checkout_with_item.lines.first()
+ product = line.variant.product
+ manager.assign_tax_code_to_object_meta(product, "standard")
+ product.save()
+
+ site_settings.include_taxes_in_prices = True
+ site_settings.save()
+
+ unit_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
+
+ variant = line.variant
+ checkout_line_info = CheckoutLineInfo(
+ line=line,
+ variant=variant,
+ channel_listing=variant.channel_listings.first(),
+ product=variant.product,
+ collections=[],
+ )
+
+ tax_rate = manager.get_checkout_shipping_tax_rate(
+ checkout_with_item,
+ checkout_line_info,
+ checkout_with_item.shipping_address,
+ [],
+ unit_price,
+ )
+ assert tax_rate == Decimal("0.25")
+
+
+def test_get_checkout_shipping_tax_rate_skip_plugin(
+ site_settings, vatlayer, checkout_with_item, monkeypatch, address, shipping_zone
+):
+ manager = get_plugins_manager(
+ plugins=["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
+ )
+ monkeypatch.setattr(
+ "saleor.plugins.vatlayer.plugin.VatlayerPlugin._skip_plugin", lambda *_: True,
+ )
+
+ checkout_with_item.shipping_address = address
+ checkout_with_item.save()
+ checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.save()
+
+ line = checkout_with_item.lines.first()
+ product = line.variant.product
+ manager.assign_tax_code_to_object_meta(product, "standard")
+ product.save()
+
+ site_settings.include_taxes_in_prices = True
+ site_settings.save()
+
+ unit_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
+
+ variant = line.variant
+ checkout_line_info = CheckoutLineInfo(
+ line=line,
+ variant=variant,
+ channel_listing=variant.channel_listings.first(),
+ product=variant.product,
+ collections=[],
+ )
+
+ tax_rate = manager.get_checkout_shipping_tax_rate(
+ checkout_with_item,
+ checkout_line_info,
+ checkout_with_item.shipping_address,
+ [],
+ unit_price,
+ )
+ assert tax_rate == Decimal("0.25")
+
+
+def test_get_order_shipping_tax_rate(
+ site_settings, vatlayer, order_line, address, shipping_zone,
+):
+ manager = get_plugins_manager(
+ plugins=["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
+ )
+ order = order_line.order
+ product = Product.objects.get(name=order_line.product_name)
+ product.save()
+
+ method = shipping_zone.shipping_methods.get()
+ order.shipping_address = address
+ order.shipping_method_name = method.name
+ order.shipping_method = method
+ order.save()
+
+ manager.assign_tax_code_to_object_meta(product, "standard")
+ product.save()
+
+ site_settings.include_taxes_in_prices = True
+ site_settings.save()
+
+ shipping_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
+
+ tax_rate = manager.get_order_shipping_tax_rate(order, shipping_price)
+ assert tax_rate == Decimal("0.230")
+
+
+def test_get_order_shipping_tax_rate_no_address_given(
+ site_settings, order_line, vatlayer,
+):
+ manager = get_plugins_manager(
+ plugins=["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
+ )
+ order = order_line.order
+ product = Product.objects.get(name=order_line.product_name)
+
+ manager.assign_tax_code_to_object_meta(product, "standard")
+ product.save()
+
+ order.shipping_address = None
+ order.billing_address = None
+ order.save(update_fields=["shipping_address", "billing_address"])
+
+ site_settings.include_taxes_in_prices = True
+ site_settings.save()
+
+ shipping_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
+
+ tax_rate = manager.get_order_shipping_tax_rate(order, shipping_price)
+ assert tax_rate == Decimal("0.25")
+
+
+def test_get_order_shipping_tax_rate_skip_plugin(
+ site_settings, order_line, vatlayer, monkeypatch
+):
+ manager = get_plugins_manager(
+ plugins=["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
+ )
+ monkeypatch.setattr(
+ "saleor.plugins.vatlayer.plugin.VatlayerPlugin._skip_plugin", lambda *_: True,
+ )
+ order = order_line.order
+ product = Product.objects.get(name=order_line.product_name)
+
+ manager.assign_tax_code_to_object_meta(product, "standard")
+ product.save()
+
+ site_settings.include_taxes_in_prices = True
+ site_settings.save()
+
+ shipping_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
+
+ tax_rate = manager.get_order_shipping_tax_rate(order, shipping_price)
+ assert tax_rate == Decimal("0.25")
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 14bb5b810b..66adacfbd5 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -42,6 +42,7 @@ ORDER_FIELDS = (
"shipping_method_name",
"shipping_price_net_amount",
"shipping_price_gross_amount",
+ "shipping_tax_rate",
"total_net_amount",
"total_gross_amount",
"shipping_price_net_amount",
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index eff7d70f0d..7558772bb0 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -20,6 +20,7 @@ def test_generate_order_payload(
assert payload.get("payments")
assert payload.get("shipping_method")
+ assert payload.get("shipping_tax_rate")
assert payload.get("lines")
assert payload.get("payments")
assert payload.get("shipping_address")