Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Quantize prices returned from tax gateway
Maciej Korycinski374f1a95bf34
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 7147b5f404..f9cd1509bc 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -16,7 +16,7 @@ from ..account.forms import get_address_formfrom ..account.models import Address, Userfrom ..account.utils import store_user_addressfrom ..core.exceptions import InsufficientStock-from ..core.taxes import zero_money, zero_taxed_money+from ..core.taxes import quantize_price, zero_money, zero_taxed_moneyfrom ..core.taxes.interface import (calculate_checkout_line_total,calculate_checkout_shipping,@@ -109,8 +109,9 @@ def get_prices_of_discounted_products(checkout, discounted_products):if discounted_products:for line in checkout:if line.variant.product in discounted_products:- line_unit_price = (- calculate_checkout_line_total(line, []).gross / line.quantity+ line_total = calculate_checkout_line_total(line, []).gross+ line_unit_price = quantize_price(+ (line_total / line.quantity), line_total.currency)line_prices.extend([line_unit_price] * line.quantity)return line_prices@@ -127,8 +128,9 @@ def get_prices_of_products_in_discounted_collections(checkout, discounted_colleccontinueproduct_collections = line.variant.product.collections.all()if set(product_collections).intersection(discounted_collections):- line_unit_price = (- calculate_checkout_line_total(line, []).gross / line.quantity+ line_total = calculate_checkout_line_total(line, []).gross+ line_unit_price = quantize_price(+ (line_total / line.quantity), line_total.currency)line_prices.extend([line_unit_price] * line.quantity)return line_prices@@ -150,8 +152,9 @@ def get_prices_of_products_in_discounted_categories(checkout, discounted_categorcontinueproduct_category = line.variant.product.categoryif product_category in discounted_categories:- line_unit_price = (- calculate_checkout_line_total(line, []).gross / line.quantity+ line_total = calculate_checkout_line_total(line, []).gross+ line_unit_price = quantize_price(+ (line_total / line.quantity), line_total.currency)line_prices.extend([line_unit_price] * line.quantity)return line_prices@@ -1017,7 +1020,9 @@ def create_line_for_order(checkout_line: "CheckoutLine", discounts) -> OrderLinetranslated_product_name = ""total_line_price = calculate_checkout_line_total(checkout_line, discounts)- unit_price = total_line_price / checkout_line.quantity+ unit_price = quantize_price(+ total_line_price / checkout_line.quantity, total_line_price.currency+ )line = OrderLine(product_name=product_name,translated_product_name=translated_product_name,diff --git a/saleor/checkout/views/__init__.py b/saleor/checkout/views/__init__.pyindex cf07a7538c..e21f296442 100644--- a/saleor/checkout/views/__init__.py+++ b/saleor/checkout/views/__init__.py@@ -7,6 +7,7 @@ from ...account.forms import LoginFormfrom ...core.taxes import (get_display_price,interface as tax_interface,+ quantize_price,zero_taxed_money,)from ...core.utils import format_money, get_user_shipping_country, to_local_currency@@ -140,7 +141,7 @@ def checkout_index(request, checkout):discounts=discounts,)total_line = tax_interface.calculate_checkout_line_total(line, discounts)- variant_price = total_line / line.quantity+ variant_price = quantize_price(total_line / line.quantity, total_line.currency)checkout_lines.append({"variant": line.variant,diff --git a/saleor/core/taxes/__init__.py b/saleor/core/taxes/__init__.pyindex e1c0788f47..8e11b50c08 100644--- a/saleor/core/taxes/__init__.py+++ b/saleor/core/taxes/__init__.py@@ -1,6 +1,8 @@from dataclasses import dataclass+from decimal import Decimalfrom typing import Union+from babel.numbers import get_currency_precisionfrom django.conf import settingsfrom django.contrib.sites.models import Sitefrom prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange@@ -45,6 +47,14 @@ def get_display_price(return base+def quantize_price(+ price: Union["TaxedMoney", "Money", "Decimal", "TaxedMoneyRange"], currency+):+ precision = get_currency_precision(currency)+ number_places = Decimal(10) ** -precision+ return price.quantize(number_places)++@dataclass(frozen=True)class TaxType:"""Dataclass for unifying tax type object that comes from tax gateway"""diff --git a/saleor/core/taxes/avatax/interface.py b/saleor/core/taxes/avatax/interface.pyindex 383688b71f..7329858c62 100644--- a/saleor/core/taxes/avatax/interface.py+++ b/saleor/core/taxes/avatax/interface.py@@ -41,8 +41,8 @@ def calculate_checkout_total(return TaxedMoney(net=checkout_total, gross=checkout_total)currency = response.get("currencyCode")- tax = Decimal(str(response.get("totalTax", 0.0)))- total_net = Decimal(str(response.get("totalAmount", 0.0)))+ tax = Decimal(response.get("totalTax", 0.0))+ total_net = Decimal(response.get("totalAmount", 0.0))total_gross = Money(amount=total_net + tax, currency=currency)total_net = Money(amount=total_net, currency=currency)total = TaxedMoney(net=total_net, gross=total_gross)@@ -69,8 +69,8 @@ def calculate_checkout_subtotal(for line in response.get("lines", []):if line["itemCode"] == "Shipping":continue- sub_tax += Decimal(str(line["tax"]))- sub_net += Decimal(str(line.get("lineAmount", 0.0)))+ sub_tax += Decimal(line["tax"])+ sub_net += Decimal(line.get("lineAmount", 0.0))sub_total_gross = Money(sub_net + sub_tax, currency)sub_total_net = Money(sub_net, currency)@@ -93,8 +93,8 @@ def calculate_checkout_shipping(currency = response.get("currencyCode")for line in response.get("lines", []):if line["itemCode"] == "Shipping":- shipping_net = Decimal(str(line["lineAmount"]))- shipping_tax = Decimal(str(line["tax"]))+ shipping_net = Decimal(line["lineAmount"])+ shipping_tax = Decimal(line["tax"])breakshipping_gross = Money(amount=shipping_net + shipping_tax, currency=currency)@@ -149,8 +149,8 @@ def calculate_checkout_line_total(currency = taxes_data.get("currencyCode")for line in taxes_data.get("lines", []):if line.get("itemCode") == checkout_line.variant.sku:- tax = Decimal(str(line.get("tax", 0.0)))- line_net = Decimal(str(line["lineAmount"]))+ tax = Decimal(line.get("tax", 0.0))+ line_net = Decimal(line["lineAmount"])line_gross = Money(amount=line_net + tax, currency=currency)line_net = Money(amount=line_net, currency=currency)return TaxedMoney(net=line_net, gross=line_gross)@@ -166,8 +166,8 @@ def calculate_order_line_unit(order_line: "OrderLine"):currency = taxes_data.get("currencyCode")for line in taxes_data.get("lines", []):if line.get("itemCode") == order_line.variant.sku:- tax = Decimal(str(line.get("tax", 0.0))) / order_line.quantity- net = Decimal(str(line.get("lineAmount", 0.0))) / order_line.quantity+ tax = Decimal(line.get("tax", 0.0)) / order_line.quantity+ net = Decimal(line.get("lineAmount", 0.0)) / order_line.quantitygross = Money(amount=net + tax, currency=currency)net = Money(amount=net, currency=currency)@@ -182,8 +182,8 @@ def calculate_order_shipping(order: "Order"):currency = taxes_data.get("currencyCode")for line in taxes_data.get("lines", []):if line["itemCode"] == "Shipping":- tax = Decimal(str(line.get("tax", 0.0)))- net = Decimal(str(line.get("lineAmount", 0.0)))+ tax = Decimal(line.get("tax", 0.0))+ net = Decimal(line.get("lineAmount", 0.0))gross = Money(amount=net + tax, currency=currency)net = Money(amount=net, currency=currency)return TaxedMoney(net=net, gross=gross)diff --git a/saleor/core/taxes/interface.py b/saleor/core/taxes/interface.pyindex dd3c36789c..01a03fb76b 100644--- a/saleor/core/taxes/interface.py+++ b/saleor/core/taxes/interface.py@@ -4,7 +4,7 @@ from django.conf import settingsfrom django_countries.fields import Countryfrom prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange-from . import TaxType+from . import TaxType, quantize_pricefrom .avatax import interface as avatax_interfacefrom .vatlayer import interface as vatlayer_interface@@ -20,13 +20,17 @@ def calculate_checkout_total() -> TaxedMoney:"""Calculate total gross for checkout"""+ total = Noneif settings.VATLAYER_ACCESS_KEY:- return vatlayer_interface.calculate_checkout_total(checkout, discounts)+ total = vatlayer_interface.calculate_checkout_total(checkout, discounts)elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:- return avatax_interface.calculate_checkout_total(checkout, discounts)+ total = avatax_interface.calculate_checkout_total(checkout, discounts)++ if total:+ return quantize_price(total, total.currency)total = checkout.get_total(discounts)- return TaxedMoney(net=total, gross=total)+ return quantize_price(TaxedMoney(net=total, gross=total), total.currency)def calculate_checkout_subtotal(@@ -34,13 +38,17 @@ def calculate_checkout_subtotal() -> TaxedMoney:"""Calculate subtotal gross for checkout"""+ subtotal = Noneif settings.VATLAYER_ACCESS_KEY:- return vatlayer_interface.calculate_checkout_subtotal(checkout, discounts)+ subtotal = vatlayer_interface.calculate_checkout_subtotal(checkout, discounts)elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:- return avatax_interface.calculate_checkout_subtotal(checkout, discounts)+ subtotal = avatax_interface.calculate_checkout_subtotal(checkout, discounts)++ if subtotal:+ return quantize_price(subtotal, subtotal.currency)subtotal = checkout.get_subtotal(discounts)- return TaxedMoney(net=subtotal, gross=subtotal)+ return quantize_price(TaxedMoney(net=subtotal, gross=subtotal), subtotal.currency)def calculate_checkout_shipping(@@ -50,36 +58,44 @@ def calculate_checkout_shipping(total = checkout.get_shipping_price()total = TaxedMoney(net=total, gross=total)if not checkout.shipping_method:- return total+ return quantize_price(total, total.currency)if settings.VATLAYER_ACCESS_KEY:- return vatlayer_interface.calculate_checkout_shipping(checkout, discounts)+ total = vatlayer_interface.calculate_checkout_shipping(checkout, discounts)elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:- return avatax_interface.calculate_checkout_shipping(checkout, discounts)-- return total+ total = avatax_interface.calculate_checkout_shipping(checkout, discounts)+ return quantize_price(total, total.currency)def calculate_order_shipping(order: "Order") -> TaxedMoney:"""Calculate shipping price that assigned to order"""+ shipping_price = Noneif settings.VATLAYER_ACCESS_KEY:- return vatlayer_interface.calculate_order_shipping(order)+ shipping_price = vatlayer_interface.calculate_order_shipping(order)elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:- return avatax_interface.calculate_order_shipping(order)- price = order.shipping_method.price- return TaxedMoney(net=price, gross=price)+ shipping_price = avatax_interface.calculate_order_shipping(order)++ if shipping_price:+ return quantize_price(shipping_price, shipping_price.currency)+ shipping_price = order.shipping_method.price+ return quantize_price(+ TaxedMoney(net=shipping_price, gross=shipping_price), shipping_price.currency+ )def apply_taxes_to_shipping(price: Money, shipping_address: "Address") -> TaxedMoney:"""Apply taxes for shipping methods that user can use during checkout"""if shipping_address:if settings.VATLAYER_ACCESS_KEY:- return vatlayer_interface.apply_taxes_to_shipping(price, shipping_address)+ return quantize_price(+ vatlayer_interface.apply_taxes_to_shipping(price, shipping_address),+ price.currency,+ )if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:# For now we can't calculate product/shipping prices that are not directly# assigned to order. Avatax has api only to calculate prices based on# checkout/order datapass- return TaxedMoney(net=price, gross=price)+ return quantize_price(TaxedMoney(net=price, gross=price), price.currency)def get_tax_rate_type_choices() -> List[TaxType]:@@ -93,35 +109,44 @@ def get_tax_rate_type_choices() -> List[TaxType]:def calculate_checkout_line_total(checkout_line: "CheckoutLine", discounts: List["DiscountInfo"]):+ total = Noneif settings.VATLAYER_ACCESS_KEY:- return vatlayer_interface.calculate_checkout_line_total(+ total = vatlayer_interface.calculate_checkout_line_total(checkout_line, discounts)- if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:- return avatax_interface.calculate_checkout_line_total(checkout_line, discounts)+ elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:+ total = avatax_interface.calculate_checkout_line_total(checkout_line, discounts)+ if total:+ return quantize_price(total, total.currency)total = checkout_line.get_total(discounts)- return TaxedMoney(net=total, gross=total)+ return quantize_price(TaxedMoney(net=total, gross=total), total.currency)def calculate_order_line_unit(order_line: "OrderLine"):"""It updates unit_price for a given order line based on current price of variant"""if settings.VATLAYER_ACCESS_KEY:- return vatlayer_interface.calculate_order_line_unit(order_line)- if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:- return avatax_interface.calculate_order_line_unit(order_line)- return order_line.unit_price+ unit_price = vatlayer_interface.calculate_order_line_unit(order_line)+ elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:+ unit_price = avatax_interface.calculate_order_line_unit(order_line)+ else:+ unit_price = order_line.unit_price++ return quantize_price(unit_price, unit_price.currency)def apply_taxes_to_product(product: "Product", price: Money, country: Country, **kwargs):if settings.VATLAYER_ACCESS_KEY:- return vatlayer_interface.apply_taxes_to_product(- product, price, country, **kwargs+ return quantize_price(+ vatlayer_interface.apply_taxes_to_product(+ product, price, country, **kwargs+ ),+ price.currency,)- if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:- return TaxedMoney(net=price, gross=price)- return TaxedMoney(net=price, gross=price)+ elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:+ pass+ return quantize_price(TaxedMoney(net=price, gross=price), price.currency)def show_taxes_on_storefront() -> bool:@@ -144,14 +169,15 @@ def taxes_are_enabled() -> bool:def apply_taxes_to_shipping_price_range(prices: MoneyRange, country: Country):if country:if settings.VATLAYER_ACCESS_KEY:- return vatlayer_interface.apply_taxes_to_shipping_price_range(- prices, country+ return quantize_price(+ vatlayer_interface.apply_taxes_to_shipping_price_range(prices, country),+ prices.currency,)if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:passstart = TaxedMoney(net=prices.start, gross=prices.start)stop = TaxedMoney(net=prices.stop, gross=prices.stop)- return TaxedMoneyRange(start=start, stop=stop)+ return quantize_price(TaxedMoneyRange(start=start, stop=stop), start.currency)def preprocess_order_creation(checkout: "Checkout", discounts: List["DiscountInfo"]):diff --git a/tests/taxes/test_avatax.py b/tests/taxes/test_avatax.pyindex 6682806423..1dba0099f5 100644--- a/tests/taxes/test_avatax.py+++ b/tests/taxes/test_avatax.py@@ -2,6 +2,7 @@ import pytestfrom prices import Money, TaxedMoneyfrom saleor.checkout.utils import add_variant_to_checkout+from saleor.core.taxes import quantize_pricefrom saleor.core.taxes.avatax import interface@@ -44,6 +45,7 @@ def test_calculate_checkout_line_total(product.save()discounts = [discount_info] if with_discount else Nonetotal = interface.calculate_checkout_line_total(line, discounts)+ total = quantize_price(total, total.currency)assert total == TaxedMoney(net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD"))@@ -93,6 +95,7 @@ def test_calculate_checkout_total(discounts = [discount_info] if with_discount else Nonetotal = interface.calculate_checkout_total(checkout_with_item, discounts)+ total = quantize_price(total, total.currency)assert total == TaxedMoney(net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD"))@@ -122,6 +125,7 @@ def test_calculate_checkout_shipping(shipping_price = interface.calculate_checkout_shipping(checkout_with_item, [discount_info])+ shipping_price = quantize_price(shipping_price, shipping_price.currency)assert shipping_price == TaxedMoney(net=Money("8.13", "USD"), gross=Money("10.00", "USD"))@@ -167,7 +171,7 @@ def test_calculate_checkout_subtotal(discounts = [discount_info] if with_discount else Noneadd_variant_to_checkout(checkout_with_item, variant, 2)total = interface.calculate_checkout_subtotal(checkout_with_item, discounts)-+ total = quantize_price(total, total.currency)assert total == TaxedMoney(net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD"))@@ -188,6 +192,7 @@ def test_calculate_order_shipping(site_settings.save()price = interface.calculate_order_shipping(order)+ price = quantize_price(price, price.currency)assert price == TaxedMoney(net=Money("8.13", "USD"), gross=Money("10.00", "USD"))@@ -210,6 +215,8 @@ def test_calculate_order_line_unit(site_settings.company_address = address_usasite_settings.save()- assert interface.calculate_order_line_unit(order_line) == TaxedMoney(+ line_price = interface.calculate_order_line_unit(order_line)+ line_price = quantize_price(line_price, line_price.currency)+ assert line_price == TaxedMoney(net=Money("8.13", "USD"), gross=Money("10.00", "USD"))diff --git a/tests/taxes/test_interface.py b/tests/taxes/test_interface.pyindex 1bf9334957..847905a28f 100644--- a/tests/taxes/test_interface.py+++ b/tests/taxes/test_interface.py@@ -3,7 +3,7 @@ from django_countries.fields import Countryfrom prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRangefrom saleor.checkout.utils import add_variant_to_checkout-from saleor.core.taxes import interface+from saleor.core.taxes import interface, quantize_pricefrom saleor.shipping import ShippingMethodType@@ -94,7 +94,9 @@ def test_calculate_order_shipping(order, shipping_zone):def test_calculate_order_line_unit(order_line):- assert interface.calculate_order_line_unit(order_line) == order_line.unit_price+ assert interface.calculate_order_line_unit(order_line) == quantize_price(+ order_line.unit_price, order_line.unit_price.currency+ )@pytest.mark.parametrize(