Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix: AvataxPlugin: Correct tax calculation for duplicate variant lines (#18465)
Maciej Korycinski7a4e9b6bfc0e
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.pyindex e77ccf8c5a..4fd66698b2 100644--- a/saleor/checkout/tests/test_calculations.py+++ b/saleor/checkout/tests/test_calculations.py@@ -46,10 +46,7 @@ from ..calculations import ()from ..fetch import CheckoutLineInfo, fetch_checkout_info, fetch_checkout_linesfrom ..models import Checkout-from ..utils import (- add_promo_code_to_checkout,- assign_external_shipping_to_checkout,-)+from ..utils import add_promo_code_to_checkout, assign_external_shipping_to_checkout@pytest.fixture@@ -1175,18 +1172,18 @@ def test_fetch_order_data_plugin_tax_data_with_negative_values(channel.tax_configuration.save(update_fields=["tax_app_id"])tax_data = {- "lines": [- {+ "lines": {+ str(checkout.lines.first().id): {"lineAmount": 30.0000,"quantity": 3.0,"itemCode": "SKU_A",},- {+ "Shipping": {"lineAmount": -8.1300,"quantity": 1.0,"itemCode": "Shipping",},- ]+ }}mock_get_tax_data.return_value = tax_data@@ -1220,18 +1217,18 @@ def test_fetch_order_data_plugin_tax_data_price_overflow(channel.tax_configuration.save(update_fields=["tax_app_id"])tax_data = {- "lines": [- {+ "lines": {+ str(checkout.lines.first().id): {"lineAmount": 3892370265647658029.0000,"quantity": 3.0,"itemCode": "SKU_A",},- {+ "Shipping": {"lineAmount": 8.1300,"quantity": 1.0,"itemCode": "Shipping",},- ]+ }}mock_get_tax_data.return_value = tax_datadiff --git a/saleor/order/calculations.py b/saleor/order/calculations.pyindex 19aad9330d..9deb60ec38 100644--- a/saleor/order/calculations.py+++ b/saleor/order/calculations.py@@ -357,6 +357,7 @@ def _recalculate_with_plugins(line.tax_rate = manager.get_order_line_tax_rate(order,+ line,product,variant,None,diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.pyindex f141c26df5..7b30cbd6ff 100644--- a/saleor/order/tests/test_calculations.py+++ b/saleor/order/tests/test_calculations.py@@ -1715,23 +1715,23 @@ def test_fetch_order_data_plugin_tax_data_with_negative_values(channel.tax_configuration.save(update_fields=["tax_app_id"])tax_data = {- "lines": [- {+ "lines": {+ str(order_with_lines.lines.all()[0].id): {"lineAmount": -30.0000,"quantity": 3.0,"itemCode": "SKU_A",},- {+ str(order_with_lines.lines.all()[1].id): {"lineAmount": 40.0000,"quantity": 2.0,"itemCode": "SKU_B",},- {+ "Shipping": {"lineAmount": 8.1300,"quantity": 1.0,"itemCode": "Shipping",},- ]+ }}mock_get_tax_data.return_value = tax_data@@ -1763,23 +1763,23 @@ def test_fetch_order_data_plugin_tax_data_price_overflow(channel.tax_configuration.save(update_fields=["tax_app_id"])tax_data = {- "lines": [- {+ "lines": {+ str(order_with_lines.lines.all()[0].id): {"lineAmount": 30.0000,"quantity": 3.0,"itemCode": "SKU_A",},- {+ str(order_with_lines.lines.all()[1].id): {"lineAmount": 40.0000,"quantity": 2.0,"itemCode": "SKU_B",},- {+ "Shipping": {"lineAmount": 83689989725697628976.1300,"quantity": 1.0,"itemCode": "Shipping",},- ]+ }}mock_get_tax_data.return_value = tax_datadiff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.pyindex 8e9ae14f20..7f8db05304 100644--- a/saleor/plugins/avatax/__init__.py+++ b/saleor/plugins/avatax/__init__.py@@ -1,6 +1,7 @@import datetimeimport jsonimport logging+from collections.abc import Iteratorfrom dataclasses import dataclassfrom decimal import Decimalfrom typing import TYPE_CHECKING, Any, cast@@ -30,8 +31,8 @@ from ...warehouse.models import Warehouseif TYPE_CHECKING:from ...checkout.fetch import CheckoutInfo, CheckoutLineInfo- from ...order.models import Order- from ...product.models import Product, ProductType+ from ...order.models import Order, OrderLine+ from ...product.models import Product, ProductType, ProductVariantfrom ...tax.models import TaxClass@@ -241,6 +242,7 @@ def append_line_to_data(tax_override_data: dict | None = None,ref1: str | None = None,ref2: str | None = None,+ number: str | None = None,):line_data = {"quantity": quantity,@@ -252,6 +254,8 @@ def append_line_to_data("description": name,}+ if number:+ line_data["number"] = numberif tax_override_data:line_data["taxOverride"] = tax_override_dataif ref1:@@ -296,7 +300,7 @@ def generate_request_data_from_checkout_lines(bool(checkout_info.discounts) or is_entire_order_discount)- for line_info in lines_info:+ for index, line_info in enumerate(lines_info, start=1):product = line_info.productproduct_type = line_info.product_typetax_code = _get_product_tax_code(product, product_type)@@ -341,6 +345,7 @@ def generate_request_data_from_checkout_lines("prices_entered_with_tax": prices_entered_with_tax,"discounted": applicable_checkout_discount,"tax_override_data": tax_override_data,+ "number": str(index),}append_line_to_data(@@ -368,19 +373,17 @@ def generate_request_data_from_checkout_lines(def get_order_lines_data(- order: "Order", config: AvataxConfiguration, discounted: bool+ order: "Order",+ config: AvataxConfiguration,+ discounted: bool,+ lines: list["OrderLine"],) -> list[dict[str, str | int | bool | None]]:data: list[dict[str, str | int | bool | None]] = []- lines = order.lines.prefetch_related(- "variant__product__category",- "variant__product__collections",- "variant__product__product_type",- )tax_configuration = order.channel.tax_configurationprices_entered_with_tax = tax_configuration.prices_entered_with_tax- for line in lines:+ for line_number, line in enumerate(lines, start=1):if not line.variant:continue@@ -416,6 +419,7 @@ def get_order_lines_data("name": line.variant.product.name,"prices_entered_with_tax": prices_entered_with_tax,"discounted": discounted,+ "number": str(line_number),}append_line_to_data(**append_line_to_data_kwargs,@@ -597,16 +601,69 @@ def get_cached_response_or_fetch(return response+def iter_checkout_lines(+ lines_info: list["CheckoutLineInfo"],+) -> Iterator[tuple[str, "ProductVariant", str]]:+ for index, line_info in enumerate(lines_info, start=1):+ yield str(index), line_info.variant, str(line_info.line.id)+++def iter_order_lines(+ order_lines: list["OrderLine"],+) -> Iterator[tuple[str, "ProductVariant", str]]:+ for index, line in enumerate(order_lines, start=1):+ if not line.variant:+ continue+ yield str(index), line.variant, str(line.id)+++def convert_response_lines_list_to_dict(+ response: dict[str, Any],+ lines_iterable: Iterator[tuple[str, "ProductVariant", str]],+):+ # Convert `lines` to dict as we can send multiple lines with the same itemCode+ # and we need to be able to find proper line by line id.+ lines_from_response = {+ line["lineNumber"]: line for line in response.get("lines", [])+ }+ line_data_dict = {}+ for line_index, variant, line_id in lines_iterable:+ response_line = lines_from_response.get(line_index)+ if not response_line:+ continue++ variant_item_code = variant.sku or variant.get_global_id()+ if response_line.get("itemCode") != variant_item_code:+ continue++ line_data_dict[line_id] = response_line++ for item in response.get("lines", []):+ if item.get("itemCode") == SHIPPING_ITEM_CODE:+ line_data_dict[SHIPPING_ITEM_CODE] = item+ response["lines"] = line_data_dict++def get_checkout_tax_data(checkout_info: "CheckoutInfo",lines_info: list["CheckoutLineInfo"],config: AvataxConfiguration,-) -> dict[str, Any]:+) -> dict[str, Any] | None:data = generate_request_data_from_checkout(checkout_info, lines_info, config)- return get_cached_response_or_fetch(data, str(checkout_info.checkout.token), config)+ response = get_cached_response_or_fetch(+ data, str(checkout_info.checkout.token), config+ )++ if response is None:+ return response++ convert_response_lines_list_to_dict(response, iter_checkout_lines(lines_info))+ return response-def get_order_request_data(order: "Order", config: AvataxConfiguration):+def get_order_request_data(+ order: "Order", config: AvataxConfiguration, order_lines: list["OrderLine"]+):address = get_address_for_order_taxes(order)transaction = (TransactionType.INVOICE@@ -615,7 +672,9 @@ def get_order_request_data(order: "Order", config: AvataxConfiguration):)discount_amount = get_total_order_discount_excluding_shipping(order).amountdiscounted_lines = discount_amount != Decimal(0)- lines = get_order_lines_data(order, config, discounted=discounted_lines)+ lines = get_order_lines_data(+ order, config, discounted=discounted_lines, lines=order_lines+ )# if there is no lines to sent we do not want to send the request to avalaraif not lines:return {}@@ -634,8 +693,15 @@ def get_order_request_data(order: "Order", config: AvataxConfiguration):def get_order_tax_data(order: "Order", config: AvataxConfiguration, force_refresh=False-) -> dict[str, Any]:- data = get_order_request_data(order, config)+) -> dict[str, Any] | None:+ order_lines = list(+ order.lines.prefetch_related(+ "variant__product__category",+ "variant__product__collections",+ "variant__product__product_type",+ ).all()+ )+ data = get_order_request_data(order, config, order_lines)response = get_cached_response_or_fetch(data, f"order_{order.id}", config, force_refresh)@@ -650,6 +716,10 @@ def get_order_tax_data()log_address_if_validation_skipped_for_order(order, logger)raise TaxError(response.get("error"))+ if response is None:+ return response++ convert_response_lines_list_to_dict(response, iter_order_lines(order_lines))return responsediff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.pyindex 5d393c1e58..e861e60793 100644--- a/saleor/plugins/avatax/plugin.py+++ b/saleor/plugins/avatax/plugin.py@@ -229,7 +229,7 @@ class DeprecatedAvataxPlugin(BasePlugin):for line in lines:taxed_line_total_data = self._calculate_checkout_line_total_price(taxes_data=response,- item_code=line.variant.sku or line.variant.get_global_id(),+ checkout_line_id=str(line.line.id),prices_entered_with_tax=prices_entered_with_tax,# for some cases we will need a base_value but no need to call it for# each line@@ -243,7 +243,7 @@ class DeprecatedAvataxPlugin(BasePlugin):checkout_info, lines)shipping_price = self._calculate_checkout_shipping(- checkout_info, currency, response.get("lines", []), base_shipping_price+ checkout_info, currency, response.get("lines", {}), base_shipping_price)taxed_total += shipping_price@@ -257,21 +257,20 @@ class DeprecatedAvataxPlugin(BasePlugin):self,checkout_info: "CheckoutInfo",currency: str,- lines: list[dict],+ lines: dict[str, dict],shipping_price: Money,) -> TaxedMoney:discount_amount = Decimal(0.0)shipping_tax = Decimal(0.0)shipping_net = shipping_price.amount- for line in lines:- 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.- shipping_net = Decimal(line["lineAmount"])- discount_amount = Decimal(line.get("discountAmount", 0.0))- shipping_tax = Decimal(line["tax"])- break+ line = lines.get(SHIPPING_ITEM_CODE)+ if line:+ # The lineAmount does not include the discountAmount,+ # but tax is calculated for discounted net price, that+ # take into account provided discount.+ shipping_net = Decimal(line["lineAmount"])+ discount_amount = Decimal(line.get("discountAmount", 0.0))+ shipping_tax = Decimal(line["tax"])prices_entered_with_tax = partial(_get_prices_entered_with_tax_for_checkout, checkout_info@@ -304,7 +303,7 @@ class DeprecatedAvataxPlugin(BasePlugin):currency = str(response.get("currencyCode"))return self._calculate_checkout_shipping(- checkout_info, currency, response.get("lines", []), base_shipping_price.net+ checkout_info, currency, response.get("lines", {}), base_shipping_price.net)def preprocess_order_creation(@@ -381,7 +380,14 @@ class DeprecatedAvataxPlugin(BasePlugin):):return previous_value- request_data = get_order_request_data(order, self.config)+ order_lines = list(+ order.lines.prefetch_related(+ "variant__product__category",+ "variant__product__collections",+ "variant__product__product_type",+ ).all()+ )+ request_data = get_order_request_data(order, self.config, order_lines)if not request_data:return previous_value@@ -410,14 +416,13 @@ class DeprecatedAvataxPlugin(BasePlugin):)taxes_data = self._get_checkout_tax_data(checkout_info, lines, previous_value)- variant = checkout_line_info.variantif not taxes_data or "error" in taxes_data:return previous_valuereturn self._calculate_checkout_line_total_price(taxes_data,- variant.sku or variant.get_global_id(),+ str(checkout_line_info.line.id),prices_entered_with_tax,base_value=SimpleLazyObject(lambda: base_calculations.calculate_base_line_total_price(@@ -429,17 +434,15 @@ class DeprecatedAvataxPlugin(BasePlugin):@staticmethoddef _calculate_checkout_line_total_price(taxes_data: dict[str, Any],- item_code: str,+ checkout_line_id: str,prices_entered_with_tax: Callable[[], bool],# base_value should be provided as SimpleLazyObjectbase_value: Money,) -> TaxedMoney:- currency = taxes_data.get("currencyCode")-- for line in taxes_data.get("lines", []):- if line.get("itemCode") != item_code:- continue+ currency: str = taxes_data.get("currencyCode") or base_value.currency+ line = taxes_data.get("lines", {}).get(checkout_line_id)+ if line:# The lineAmount does not include the discountAmount, but tax is calculated# for discounted net price, that take into account provided discount.tax = Decimal(line.get("tax", 0.0))@@ -458,7 +461,6 @@ class DeprecatedAvataxPlugin(BasePlugin):net -= discount_amountline_gross = Money(amount=net + tax, currency=currency)line_net = Money(amount=net, currency=currency)-return TaxedMoney(net=line_net, gross=line_gross)if isinstance(base_value, SimpleLazyObject):base_value = base_value._setupfunc() # type: ignore[attr-defined]@@ -485,15 +487,15 @@ class DeprecatedAvataxPlugin(BasePlugin):taxes_data = self._get_order_tax_data(order, previous_value)return self._calculate_order_line_total_price(taxes_data,- variant.sku or variant.get_global_id(),+ str(order_line.id),prices_entered_with_tax,base_value,)@staticmethoddef _calculate_order_line_total_price(- taxes_data: dict[str, Any],- item_code: str,+ taxes_data: dict[str, Any] | None,+ order_line_id: str,prices_entered_with_tax: Callable[[], bool],base_value: OrderTaxedPricesData,) -> OrderTaxedPricesData:@@ -503,10 +505,8 @@ class DeprecatedAvataxPlugin(BasePlugin):currency = taxes_data.get("currencyCode")line_price_with_discounts = None- for line in taxes_data.get("lines", []):- if line.get("itemCode") != item_code:- continue-+ line = taxes_data.get("lines", {}).get(order_line_id)+ if line:# The lineAmount does not include the discountAmount, but tax is calculated# for discounted net price, that take into account provided discount.tax = Decimal(line.get("tax", 0.0))@@ -550,7 +550,6 @@ class DeprecatedAvataxPlugin(BasePlugin):prices_entered_with_tax = partial(_get_prices_entered_with_tax_for_checkout, checkout_info)- variant = checkout_line_info.variantquantity = checkout_line_info.line.quantitytaxes_data = self._get_checkout_tax_data(checkout_info, lines, previous_value)@@ -559,7 +558,7 @@ class DeprecatedAvataxPlugin(BasePlugin):taxed_total_price = self._calculate_checkout_line_total_price(taxes_data,- variant.sku or variant.get_global_id(),+ str(checkout_line_info.line.id),prices_entered_with_tax,base_value=SimpleLazyObject(lambda: base_calculations.calculate_base_line_total_price(@@ -590,7 +589,7 @@ class DeprecatedAvataxPlugin(BasePlugin):taxed_total_prices_data = self._calculate_order_line_total_price(taxes_data,- variant.sku or variant.get_global_id(),+ str(order_line.id),prices_entered_with_tax,base_total,)@@ -603,18 +602,18 @@ class DeprecatedAvataxPlugin(BasePlugin):def _calculate_order_shipping(self, order, taxes_data) -> TaxedMoney: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_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- if currency == "JPY" and prices_entered_with_tax():- gross = order.base_shipping_price- net = Money(amount=gross.amount - tax, currency=currency)- else:- gross = Money(amount=net + tax, currency=currency)- net = Money(amount=net, currency=currency)- return TaxedMoney(net=net, gross=gross)+ line = taxes_data.get("lines", {}).get(SHIPPING_ITEM_CODE)+ if line:+ tax = Decimal(line.get("tax", 0.0))+ discount_amount = Decimal(line.get("discountAmount", 0.0))+ net = Decimal(line.get("lineAmount", 0.0)) - discount_amount+ if currency == "JPY" and prices_entered_with_tax():+ gross = order.base_shipping_price+ net = Money(amount=gross.amount - tax, currency=currency)+ else:+ gross = Money(amount=net + tax, currency=currency)+ net = Money(amount=net, currency=currency)+ return TaxedMoney(net=net, gross=gross)price = order.base_shipping_pricereturn TaxedMoney(@@ -652,7 +651,7 @@ class DeprecatedAvataxPlugin(BasePlugin):)taxed_line_total_data = self._calculate_order_line_total_price(taxes_data,- line.product_sku or line.variant_name,+ str(line.id),prices_entered_with_tax,base_line_price,).price_with_discounts@@ -690,10 +689,9 @@ class DeprecatedAvataxPlugin(BasePlugin):return previous_valueresponse = self._get_checkout_tax_data(checkout_info, lines, previous_value)- variant = checkout_line_info.variantreturn self._get_item_tax_rate(response,- variant.sku or variant.get_global_id(),+ str(checkout_line_info.line.id),previous_value,str(checkout_info.checkout.pk),"Checkout",@@ -702,6 +700,7 @@ class DeprecatedAvataxPlugin(BasePlugin):def get_order_line_tax_rate(self,order: "Order",+ order_line: "OrderLine",product: "Product",variant: "ProductVariant",address: Optional["Address"],@@ -714,7 +713,7 @@ class DeprecatedAvataxPlugin(BasePlugin):response = self._get_order_tax_data(order, previous_value)return self._get_item_tax_rate(response,- variant.sku or variant.get_global_id(),+ str(order_line.id),previous_value,str(order.pk),"Order",@@ -730,16 +729,20 @@ class DeprecatedAvataxPlugin(BasePlugin):response = self._get_checkout_tax_data(checkout_info, lines, previous_value)return self._get_item_tax_rate(response,- SHIPPING_ITEM_CODE,- previous_value,- str(checkout_info.checkout.pk),- "Checkout",+ object_line_id=SHIPPING_ITEM_CODE,+ base_rate=previous_value,+ related_object_id=str(checkout_info.checkout.pk),+ related_object_type="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_item_tax_rate(- response, SHIPPING_ITEM_CODE, previous_value, str(order.pk), "Order"+ response,+ object_line_id=SHIPPING_ITEM_CODE,+ base_rate=previous_value,+ related_object_id=str(order.pk),+ related_object_type="Order",)def _get_checkout_tax_data(@@ -787,7 +790,7 @@ class DeprecatedAvataxPlugin(BasePlugin):def _get_order_tax_data(self, order: "Order", base_value: Decimal | OrderTaxedPricesData- ):+ ) -> dict[str, Any] | None:if self._skip_plugin(base_value):self._set_order_tax_error(order, TaxDataErrorMessage.EMPTY)return None@@ -816,66 +819,62 @@ class DeprecatedAvataxPlugin(BasePlugin):@staticmethoddef _get_item_tax_rate(- response: dict[str, Any],- item_code: str,+ response: dict[str, Any] | None,+ object_line_id: str,base_rate: Decimal,related_object_id: str,related_object_type: str,):if response is None:return base_rate- lines_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:+ lines_data = response.get("lines", {})+ line = lines_data.get(object_line_id)+ if line:+ 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+ 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,+ "object_line_id": object_line_id,+ "base_rate": base_rate,+ },+ )return base_rate-- # when tax is equal to 0 tax rate for product is still provided- # in the response- 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 rate+ rate += Decimal(detail.get("rate", 0.0))+ return ratereturn base_ratedef get_tax_code_from_object_meta(@@ -980,7 +979,7 @@ class DeprecatedAvataxPlugin(BasePlugin):if not tax_data:return False- for line in tax_data.get("lines", []):+ for line in tax_data.get("lines", {}).values():if line.get("lineAmount", 0) < 0:return True@@ -992,7 +991,7 @@ class DeprecatedAvataxPlugin(BasePlugin):if not tax_data:return False- for line in tax_data.get("lines", []):+ for line in tax_data.get("lines", {}).values():if line.get("lineAmount", 0) > MAXIMUM_PRICE:return Truediff --git a/saleor/plugins/avatax/tests/conftest.py b/saleor/plugins/avatax/tests/conftest.pyindex fe1d859c53..fadcf4e573 100644--- a/saleor/plugins/avatax/tests/conftest.py+++ b/saleor/plugins/avatax/tests/conftest.py@@ -643,3 +643,337 @@ def avalara_response_with_line_details_and_zero_tax_with_returned_rate():}],}+++def test_response_multiple_lines_with_same_item_code():+ return {+ "id": 0,+ "code": "139256ab-1bd9-4573-951c-e612314e2014",+ "companyId": 7799660,+ "date": "2025-11-06",+ "paymentDate": "2025-11-06",+ "status": "Temporary",+ "type": "SalesOrder",+ "batchCode": "",+ "currencyCode": "USD",+ "exchangeRateCurrencyCode": "USD",+ "customerUsageType": "",+ "entityUseCode": "",+ "customerVendorCode": "0",+ "customerCode": "0",+ "exemptNo": "",+ "reconciled": False,+ "locationCode": "",+ "reportingLocationCode": "",+ "purchaseOrderNo": "",+ "referenceCode": "",+ "salespersonCode": "",+ "totalAmount": 62.33,+ "totalExempt": 0.0,+ "totalDiscount": 0.0,+ "totalTax": 14.34,+ "totalTaxable": 62.33,+ "totalTaxCalculated": 14.34,+ "adjustmentReason": "NotAdjusted",+ "locked": False,+ "version": 1,+ "originAddressId": 2,+ "destinationAddressId": 1,+ "exchangeRateEffectiveDate": "2025-11-06",+ "exchangeRate": 1.0,+ "email": "[email protected]",+ "modifiedDate": "2025-11-06T11:57:33.6683291Z",+ "modifiedUserId": 6479978,+ "taxDate": "2025-11-06",+ "lines": [+ {+ "id": 0,+ "transactionId": 0,+ "lineNumber": "1",+ "customerUsageType": "",+ "entityUseCode": "",+ "description": "Test product",+ "destinationAddressId": 1,+ "originAddressId": 2,+ "discountAmount": 0.0,+ "exemptAmount": 0.0,+ "exemptCertId": 0,+ "exemptNo": "",+ "isItemTaxable": True,+ "itemCode": "123",+ "lineAmount": 30.0,+ "quantity": 3.0,+ "ref1": "123",+ "ref2": "",+ "reportingDate": "2025-11-06",+ "revAccount": "",+ "sourcing": "Destination",+ "tax": 6.9,+ "taxableAmount": 30.0,+ "taxCalculated": 6.9,+ "taxCode": "O9999999",+ "taxCodeId": 9111,+ "taxDate": "2025-11-06",+ "taxIncluded": False,+ "details": [+ {+ "id": 0,+ "transactionLineId": 0,+ "transactionId": 0,+ "country": "PL",+ "region": "PL",+ "stateFIPS": "PL",+ "exemptAmount": 0.0,+ "jurisCode": "PL",+ "jurisName": "POLAND",+ "jurisdictionId": 200102,+ "stateAssignedNo": "",+ "jurisType": "CNT",+ "jurisdictionType": "Country",+ "nonTaxableAmount": 0.0,+ "rate": 0.230000,+ "sourcing": "Destination",+ "tax": 6.9,+ "taxableAmount": 30.0,+ "taxType": "Output",+ "taxSubTypeId": "O",+ "taxName": "Standard Rate",+ "taxAuthorityTypeId": 45,+ "taxCalculated": 6.9,+ "rateType": "Standard",+ "rateTypeCode": "S",+ "taxableUnits": 30.0000,+ "nonTaxableUnits": 0.0000,+ "exemptUnits": 0.0000,+ "unitOfBasis": "PerCurrencyUnit",+ "isNonPassThru": False,+ "isFee": False,+ "reportingTaxableUnits": 30.0,+ "reportingNonTaxableUnits": 0.0,+ "reportingExemptUnits": 0.0,+ "reportingTax": 6.9,+ "reportingTaxCalculated": 6.9,+ "liabilityType": "Seller",+ "chargedTo": "Buyer",+ "vatCode": "PL_S_-_230_C",+ }+ ],+ "nonPassthroughDetails": [],+ "hsCode": "",+ "costInsuranceFreight": 0.0,+ "vatCode": "PLS-230C",+ "vatNumberTypeId": 0,+ },+ {+ "id": 0,+ "transactionId": 0,+ "lineNumber": "2",+ "customerUsageType": "",+ "entityUseCode": "",+ "description": "Test product",+ "destinationAddressId": 1,+ "originAddressId": 2,+ "discountAmount": 0.0,+ "exemptAmount": 0.0,+ "exemptCertId": 0,+ "exemptNo": "",+ "isItemTaxable": True,+ "itemCode": "123",+ "lineAmount": 22.33,+ "quantity": 1.0,+ "ref1": "123",+ "ref2": "",+ "reportingDate": "2025-11-06",+ "revAccount": "",+ "sourcing": "Destination",+ "tax": 5.14,+ "taxableAmount": 22.33,+ "taxCalculated": 5.14,+ "taxCode": "O9999999",+ "taxCodeId": 9111,+ "taxDate": "2025-11-06",+ "taxIncluded": False,+ "details": [+ {+ "id": 0,+ "transactionLineId": 0,+ "transactionId": 0,+ "country": "PL",+ "region": "PL",+ "stateFIPS": "PL",+ "exemptAmount": 0.0,+ "jurisCode": "PL",+ "jurisName": "POLAND",+ "jurisdictionId": 200102,+ "stateAssignedNo": "",+ "jurisType": "CNT",+ "jurisdictionType": "Country",+ "nonTaxableAmount": 0.0,+ "rate": 0.230000,+ "sourcing": "Destination",+ "tax": 5.14,+ "taxableAmount": 22.33,+ "taxType": "Output",+ "taxSubTypeId": "O",+ "taxName": "Standard Rate",+ "taxAuthorityTypeId": 45,+ "taxCalculated": 5.14,+ "rateType": "Standard",+ "rateTypeCode": "S",+ "taxableUnits": 22.3300,+ "nonTaxableUnits": 0.0000,+ "exemptUnits": 0.0000,+ "unitOfBasis": "PerCurrencyUnit",+ "isNonPassThru": False,+ "isFee": False,+ "reportingTaxableUnits": 22.33,+ "reportingNonTaxableUnits": 0.0,+ "reportingExemptUnits": 0.0,+ "reportingTax": 5.14,+ "reportingTaxCalculated": 5.14,+ "liabilityType": "Seller",+ "chargedTo": "Buyer",+ "vatCode": "PL_S_-_230_C",+ }+ ],+ "nonPassthroughDetails": [],+ "hsCode": "",+ "costInsuranceFreight": 0.0,+ "vatCode": "PLS-230C",+ "vatNumberTypeId": 0,+ },+ {+ "id": 0,+ "transactionId": 0,+ "lineNumber": "3",+ "customerUsageType": "",+ "entityUseCode": "",+ "destinationAddressId": 1,+ "originAddressId": 2,+ "discountAmount": 0.0,+ "exemptAmount": 0.0,+ "exemptCertId": 0,+ "exemptNo": "",+ "isItemTaxable": True,+ "itemCode": "Shipping",+ "lineAmount": 10.0,+ "quantity": 1.0,+ "ref1": "",+ "ref2": "",+ "reportingDate": "2025-11-06",+ "revAccount": "",+ "sourcing": "Destination",+ "tax": 2.3,+ "taxableAmount": 10.0,+ "taxCalculated": 2.3,+ "taxCode": "FR000000",+ "taxCodeId": 8550,+ "taxDate": "2025-11-06",+ "taxIncluded": False,+ "details": [+ {+ "id": 0,+ "transactionLineId": 0,+ "transactionId": 0,+ "country": "PL",+ "region": "PL",+ "stateFIPS": "PL",+ "exemptAmount": 0.0,+ "jurisCode": "PL",+ "jurisName": "POLAND",+ "jurisdictionId": 200102,+ "stateAssignedNo": "",+ "jurisType": "CNT",+ "jurisdictionType": "Country",+ "nonTaxableAmount": 0.0,+ "rate": 0.230000,+ "sourcing": "Destination",+ "tax": 2.3,+ "taxableAmount": 10.0,+ "taxType": "Output",+ "taxSubTypeId": "O",+ "taxName": "Standard Rate",+ "taxAuthorityTypeId": 45,+ "taxCalculated": 2.3,+ "rateType": "Standard",+ "rateTypeCode": "S",+ "taxableUnits": 10.0000,+ "nonTaxableUnits": 0.0000,+ "exemptUnits": 0.0000,+ "unitOfBasis": "PerCurrencyUnit",+ "isNonPassThru": False,+ "isFee": False,+ "reportingTaxableUnits": 10.0,+ "reportingNonTaxableUnits": 0.0,+ "reportingExemptUnits": 0.0,+ "reportingTax": 2.3,+ "reportingTaxCalculated": 2.3,+ "liabilityType": "Seller",+ "chargedTo": "Buyer",+ "vatCode": "PL_S_-_230_D",+ }+ ],+ "nonPassthroughDetails": [],+ "hsCode": "",+ "costInsuranceFreight": 0.0,+ "vatCode": "PLS-230D",+ "vatNumberTypeId": 0,+ },+ ],+ "addresses": [+ {+ "id": 1,+ "transactionId": 0,+ "boundaryLevel": "Zip5",+ "line1": "Olawska 10",+ "line2": "",+ "line3": "",+ "city": "WROCLAW",+ "region": "",+ "postalCode": "53-105",+ "country": "PL",+ "taxRegionId": 205102,+ "taxRegionIdAv": 0,+ "latitude": "",+ "longitude": "",+ },+ {+ "id": 2,+ "transactionId": 0,+ "boundaryLevel": "Zip5",+ "line1": "Teczowa 7",+ "line2": "",+ "line3": "",+ "city": "Wroclaw",+ "region": "",+ "postalCode": "53-601",+ "country": "PL",+ "taxRegionId": 205102,+ "taxRegionIdAv": 0,+ "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": 62.33,+ "rate": 0.230000,+ "tax": 14.34,+ "taxCalculated": 14.34,+ "nonTaxable": 0.0,+ "exemption": 0.0,+ }+ ],+ }diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.pyindex 08f4666314..1b379c16ec 100644--- a/saleor/plugins/avatax/tests/test_avatax.py+++ b/saleor/plugins/avatax/tests/test_avatax.py@@ -1,4 +1,5 @@import datetime+from copy import deepcopyfrom decimal import Decimalfrom json import JSONDecodeErrorfrom unittest.mock import Mock, patch@@ -29,7 +30,7 @@ from ....discount.utils.checkout import ()from ....order import OrderStatusfrom ....product import ProductTypeKind-from ....product.models import Product, ProductType+from ....product.models import Product, ProductType, ProductVariantfrom ....product.utils.variant_prices import update_discounted_prices_for_promotionfrom ....product.utils.variants import fetch_variants_for_promotion_rulesfrom ....tax import TaxCalculationStrategy@@ -40,6 +41,7 @@ from .. import (DEFAULT_TAX_CODE,META_CODE_KEY,META_DESCRIPTION_KEY,+ SHIPPING_ITEM_CODE,TAX_CODE_NON_TAXABLE_PRODUCT,AvataxConfiguration,TransactionType,@@ -4086,6 +4088,7 @@ def test_get_order_line_tax_rate(# whentax_rate = manager.get_order_line_tax_rate(order,+ order_line,product,order_line.variant,None,@@ -4112,6 +4115,7 @@ def test_get_order_line_tax_rate_order_not_valid_default_value_returned(# whentax_rate = manager.get_order_line_tax_rate(order,+ order_line,product,order_line.variant,None,@@ -4147,6 +4151,7 @@ def test_get_order_line_tax_rate_error_in_response(# whentax_rate = manager.get_order_line_tax_rate(order,+ order_line,product,order_line.variant,None,@@ -4195,11 +4200,16 @@ def test__get_item_tax_rate_for_shipping_handles_multiple_tax_districts():manager = get_plugins_manager(allow_replica=False)plugin = manager.get_plugin(DeprecatedAvataxPlugin.PLUGIN_ID, channel_USD.slug)+ shipping_line = next(+ line+ for line in avalara_response_for_checkout_with_items_and_shipping["lines"]+ if line["itemCode"] == SHIPPING_ITEM_CODE+ )# 0.46 == sum of two tax districtsassert Decimal("0.46") == plugin._get_item_tax_rate(- avalara_response_for_checkout_with_items_and_shipping,- "Shipping",+ {"lines": {SHIPPING_ITEM_CODE: shipping_line}},+ SHIPPING_ITEM_CODE,Decimal(0.0),str(checkout.pk),"Checkout",@@ -4212,11 +4222,17 @@ def test__get_item_tax_rate_handles_multiple_tax_districts():manager = get_plugins_manager(allow_replica=False)plugin = manager.get_plugin(DeprecatedAvataxPlugin.PLUGIN_ID, channel_USD.slug)+ line_id = "123"+ line = next(+ line+ for line in avalara_response_for_checkout_with_items_and_shipping["lines"]+ if line["itemCode"] == line_id+ )# 0.36 == sum of two tax districtsassert Decimal("0.36") == plugin._get_item_tax_rate(- avalara_response_for_checkout_with_items_and_shipping,- "123",+ {"lines": {line_id: line}},+ line_id,Decimal(0.0),str(checkout.pk),"Checkout",@@ -4231,11 +4247,19 @@ def test__get_item_tax_rate_handles_tax_zero_and_rate_value():manager = get_plugins_manager(allow_replica=False)plugin = manager.get_plugin(DeprecatedAvataxPlugin.PLUGIN_ID, channel_USD.slug)+ line_id = "123"+ line = next(+ line+ for line in avalara_response_with_line_details_and_zero_tax_with_returned_rate[+ "lines"+ ]+ if line["itemCode"] == line_id+ )# 0.36 == sum of two tax districtsassert Decimal(0) == plugin._get_item_tax_rate(- avalara_response_with_line_details_and_zero_tax_with_returned_rate,- "123",+ {"lines": {line_id: line}},+ line_id,Decimal(0.0),str(checkout.pk),"Checkout",@@ -4267,7 +4291,11 @@ def test__get_item_tax_rate_use_default_value_when_taxable_amount_is_different(# whenreturned_tax_rate = plugin._get_item_tax_rate(- response, item_code, default_rate_value, str(checkout.pk), object_type+ {"lines": {item_code: line_data}},+ item_code,+ default_rate_value,+ str(checkout.pk),+ object_type,).quantize(Decimal(".01"))# then@@ -4301,7 +4329,7 @@ def test__get_item_tax_rate_use_default_value_when_taxable_amount_is_different(],"id": str(checkout.pk),"type": object_type,- "item_code": item_code,+ "object_line_id": item_code,"base_rate": default_rate_value,},)@@ -4653,6 +4681,7 @@ def test_order_confirmed("quantity": order_line.quantity,"taxCode": DEFAULT_TAX_CODE,"taxIncluded": True,+ "number": "1",}],"code": str(order.id),@@ -5028,7 +5057,9 @@ def test_get_order_request_data_checks_when_taxes_are_included_to_price(order_with_lines.save()# when- request_data = get_order_request_data(order_with_lines, avatax_config)+ request_data = get_order_request_data(+ order_with_lines, avatax_config, list(order_with_lines.lines.all())+ )lines_data = request_data["createTransactionModel"]["lines"]# then@@ -5059,7 +5090,9 @@ def test_get_order_request_data_uses_correct_address_for_cc(order_with_lines.save()# when- request_data = get_order_request_data(order_with_lines, avatax_config)+ request_data = get_order_request_data(+ order_with_lines, avatax_config, list(order_with_lines.lines.all())+ )# thenexpected_address_data = address_other_country.as_data()@@ -5107,7 +5140,9 @@ def test_get_order_request_data_uses_correct_address_for_cc_with_single_locationavatax_config.from_country = address_data.get("country")# when- request_data = get_order_request_data(order_with_lines, avatax_config)+ request_data = get_order_request_data(+ order_with_lines, avatax_config, list(order_with_lines.lines.all())+ )# thenaddresses = request_data["createTransactionModel"]["addresses"]@@ -5148,7 +5183,9 @@ def test_get_order_request_data_for_line_with_already_included_taxes_in_price(order_with_lines.save()# when- request_data = get_order_request_data(order_with_lines, avatax_config)+ request_data = get_order_request_data(+ order_with_lines, avatax_config, list(order_with_lines.lines.all())+ )# thenlines_data = request_data["createTransactionModel"]["lines"]@@ -5205,7 +5242,9 @@ def test_get_order_request_data_confirmed_order_with_voucher(])- request_data = get_order_request_data(order_with_lines, avatax_config)+ request_data = get_order_request_data(+ order_with_lines, avatax_config, list(order_with_lines.lines.all())+ )lines_data = request_data["createTransactionModel"]["lines"]# extra one from shipping data@@ -5248,7 +5287,7 @@ def test_get_order_request_data_confirmed_order_with_promotion()# when- request_data = get_order_request_data(order, avatax_config)+ request_data = get_order_request_data(order, avatax_config, list(order.lines.all()))# thenlines_data = request_data["createTransactionModel"]["lines"]@@ -5298,7 +5337,9 @@ def test_get_order_request_data_draft_order_with_voucher()# when- request_data = get_order_request_data(order_with_lines, avatax_config)+ request_data = get_order_request_data(+ order_with_lines, avatax_config, list(order_with_lines.lines.all())+ )# thenlines_data = request_data["createTransactionModel"]["lines"]@@ -5358,7 +5399,9 @@ def test_get_order_request_data_draft_order_with_shipping_voucher()# when- request_data = get_order_request_data(order_with_lines, avatax_config)+ request_data = get_order_request_data(+ order_with_lines, avatax_config, list(order_with_lines.lines.all())+ )# thenlines_data = request_data["createTransactionModel"]["lines"]@@ -5416,7 +5459,9 @@ def test_get_order_request_data_draft_order_shipping_voucher_amount_too_high()# when- request_data = get_order_request_data(order_with_lines, avatax_config)+ request_data = get_order_request_data(+ order_with_lines, avatax_config, list(order_with_lines.lines.all())+ )# thenlines_data = request_data["createTransactionModel"]["lines"]@@ -5469,7 +5514,7 @@ def test_get_order_request_data_draft_order_on_promotion()# when- request_data = get_order_request_data(order, avatax_config)+ request_data = get_order_request_data(order, avatax_config, list(order.lines.all()))# thenlines_data = request_data["createTransactionModel"]["lines"]@@ -5483,7 +5528,7 @@ def test_get_order_request_data_draft_order_on_promotion(def test_get_order_tax_data(get_cached_response_or_fetch_mock,get_order_request_data_mock,- order,+ order_with_lines,plugin_configuration,):# given@@ -5493,10 +5538,11 @@ def test_get_order_tax_data(get_cached_response_or_fetch_mock.return_value = return_value# when- response = get_order_tax_data(order, conf)+ response = get_order_tax_data(order_with_lines, conf)# then- get_order_request_data_mock.assert_called_once_with(order, conf)+ lines = list(order_with_lines.lines.all())+ get_order_request_data_mock.assert_called_once_with(order_with_lines, conf, lines)assert response == return_value@@ -5983,7 +6029,12 @@ def test_get_order_lines_data_gets_tax_code_from_product_tax_class(tax_class.save()# when- lines_data = get_order_lines_data(order_with_lines, avatax_config, discounted=False)+ lines_data = get_order_lines_data(+ order_with_lines,+ avatax_config,+ discounted=False,+ lines=list(order_with_lines.lines.all()),+ )# thenassert lines_data[0]["taxCode"] == tax_code@@ -6009,7 +6060,12 @@ def test_get_order_lines_data_gets_tax_code_from_product_type_tax_class(tax_class.save()# when- lines_data = get_order_lines_data(order_with_lines, avatax_config, discounted=False)+ lines_data = get_order_lines_data(+ order_with_lines,+ avatax_config,+ discounted=False,+ lines=list(order_with_lines.lines.all()),+ )# thenassert lines_data[0]["taxCode"] == tax_code@@ -6038,7 +6094,12 @@ def test_get_order_lines_data_sets_different_tax_code_for_zero_amount(variant.product.tax_class.save()# when- lines_data = get_order_lines_data(order_with_lines, avatax_config, discounted=False)+ lines_data = get_order_lines_data(+ order_with_lines,+ avatax_config,+ discounted=False,+ lines=list(order_with_lines.lines.all()),+ )# thenassert lines_data[0]["amount"] == "0.000"@@ -6046,12 +6107,13 @@ def test_get_order_lines_data_sets_different_tax_code_for_zero_amount(def test_get_order_lines_data_with_discounted(- settings, channel_USD, plugin_configuration, order, order_line, avatax_config+ settings, channel_USD, plugin_configuration, order_line, avatax_config):# givensettings.PLUGINS = ["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"]plugin_configuration(channel=channel_USD)+ order = order_line.orderorder_line.unit_price_gross_amount = Decimal(10)order_line.undiscounted_unit_price_gross_amount = Decimal(20)order_line.quantity = 1@@ -6069,7 +6131,12 @@ def test_get_order_lines_data_with_discounted(variant.product.tax_class.save()# when- lines_data = get_order_lines_data(order, avatax_config, discounted=True)+ lines_data = get_order_lines_data(+ order,+ avatax_config,+ discounted=True,+ lines=list(order.lines.all()),+ )# thenassert len(lines_data) == 1@@ -6105,7 +6172,12 @@ def test_get_order_lines_data_sets_different_tax_code_only_for_zero_amount(config = avatax_config# when- lines_data = get_order_lines_data(order_with_lines, config, discounted=False)+ lines_data = get_order_lines_data(+ order_with_lines,+ config,+ discounted=False,+ lines=list(order_with_lines.lines.all()),+ )# thenassert lines_data[0]["amount"] == "10.000"@@ -6132,7 +6204,12 @@ def test_get_order_lines_data_adds_lines_with_taxes_disabled_for_line(line.variant.product.save(update_fields=["tax_class"])# when- lines_data = get_order_lines_data(order_with_lines, avatax_config, discounted=False)+ lines_data = get_order_lines_data(+ order_with_lines,+ avatax_config,+ discounted=False,+ lines=list(order_with_lines.lines.all()),+ )# thenassert len(lines_data) == len(order_with_lines.lines.all())@@ -6485,23 +6562,23 @@ def test_validate_plugin_tax_data_no_data(lines_info):def test_validate_plugin_tax_data_with_negative_values(lines_info, caplog):# giventax_data = {- "lines": [- {+ "lines": {+ "123": {"lineAmount": -30.0000,"quantity": 3.0,"itemCode": "SKU_A",},- {+ "124": {"lineAmount": 40.0000,"quantity": 2.0,"itemCode": "SKU_B",},- {+ "125": {"lineAmount": 8.1300,"quantity": 1.0,"itemCode": "Shipping",},- ]+ }}# when@@ -6514,23 +6591,23 @@ def test_validate_plugin_tax_data_with_negative_values(lines_info, caplog):def test_validate_plugin_tax_data_price_overflow(lines_info, caplog):# giventax_data = {- "lines": [- {+ "lines": {+ "123": {"lineAmount": 30.0000,"quantity": 3.0,"itemCode": "SKU_A",},- {+ "124": {"lineAmount": 99999999999999999.0000,"quantity": 2.0,"itemCode": "SKU_B",},- {+ "125": {"lineAmount": 8.1300,"quantity": 1.0,"itemCode": "Shipping",},- ]+ }}# when@@ -6538,3 +6615,183 @@ def test_validate_plugin_tax_data_price_overflow(lines_info, caplog):# thenassert error_message == TaxDataErrorMessage.OVERFLOW+++@patch("saleor.plugins.avatax.get_cached_response_or_fetch")+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])+def test_calculate_checkout_subtotal_with_additional_force_line(+ mock_get_cached_response_or_fetch,+ checkout_with_item,+ monkeypatch,+ ship_to_pl_address,+ shipping_zone,+ address,+ plugin_configuration,+ test_response_multiple_lines_with_same_item_code,+):+ # given+ plugin_configuration()+ monkeypatch.setattr(+ "saleor.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",+ lambda _: {"PC040156": "desc"},+ )++ def mocked_response(*args, **kwargs):+ # Making a copy, as we are repalcing the list of lines with the dict of+ # lines in the code+ return deepcopy(test_response_multiple_lines_with_same_item_code)++ mock_get_cached_response_or_fetch.side_effect = mocked_response+ manager = get_plugins_manager(allow_replica=False)++ tax_configuration = checkout_with_item.channel.tax_configuration+ tax_configuration.prices_entered_with_tax = False+ tax_configuration.charge_taxes = True+ tax_configuration.save(update_fields=["charge_taxes", "prices_entered_with_tax"])+ tax_configuration.country_exceptions.all().delete()++ checkout_with_item.shipping_address = ship_to_pl_address+ checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()+ checkout_with_item.save()+ checkout_info = fetch_checkout_info(checkout_with_item, [], manager)++ first_checkout_line = checkout_with_item.lines.first()+ variant = first_checkout_line.variant+ first_variant_base_price = variant.get_base_price(+ variant.channel_listings.get(channel=checkout_with_item.channel)+ ).amount+ price_override = Decimal("22.33")+ override_quantity = 1+ add_variant_to_checkout(+ checkout_info,+ variant,+ override_quantity,+ force_new_line=True,+ price_override=price_override,+ )++ # Make sure that price override is different than the original price+ assert first_variant_base_price != price_override+ # Make sure that quantity override is different than the original quantity+ assert first_checkout_line.quantity != override_quantity++ lines, _ = fetch_checkout_lines(checkout_with_item)++ # when+ subtotal = manager.calculate_checkout_subtotal(checkout_info, lines, address)++ # then+ expected_subtotal_net = quantize_price(+ (first_variant_base_price * first_checkout_line.quantity + price_override),+ checkout_with_item.currency,+ )+ expected_subtotal_gross = quantize_price(+ expected_subtotal_net * Decimal("1.23"), checkout_with_item.currency+ )+ assert subtotal == TaxedMoney(+ net=Money(expected_subtotal_net, checkout_with_item.currency),+ gross=Money(expected_subtotal_gross, checkout_with_item.currency),+ )+++@patch("saleor.plugins.avatax.get_cached_response_or_fetch")+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.DeprecatedAvataxPlugin"])+def test_calculate_order_total_with_additional_force_line(+ mock_get_cached_response_or_fetch,+ order_line,+ shipping_zone,+ site_settings,+ address,+ plugin_configuration,+ test_response_multiple_lines_with_same_item_code,+):+ # given+ def mocked_response(*args, **kwargs):+ # Making a copy, as we are repalcing the list of lines with the dict of+ # lines in the code+ return deepcopy(test_response_multiple_lines_with_same_item_code)++ mock_get_cached_response_or_fetch.side_effect = mocked_response++ plugin_configuration()+ manager = get_plugins_manager(allow_replica=False)+ order = order_line.order++ assert order.lines.count() == 1++ variant = order_line.variant+ # Set SKU to the same as the lines from the:+ # test_response_multiple_lines_with_same_item_code+ ProductVariant.objects.filter(sku="123").delete()+ variant.sku = "123"+ variant.save()++ product = variant.product+ quantity = 1++ channel = order.channel++ tax_configuration = channel.tax_configuration+ tax_configuration.prices_entered_with_tax = False+ tax_configuration.charge_taxes = True+ tax_configuration.save(update_fields=["charge_taxes", "prices_entered_with_tax"])+ tax_configuration.country_exceptions.all().delete()++ price_overridden = Money(Decimal("22.33"), channel.currency_code)+ overriden_unit_price = TaxedMoney(net=price_overridden, gross=price_overridden)+ order_line.base_unit_price_amount = Decimal("10.00")+ order_line.save()++ assert order_line.unit_price.net.amount != price_overridden++ order.lines.create(+ product_name=str(product),+ variant_name=str(variant),+ product_sku=variant.sku,+ product_variant_id=variant.get_global_id(),+ is_shipping_required=True,+ is_gift_card=variant.is_gift_card(),+ quantity=quantity,+ variant=variant,+ unit_price=overriden_unit_price,+ total_price=overriden_unit_price * quantity,+ undiscounted_unit_price=overriden_unit_price,+ undiscounted_total_price=overriden_unit_price * quantity,+ base_unit_price=overriden_unit_price.gross,+ undiscounted_base_unit_price=overriden_unit_price.gross,+ tax_rate=Decimal(0),+ tax_class=variant.product.tax_class,+ is_price_overridden=True,+ )++ order.status = OrderStatus.DRAFT+ order.shipping_address = order.billing_address.get_copy()+ order.should_refresh_prices = True+ method = shipping_zone.shipping_methods.get()++ order.shipping_address = order.billing_address.get_copy()+ order_set_shipping_method(order, method)+ order.base_shipping_price_amount = Decimal("10.00")+ order.save()++ # when+ total = manager.calculate_order_total(order, order.lines.all())++ # then+ expected_tax_rate = Decimal("1.23")++ expected_shipping_net = Money(order.base_shipping_price_amount, order.currency)++ expected_total_net = quantize_price(+ (+ order_line.unit_price.net * order_line.quantity+ + price_overridden+ + expected_shipping_net+ ),+ order.currency,+ )+ expected_total_gross = quantize_price(+ expected_total_net * expected_tax_rate,+ order.currency,+ )+ assert total == TaxedMoney(net=expected_total_net, gross=expected_total_gross)diff --git a/saleor/plugins/avatax/tests/test_avatax_caching.py b/saleor/plugins/avatax/tests/test_avatax_caching.pyindex 646e3df2f7..2698bf3f40 100644--- a/saleor/plugins/avatax/tests/test_avatax_caching.py+++ b/saleor/plugins/avatax/tests/test_avatax_caching.py@@ -1,3 +1,4 @@+from copy import deepcopyfrom decimal import Decimalfrom unittest.mock import ANY, Mock, patch@@ -132,12 +133,17 @@ def test_calculate_checkout_subtotal_use_cache(avalara_request_data = generate_request_data_from_checkout(checkout_info, lines, plugin.config, transaction_token=[])- mocked_cache = Mock(- return_value=(++ def mock_side_effect(*args, **kwargs):+ return (avalara_request_data,- avalara_response_for_checkout_with_items_and_shipping,+ # Deep copy, as after caching the response, we replace list lines+ # with dict lines+ deepcopy(avalara_response_for_checkout_with_items_and_shipping),)- )++ mocked_cache = Mock(side_effect=mock_side_effect)+monkeypatch.setattr("saleor.plugins.avatax.cache.get", mocked_cache)mock_validate_tax_data.return_value = ""diff --git a/saleor/plugins/avatax/tests/test_tasks.py b/saleor/plugins/avatax/tests/test_tasks.pyindex 016a697c83..e3a6a90cdc 100644--- a/saleor/plugins/avatax/tests/test_tasks.py+++ b/saleor/plugins/avatax/tests/test_tasks.py@@ -31,7 +31,9 @@ def test_api_post_request_task_sends_request(from_postal_code="53-601",from_country="PL",)- request_data = get_order_request_data(order_with_lines, config)+ request_data = get_order_request_data(+ order_with_lines, config, list(order_with_lines.lines.all())+ )transaction_url = urljoin(get_api_url(config.use_sandbox), "transactions/createoradjust"@@ -63,7 +65,9 @@ def test_api_post_request_task_creates_order_event(from_postal_code="53-601",from_country="PL",)- request_data = get_order_request_data(order_with_lines, config)+ request_data = get_order_request_data(+ order_with_lines, config, list(order_with_lines.lines.all())+ )transaction_url = urljoin(get_api_url(config.use_sandbox), "transactions/createoradjust"@@ -96,7 +100,9 @@ def test_api_post_request_task_missing_response(from_postal_code="53-601",from_country="PL",)- request_data = get_order_request_data(order_with_lines, config)+ request_data = get_order_request_data(+ order_with_lines, config, list(order_with_lines.lines.all())+ )transaction_url = urljoin(get_api_url(config.use_sandbox), "transactions/createoradjust"diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 916394e925..1fb3fbffc6 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -741,7 +741,14 @@ class BasePlugin:get_client_token: Callable[[Any, Any], Any]get_order_line_tax_rate: Callable[- ["Order", "Product", "ProductVariant", Union["Address", None], Decimal],+ [+ "Order",+ "OrderLine",+ "Product",+ "ProductVariant",+ Union["Address", None],+ Decimal,+ ],Decimal,]diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex dee10df7ef..bcc9520565 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -598,6 +598,7 @@ class PluginsManager(PaymentInterface):def get_order_line_tax_rate(self,order: "Order",+ order_line: "OrderLine",product: "Product",variant: "ProductVariant",address: Optional["Address"],@@ -609,6 +610,7 @@ class PluginsManager(PaymentInterface):"get_order_line_tax_rate",default_value,order,+ order_line,product,variant,address,diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.pyindex 6c17cb2ef5..b21802274c 100644--- a/saleor/plugins/tests/sample_plugins.py+++ b/saleor/plugins/tests/sample_plugins.py@@ -269,6 +269,7 @@ class PluginSample(BasePlugin):def get_order_line_tax_rate(self,order: "Order",+ order_line: "OrderLine",product: "Product",variant: "ProductVariant",address: Optional["Address"],diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.pyindex 5eee3c3c61..04c11140b0 100644--- a/saleor/plugins/tests/test_manager.py+++ b/saleor/plugins/tests/test_manager.py@@ -358,6 +358,7 @@ def test_manager_get_order_line_tax_rate_sample_plugin(order_with_lines):unit_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))tax_rate = PluginsManager(plugins=plugins).get_order_line_tax_rate(order,+ line,product,line.variant,None,@@ -381,6 +382,7 @@ def test_manager_get_order_line_tax_rate_no_plugins(product = Product.objects.get(name=line.product_name)tax_rate = PluginsManager(plugins=[]).get_order_line_tax_rate(order,+ line,product,line.variant,None,