Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix incorrect tax rate returned by Avatax plugin (#17238)
Maciej Korycinski789e33510a42
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.pyindex 235ee25481..a808700441 100644--- a/saleor/order/calculations.py+++ b/saleor/order/calculations.py@@ -306,7 +306,7 @@ def _recalculate_with_plugins(product,variant,None,- line_unit.undiscounted_price,+ line.total_price,plugin_ids=plugin_ids,)line.undiscounted_unit_price = _get_undiscounted_price(diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.pyindex 2977492acc..2200e68432 100644--- a/saleor/plugins/avatax/__init__.py+++ b/saleor/plugins/avatax/__init__.py@@ -110,7 +110,7 @@ def api_post_request(allow_redirects=False,)logger.debug("Hit to Avatax to calculate taxes %s", url)- json_response = response.json()+ json_response = response.json(parse_float=Decimal)if "error" in response:logger.exception("Avatax response contains errors %s", json_response)return json_responsediff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.pyindex f80c497f5c..409b4d24fe 100644--- a/saleor/plugins/avatax/plugin.py+++ b/saleor/plugins/avatax/plugin.py@@ -15,16 +15,9 @@ from prices import Money, TaxedMoney, TaxedMoneyRangefrom ...checkout import base_calculationsfrom ...checkout.fetch import fetch_checkout_lines-from ...checkout.utils import (- log_address_if_validation_skipped_for_checkout,-)+from ...checkout.utils import log_address_if_validation_skipped_for_checkoutfrom ...core.prices import MAXIMUM_PRICE-from ...core.taxes import (- TaxDataErrorMessage,- TaxError,- TaxType,- zero_taxed_money,-)+from ...core.taxes import TaxDataErrorMessage, TaxError, TaxType, zero_taxed_moneyfrom ...order import base_calculations as order_base_calculationfrom ...order.interface import OrderTaxedPricesDatafrom ...product.models import ProductType@@ -45,6 +38,7 @@ from . import (DEFAULT_TAX_DESCRIPTION,META_CODE_KEY,META_DESCRIPTION_KEY,+ SHIPPING_ITEM_CODE,AvataxConfiguration,CustomerErrors,TransactionType,@@ -266,7 +260,7 @@ class AvataxPlugin(BasePlugin):shipping_tax = Decimal(0.0)shipping_net = shipping_price.amountfor line in lines:- if line["itemCode"] == "Shipping":+ if line["itemCode"] == SHIPPING_ITEM_CODE:# The lineAmount does not include the discountAmount,# but tax is calculated for discounted net price, that# take into account provided discount.@@ -611,7 +605,7 @@ class AvataxPlugin(BasePlugin):prices_entered_with_tax = partial(_get_prices_entered_with_tax_for_order, order)currency = taxes_data.get("currencyCode")for line in taxes_data.get("lines", []):- if line["itemCode"] == "Shipping":+ if line["itemCode"] == SHIPPING_ITEM_CODE:tax = Decimal(line.get("tax", 0.0))discount_amount = Decimal(line.get("discountAmount", 0.0))net = Decimal(line.get("lineAmount", 0.0)) - discount_amount@@ -698,10 +692,12 @@ class AvataxPlugin(BasePlugin):response = self._get_checkout_tax_data(checkout_info, lines, previous_value)variant = checkout_line_info.variant- return self._get_unit_tax_rate(+ return self._get_item_tax_rate(response,variant.sku or variant.get_global_id(),previous_value,+ str(checkout_info.checkout.pk),+ "Checkout",)def get_order_line_tax_rate(@@ -717,10 +713,12 @@ class AvataxPlugin(BasePlugin):return previous_valueresponse = self._get_order_tax_data(order, previous_value)- return self._get_unit_tax_rate(+ return self._get_item_tax_rate(response,variant.sku or variant.get_global_id(),previous_value,+ str(order.pk),+ "Order",)def get_checkout_shipping_tax_rate(@@ -731,11 +729,19 @@ class AvataxPlugin(BasePlugin):previous_value: Decimal,):response = self._get_checkout_tax_data(checkout_info, lines, previous_value)- return self._get_shipping_tax_rate(response, previous_value)+ return self._get_item_tax_rate(+ response,+ SHIPPING_ITEM_CODE,+ previous_value,+ str(checkout_info.checkout.pk),+ "Checkout",+ )def get_order_shipping_tax_rate(self, order: "Order", previous_value: Decimal):response = self._get_order_tax_data(order, previous_value)- return self._get_shipping_tax_rate(response, previous_value)+ return self._get_item_tax_rate(+ response, SHIPPING_ITEM_CODE, previous_value, str(order.pk), "Order"+ )def _get_checkout_tax_data(self,@@ -810,42 +816,67 @@ class AvataxPlugin(BasePlugin):order.tax_error = tax_error@staticmethod- def _get_unit_tax_rate(+ def _get_item_tax_rate(response: dict[str, Any],item_code: str,base_rate: Decimal,+ related_object_id: str,+ related_object_type: str,):if response is None:return base_ratelines_data = response.get("lines", [])for line in lines_data:if line["itemCode"] == item_code:+ taxable_amount = Decimal(line["taxableAmount"]).quantize(+ Decimal(".0001")+ )details = line.get("details")if not details:return base_rate+# when tax is equal to 0 tax rate for product is still provided# in the response- tax = Decimal(sum([detail.get("tax", 0.0) for detail in details]))- rate = Decimal(sum([detail.get("rate", 0.0) for detail in details]))- return rate if tax != Decimal(0.0) else base_rate- return base_rate-- @staticmethod- def _get_shipping_tax_rate(- response: dict[str, Any],- base_rate: Decimal,- ):- 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 base_rate- return sum(- [Decimal(detail.get("rate", 0.0)) for detail in line_details]- )+ rate = Decimal(0)+ for detail in details:+ if not Decimal(detail.get("tax", 0)):+ # When tax is zero, any rate provided in response should not be+ # included in returned tax-rate+ continue+ taxable_amount_from_detail = Decimal(+ detail.get("taxableAmount", 0)+ ).quantize(Decimal(".0001"))+ if (+ taxable_amount_from_detail+ and taxable_amount_from_detail != taxable_amount+ ):+ logger.warning(+ "taxableAmounts from line.details[] are different than "+ "line.taxableAmount. Returning the rate calculated by "+ "Saleor. For %s:%s",+ related_object_type,+ related_object_id,+ extra={+ "line_taxable_amount": line["taxableAmount"],+ "line_details": [+ {+ "tax": log_detail.get("tax"),+ "taxable_amount": log_detail.get(+ "taxableAmount"+ ),+ "rate": log_detail.get("rate"),+ }+ for log_detail in line["details"]+ ],+ "id": related_object_id,+ "type": related_object_type,+ "item_code": item_code,+ "base_rate": base_rate,+ },+ )+ return base_rate+ rate += Decimal(detail.get("rate", 0.0))+ return ratereturn base_ratedef get_tax_code_from_object_meta(diff --git a/saleor/plugins/avatax/tests/conftest.py b/saleor/plugins/avatax/tests/conftest.pyindex bd7e9198f9..f7f77b2bb4 100644--- a/saleor/plugins/avatax/tests/conftest.py+++ b/saleor/plugins/avatax/tests/conftest.py@@ -219,6 +219,39 @@ def avalara_response_for_checkout_with_items_and_shipping():"reportingTaxCalculated": 0.93,"liabilityType": "Seller",},+ {+ "id": 0,+ "transactionLineId": 0,+ "transactionId": 0,+ "country": "PL",+ "region": "PL",+ "exemptAmount": 0.0,+ "jurisCode": "EU",+ "jurisName": "EUROPE",+ "stateAssignedNo": "",+ "jurisType": "CNT",+ "jurisdictionType": "Country",+ "nonTaxableAmount": 0.0,+ "rate": 0.13,+ "tax": 0.0,+ "taxableAmount": 0,+ "taxType": "Output",+ "taxSubTypeId": "O",+ "taxName": "Standard Rate",+ "taxAuthorityTypeId": 45,+ "taxCalculated": 0,+ "rateType": "Standard",+ "rateTypeCode": "S",+ "unitOfBasis": "PerCurrencyUnit",+ "isNonPassThru": False,+ "isFee": False,+ "reportingTaxableUnits": 0,+ "reportingNonTaxableUnits": 0.0,+ "reportingExemptUnits": 0.0,+ "reportingTax": 0.0,+ "reportingTaxCalculated": 0.0,+ "liabilityType": "Seller",+ },],"nonPassthroughDetails": [],"hsCode": "",@@ -364,3 +397,249 @@ def avalara_response_for_checkout_with_items_and_shipping():}],}+++def avalara_response_with_line_details_and_zero_tax_with_returned_rate():+ return {+ "id": 0,+ "code": "8657e84b-c5ab-4c27-bcc2-c8d3ebbe771b",+ "companyId": 242975,+ "date": "2021-03-18",+ "paymentDate": "2021-03-18",+ "status": "Temporary",+ "type": "SalesOrder",+ "batchCode": "",+ "currencyCode": "USD",+ "exchangeRateCurrencyCode": "USD",+ "customerUsageType": "",+ "entityUseCode": "",+ "customerVendorCode": "0",+ "customerCode": "0",+ "exemptNo": "",+ "reconciled": False,+ "locationCode": "",+ "reportingLocationCode": "",+ "purchaseOrderNo": "",+ "referenceCode": "",+ "salespersonCode": "",+ "totalAmount": 12.2,+ "totalExempt": 0.0,+ "totalDiscount": 0.0,+ "totalTax": 2.8,+ "totalTaxable": 12.2,+ "totalTaxCalculated": 2.8,+ "adjustmentReason": "NotAdjusted",+ "locked": False,+ "version": 1,+ "exchangeRateEffectiveDate": "2021-03-18",+ "exchangeRate": 1.0,+ "email": "",+ "modifiedDate": "2021-03-18T13:23:21.7641305Z",+ "modifiedUserId": 283192,+ "taxDate": "2021-03-18T00:00:00Z",+ "lines": [+ {+ "id": 0,+ "transactionId": 0,+ "lineNumber": "1",+ "customerUsageType": "",+ "entityUseCode": "",+ "description": "Test product",+ "discountAmount": 0.0,+ "exemptAmount": 0.0,+ "exemptCertId": 0,+ "exemptNo": "",+ "isItemTaxable": True,+ "itemCode": "123",+ "lineAmount": 4.07,+ "quantity": 1.0,+ "ref1": "",+ "ref2": "",+ "reportingDate": "2021-03-18",+ "tax": 0.93,+ "taxableAmount": 4.07,+ "taxCalculated": 0.93,+ "taxCode": "O9999999",+ "taxCodeId": 5340,+ "taxDate": "2021-03-18",+ "taxIncluded": True,+ "details": [+ {+ "id": 0,+ "transactionLineId": 0,+ "transactionId": 0,+ "country": "PL",+ "region": "PL",+ "exemptAmount": 0.0,+ "jurisCode": "PL",+ "jurisName": "POLAND",+ "stateAssignedNo": "",+ "jurisType": "CNT",+ "jurisdictionType": "Country",+ "nonTaxableAmount": 0.0,+ "rate": 0.23,+ "tax": 0,+ "taxableAmount": 0,+ "taxType": "Output",+ "taxSubTypeId": "O",+ "taxName": "Standard Rate",+ "taxAuthorityTypeId": 45,+ "taxCalculated": 00,+ "rateType": "Standard",+ "rateTypeCode": "S",+ "unitOfBasis": "PerCurrencyUnit",+ "isNonPassThru": False,+ "isFee": False,+ "reportingTaxableUnits": 0,+ "reportingNonTaxableUnits": 0.0,+ "reportingExemptUnits": 0.0,+ "reportingTax": 0,+ "reportingTaxCalculated": 0,+ "liabilityType": "Seller",+ },+ {+ "id": 0,+ "transactionLineId": 0,+ "transactionId": 0,+ "country": "PL",+ "region": "PL",+ "exemptAmount": 0.0,+ "jurisCode": "EU",+ "jurisName": "EUROPE",+ "stateAssignedNo": "",+ "jurisType": "CNT",+ "jurisdictionType": "Country",+ "nonTaxableAmount": 0.0,+ "rate": 0.13,+ "tax": 0,+ "taxableAmount": 0,+ "taxType": "Output",+ "taxSubTypeId": "O",+ "taxName": "Standard Rate",+ "taxAuthorityTypeId": 45,+ "taxCalculated": 0,+ "rateType": "Standard",+ "rateTypeCode": "S",+ "unitOfBasis": "PerCurrencyUnit",+ "isNonPassThru": False,+ "isFee": False,+ "reportingTaxableUnits": 0,+ "reportingNonTaxableUnits": 0.0,+ "reportingExemptUnits": 0.0,+ "reportingTax": 0.0,+ "reportingTaxCalculated": 0.0,+ "liabilityType": "Seller",+ },+ ],+ "nonPassthroughDetails": [],+ "hsCode": "",+ "costInsuranceFreight": 0.0,+ "vatCode": "PLS-230O--PL",+ "vatNumberTypeId": 0,+ },+ {+ "id": 0,+ "transactionId": 0,+ "lineNumber": "2",+ "customerUsageType": "",+ "entityUseCode": "",+ "discountAmount": 0.0,+ "exemptAmount": 0.0,+ "exemptCertId": 0,+ "exemptNo": "",+ "isItemTaxable": True,+ "itemCode": "Shipping",+ "lineAmount": 8.13,+ "quantity": 1.0,+ "ref1": "",+ "ref2": "",+ "reportingDate": "2021-03-18",+ "tax": 1.87,+ "taxableAmount": 8.13,+ "taxCalculated": 1.87,+ "taxCode": "FR020100",+ "taxCodeId": 4784,+ "taxDate": "2021-03-18",+ "taxIncluded": True,+ "details": [+ {+ "id": 0,+ "transactionLineId": 0,+ "transactionId": 0,+ "country": "PL",+ "region": "PL",+ "exemptAmount": 0.0,+ "jurisCode": "PL",+ "jurisName": "POLAND",+ "stateAssignedNo": "",+ "jurisType": "CNT",+ "jurisdictionType": "Country",+ "nonTaxableAmount": 0.0,+ "rate": 0.23,+ "tax": 0,+ "taxableAmount": 0,+ "taxType": "Output",+ "taxSubTypeId": "O",+ "taxName": "Standard Rate",+ "taxAuthorityTypeId": 45,+ "taxCalculated": 0,+ "rateType": "Standard",+ "rateTypeCode": "S",+ "unitOfBasis": "PerCurrencyUnit",+ "isNonPassThru": False,+ "isFee": False,+ "reportingTaxableUnits": 0,+ "reportingNonTaxableUnits": 0.0,+ "reportingExemptUnits": 0.0,+ "reportingTax": 0,+ "reportingTaxCalculated": 0,+ "liabilityType": "Seller",+ },+ ],+ "nonPassthroughDetails": [],+ "hsCode": "",+ "costInsuranceFreight": 0.0,+ "vatCode": "PLS-230F--PL",+ "vatNumberTypeId": 0,+ },+ ],+ "addresses": [+ {+ "id": 0,+ "transactionId": 0,+ "boundaryLevel": "Zip5",+ "line1": "Teczowa 7",+ "line2": "",+ "line3": "",+ "city": "WROCLAW",+ "region": "",+ "postalCode": "53-601",+ "country": "PL",+ "taxRegionId": 205102,+ "latitude": "",+ "longitude": "",+ }+ ],+ "summary": [+ {+ "country": "PL",+ "region": "PL",+ "jurisType": "Country",+ "jurisCode": "PL",+ "jurisName": "POLAND",+ "taxAuthorityType": 45,+ "stateAssignedNo": "",+ "taxType": "Output",+ "taxSubType": "O",+ "taxName": "Standard Rate",+ "rateType": "Standard",+ "taxable": 12.2,+ "rate": 0.23,+ "tax": 2.8,+ "taxCalculated": 2.8,+ "nonTaxable": 0.0,+ "exemption": 0.0,+ }+ ],+ }diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.pyindex 0e4a8af87c..f8c4a6e57c 100644--- a/saleor/plugins/avatax/tests/test_avatax.py+++ b/saleor/plugins/avatax/tests/test_avatax.py@@ -12,11 +12,7 @@ from requests import RequestExceptionfrom requests_hardened import HTTPSessionfrom ....account.models import Address-from ....checkout.fetch import (- CheckoutInfo,- fetch_checkout_info,- fetch_checkout_lines,-)+from ....checkout.fetch import CheckoutInfo, fetch_checkout_info, fetch_checkout_linesfrom ....checkout.utils import add_variant_to_checkoutfrom ....core.prices import quantize_pricefrom ....core.taxes import (@@ -60,7 +56,7 @@ from .. import (get_order_tax_data,taxes_need_new_fetch,)-from ..plugin import AvataxPlugin+from ..plugin import AvataxPlugin, loggerdef order_set_shipping_method(order, shipping_method):@@ -4187,30 +4183,122 @@ def test_get_checkout_shipping_tax_rate(@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])-def test__get_shipping_tax_rate_handles_multiple_tax_districts(- avalara_response_for_checkout_with_items_and_shipping, channel_USD+def test__get_item_tax_rate_for_shipping_handles_multiple_tax_districts(+ avalara_response_for_checkout_with_items_and_shipping, channel_USD, checkout):manager = get_plugins_manager(allow_replica=False)plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)# 0.46 == sum of two tax districts- assert Decimal("0.46") == plugin._get_shipping_tax_rate(- avalara_response_for_checkout_with_items_and_shipping, Decimal(0.0)+ assert Decimal("0.46") == plugin._get_item_tax_rate(+ avalara_response_for_checkout_with_items_and_shipping,+ "Shipping",+ Decimal(0.0),+ str(checkout.pk),+ "Checkout",).quantize(Decimal(".01"))@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])-def test__get_unit_tax_rate_handles_multiple_tax_districts(- avalara_response_for_checkout_with_items_and_shipping, channel_USD+def test__get_item_tax_rate_handles_multiple_tax_districts(+ avalara_response_for_checkout_with_items_and_shipping, channel_USD, checkout):manager = get_plugins_manager(allow_replica=False)plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)# 0.36 == sum of two tax districts- assert Decimal("0.36") == plugin._get_unit_tax_rate(- avalara_response_for_checkout_with_items_and_shipping, "123", Decimal(0.0)+ assert Decimal("0.36") == plugin._get_item_tax_rate(+ avalara_response_for_checkout_with_items_and_shipping,+ "123",+ Decimal(0.0),+ str(checkout.pk),+ "Checkout",+ ).quantize(Decimal(".01"))+++@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+def test__get_item_tax_rate_handles_tax_zero_and_rate_value(+ avalara_response_with_line_details_and_zero_tax_with_returned_rate,+ channel_USD,+ checkout,+):+ manager = get_plugins_manager(allow_replica=False)+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)++ # 0.36 == sum of two tax districts+ assert Decimal("0") == plugin._get_item_tax_rate(+ avalara_response_with_line_details_and_zero_tax_with_returned_rate,+ "123",+ Decimal(0.0),+ str(checkout.pk),+ "Checkout",+ ).quantize(Decimal(".01"))+++@patch("saleor.plugins.avatax.plugin.logger", wraps=logger)+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+def test__get_item_tax_rate_use_default_value_when_taxable_amount_is_different(+ mocked_logger,+ avalara_response_for_checkout_with_items_and_shipping,+ channel_USD,+ checkout,+):+ # given+ response = avalara_response_for_checkout_with_items_and_shipping+ line_data = response["lines"][0]+ line_taxable_amount = line_data["taxableAmount"]++ response["lines"][0]["details"][0]["taxableAmount"] = line_taxable_amount + 1+ response["lines"][0]["details"][1]["taxableAmount"] = line_taxable_amount + 2++ manager = get_plugins_manager(allow_replica=False)+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)++ default_rate_value = Decimal("0.66")+ object_type = "Checkout"+ item_code = "123"++ # when+ returned_tax_rate = plugin._get_item_tax_rate(+ response, item_code, default_rate_value, str(checkout.pk), object_type).quantize(Decimal(".01"))+ # then+ assert default_rate_value == returned_tax_rate++ line_details = line_data["details"]+ mocked_logger.warning.assert_called_once_with(+ "taxableAmounts from line.details[] are different than "+ "line.taxableAmount. Returning the rate calculated by "+ "Saleor. For %s:%s",+ object_type,+ str(checkout.pk),+ extra={+ "line_taxable_amount": line_taxable_amount,+ "line_details": [+ {+ "tax": line_details[0]["tax"],+ "taxable_amount": line_taxable_amount + 1,+ "rate": line_details[0]["rate"],+ },+ {+ "tax": line_details[1]["tax"],+ "taxable_amount": line_taxable_amount + 2,+ "rate": line_details[1]["rate"],+ },+ {+ "tax": line_details[2]["tax"],+ "taxable_amount": line_details[2]["taxableAmount"],+ "rate": line_details[2]["rate"],+ },+ ],+ "id": str(checkout.pk),+ "type": object_type,+ "item_code": item_code,+ "base_rate": default_rate_value,+ },+ )+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])def test_get_checkout_shipping_tax_rate_checkout_not_valid_default_value_returned(diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 838b6f6688..9243d6ea40 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -619,10 +619,10 @@ class PluginsManager(PaymentInterface):product: "Product",variant: "ProductVariant",address: Optional["Address"],- unit_price: TaxedMoney,+ price: TaxedMoney,plugin_ids: Optional[list[str]] = None,) -> Decimal:- default_value = calculate_tax_rate(unit_price)+ default_value = calculate_tax_rate(price)return self.__run_method_on_plugins("get_order_line_tax_rate",default_value,