Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Merge branch 'master' into avatax_integration
Maciej Korycinski4d3e92ccaf1c
diff --cc saleor/checkout/utils.pyindex d09c8df391,6826118626..c45d41ce46--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@@ -990,7 -990,9 +990,7 @@@ def validate_gift_cards(checkout: Checkraise NotApplicable(msg)- def create_line_for_order(checkout_line: CheckoutLine, discounts) -> OrderLine:-def create_line_for_order(- variant: ProductVariant, quantity: int, discounts, taxes-) -> OrderLine:++def create_line_for_order(checkout_line: "CheckoutLine", discounts) -> OrderLine:""":raises InsufficientStock: when there is not enough items in stock for this variant"""@@@ -1047,8 -1040,13 +1047,8 @@@ def prepare_order_data(*, checkout: Che)order_data["lines"] = [- create_line_for_order(- variant=line.variant,- quantity=line.quantity,- discounts=discounts,- taxes=taxes,- )+ create_line_for_order(checkout_line=line, discounts=discounts)- for line in checkout # type: CheckoutLine+ for line in checkout]# validate checkout gift cardsdiff --cc saleor/core/middleware.pyindex 7333fa5ca2,513b0eb0e0..517cf44ac0--- a/saleor/core/middleware.py+++ b/saleor/core/middleware.py@@@ -21,9 -21,10 +21,9 @@@ from django.utils.functional import Simfrom django.utils.translation import get_languagefrom django_countries.fields import Country- from ..discount.models import Sale+ from ..discount.utils import fetch_discountsfrom . import analyticsfrom .utils import get_client_ip, get_country_by_ip, get_currency_for_country-from .utils.taxes import get_taxes_for_countrylogger = logging.getLogger(__name__)diff --cc saleor/core/taxes/avatax/interface.pyindex b8ac0e58da,0000000000..39962d5db3mode 100644,000000..100644--- a/saleor/core/taxes/avatax/interface.py+++ b/saleor/core/taxes/avatax/interface.py@@@ -1,209 -1,0 +1,215 @@@+import logging+from datetime import date+from decimal import Decimal+from typing import TYPE_CHECKING, List, Union+from urllib.parse import urljoin++from prices import Money, TaxedMoney++from ....checkout import models as checkout_models+from ....discount.models import Sale+from .. import ZERO_TAXED_MONEY, TaxType+from ..errors import TaxError+from . import (+ META_FIELD,+ CustomerErrors,+ TransactionType,+ api_post_request,+ generate_request_data_from_checkout,+ get_api_url,+ get_cached_tax_codes_or_fetch,+ get_checkout_tax_data,+ get_order_tax_data,+ validate_checkout,+ validate_order,+)++if TYPE_CHECKING:+ from ....checkout.models import Checkout+ from ....order.models import Order, OrderLine++logger = logging.getLogger(__name__)++- def calculate_checkout_total(checkout: "checkout_models.Checkout", discounts):++def calculate_checkout_total(++ checkout: "checkout_models.Checkout", discounts: List["DiscountInfo"]++):+ checkout_total = checkout.get_total(discounts=discounts)+ if not validate_checkout(checkout):+ return TaxedMoney(net=checkout_total, gross=checkout_total)+ response = get_checkout_tax_data(checkout, discounts)+ if not response or "error" in response:+ return TaxedMoney(net=checkout_total, gross=checkout_total)++ currency = response.get("currencyCode")+ 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)+ return TaxedMoney(net=total_net, gross=total_gross)++- def calculate_checkout_subtotal(checkout: "checkout_models.Checkout", discounts):++def calculate_checkout_subtotal(++ checkout: "checkout_models.Checkout", discounts: List["DiscountInfo"]++):+ sub_total = checkout.get_subtotal(discounts)+ if not validate_checkout(checkout):+ return TaxedMoney(net=sub_total, gross=sub_total)++ response = get_checkout_tax_data(checkout, discounts)+ if not response or "error" in response:+ return TaxedMoney(net=sub_total, gross=sub_total)++ currency = response.get("currencyCode")+ sub_tax = Decimal(0.0)+ sub_net = Decimal(0.0)+ for line in response.get("lines", []):+ if line["itemCode"] == "Shipping":+ continue+ 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)+ return TaxedMoney(net=sub_total_net, gross=sub_total_gross)++- def calculate_checkout_shipping(checkout: "checkout_models.Checkout", discounts):++def calculate_checkout_shipping(++ checkout: "checkout_models.Checkout", discounts: List["DiscountInfo"]++):+ shipping_price = checkout.get_shipping_price()+ if not validate_checkout(checkout):+ return TaxedMoney(net=shipping_price, gross=shipping_price)++ response = get_checkout_tax_data(checkout, discounts)+ if not response or "error" in response:+ return TaxedMoney(net=shipping_price, gross=shipping_price)++ shipping_tax = Decimal(0.0)+ shipping_net = shipping_price.amount+ currency = response.get("currencyCode")+ for line in response.get("lines", []):+ if line["itemCode"] == "Shipping":+ shipping_net = Decimal(line["lineAmount"])+ shipping_tax = Decimal(line["tax"])+ break++ shipping_gross = Money(amount=shipping_net + shipping_tax, currency=currency)+ shipping_net = Money(amount=shipping_net, currency=currency)+ return TaxedMoney(net=shipping_net, gross=shipping_gross)+++def preprocess_order_creation(checkout: "Checkout"):+ """Confirm that all data is correct and we can proceed with creation of order.+ Raise error when can't receive taxes"""++ discounts = Sale.objects.active(date.today()).prefetch_related(+ "products", "categories", "collections"+ )+ data = generate_request_data_from_checkout(+ checkout,+ transaction_token=str(checkout.token),+ transaction_type=TransactionType.ORDER,+ discounts=discounts,+ )+ transaction_url = urljoin(get_api_url(), "transactions/createoradjust")+ response = api_post_request(transaction_url, data)+ if not response or "error" in response:+ msg = response.get("error", {}).get("message", "")+ error_code = response.get("error", {}).get("code", "")+ logger.warning(+ "Unable to calculate taxes for checkout %s, error_code: %s, error_msg: %s",+ checkout.token,+ error_code,+ msg,+ )+ customer_msg = CustomerErrors.get_error_msg(response.get("error", {}))+ raise TaxError(customer_msg)+++def postprocess_order_creation(order: "Order"):+ # FIXME after we introduce plugin architecture, this logic could be a celery task++ data = get_order_tax_data(order, commit=False, force_refresh=True)++ transaction_url = urljoin(get_api_url(), "transactions/createoradjust")+ api_post_request(transaction_url, data)+++def calculate_checkout_line_total(- checkout_line: "checkout_models.CheckoutLine", discounts++ checkout_line: "checkout_models.CheckoutLine", discounts: List["DiscountInfo"]+):+ checkout = checkout_line.checkout+ taxes_data = get_checkout_tax_data(checkout, discounts)+ currency = taxes_data.get("currencyCode")+ for line in taxes_data.get("lines", []):+ if line.get("itemCode") == checkout_line.variant.sku:+ 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)++ total = checkout_line.get_total(discounts)+ return TaxedMoney(net=total, gross=total)+++def calculate_order_line_unit(order_line: "OrderLine"):+ order = order_line.order+ if validate_order(order):+ taxes_data = get_order_tax_data(order)+ currency = taxes_data.get("currencyCode")+ for line in taxes_data.get("lines", []):+ if line.get("itemCode") == order_line.variant.sku:+ tax = Decimal(line.get("tax", "0.0")) / order_line.quantity+ net = Decimal(line.get("lineAmount", "0.0")) / order_line.quantity++ gross = Money(amount=net + tax, currency=currency)+ net = Money(amount=net, currency=currency)+ return TaxedMoney(net=net, gross=gross)+ return order_line.unit_price+++def calculate_order_shipping(order: "Order"):+ if not validate_order(order):+ return ZERO_TAXED_MONEY+ taxes_data = get_order_tax_data(order, False)+ currency = taxes_data.get("currencyCode")+ for line in taxes_data.get("lines", []):+ if line["itemCode"] == "Shipping":+ 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)+ return TaxedMoney(+ net=order.shipping_method.price, gross=order.shipping_method.price+ )+++def get_tax_rate_type_choices() -> List[TaxType]:+ return [+ TaxType(code=tax_code, description=desc)+ for tax_code, desc in get_cached_tax_codes_or_fetch().items()+ ]+++def assign_tax_to_object_meta(obj: Union["Product", "ProductType"], tax_code: str):+ codes = get_cached_tax_codes_or_fetch()+ if tax_code not in codes:+ return++ tax_description = codes[tax_code]+ if not hasattr(obj, "meta"):+ return+ if "taxes" not in obj.meta:+ obj.meta["taxes"] = {}+ obj.meta["taxes"]["avatax"] = {"code": tax_code, "description": tax_description}+++def get_tax_from_object_meta(obj: Union["Product", "ProductType"]) -> TaxType:+ if not hasattr(obj, "meta"):+ return TaxType(code="", description="")++ tax = obj.meta.get("taxes", {}).get(META_FIELD, {})+ return TaxType(code=tax.get("code", ""), description=tax.get("description", ""))diff --cc saleor/core/taxes/interface.pyindex c1d6802ab3,0000000000..aa19aa097emode 100644,000000..100644--- a/saleor/core/taxes/interface.py+++ b/saleor/core/taxes/interface.py@@@ -1,176 -1,0 +1,175 @@@+from typing import TYPE_CHECKING, List, Union++from django.conf import settings+from django_countries.fields import Country+from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange++from . import ZERO_TAXED_MONEY, TaxType+from .avatax import interface as avatax_interface+from .vatlayer import interface as vatlayer_interface++if TYPE_CHECKING:- from ...discount.models import SaleQueryset+ from ...checkout.models import Checkout, CheckoutLine+ from ...product.models import Product+ from ...account.models import Address+ from ...order.models import OrderLine, Order+++def calculate_checkout_total(- checkout: "Checkout", discounts: "SaleQueryset"++ checkout: "Checkout", discounts: List["DiscountInfo"]+) -> TaxedMoney:+ """Calculate total gross for checkout"""++ if settings.VATLAYER_ACCESS_KEY:+ return 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 = checkout.get_total(discounts)+ return TaxedMoney(net=total, gross=total)+++def calculate_checkout_subtotal(- checkout: "Checkout", discounts: "SaleQueryset"++ checkout: "Checkout", discounts: List["DiscountInfo"]+) -> TaxedMoney:+ """Calculate subtotal gross for checkout"""++ if settings.VATLAYER_ACCESS_KEY:+ return 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 = checkout.get_subtotal(discounts)+ return TaxedMoney(net=subtotal, gross=subtotal)+++def calculate_checkout_shipping(- checkout: "Checkout", discounts: "SaleQueryset"++ checkout: "Checkout", discounts: List["DiscountInfo"]+) -> TaxedMoney:+ """Calculate shipping gross for checkout"""+ if not checkout.shipping_method:+ return ZERO_TAXED_MONEY+ if settings.VATLAYER_ACCESS_KEY:+ return 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)+ total = checkout.shipping_method.get_total()+ return TaxedMoney(net=total, gross=total)+++def calculate_order_shipping(order: "Order") -> TaxedMoney:+ """Calculate shipping price that assigned to order"""+ if settings.VATLAYER_ACCESS_KEY:+ return 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)+++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)+ 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 data+ pass+ return TaxedMoney(net=price, gross=price)+++def get_tax_rate_type_choices() -> List[TaxType]:+ if settings.VATLAYER_ACCESS_KEY:+ return vatlayer_interface.get_tax_rate_type_choices()+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:+ return avatax_interface.get_tax_rate_type_choices()+ return []+++def calculate_checkout_line_total(- checkout_line: "CheckoutLine", discounts: "SaleQueryset"++ checkout_line: "CheckoutLine", discounts: List["DiscountInfo"]+):+ if settings.VATLAYER_ACCESS_KEY:+ return 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)+ total = checkout_line.get_total(discounts)+ return TaxedMoney(net=total, gross=total)+++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+++def apply_taxes_to_product(product: "Product", price: Money, country: Country):+ if settings.VATLAYER_ACCESS_KEY:+ return vatlayer_interface.apply_taxes_to_product(product, price, country)+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:+ return TaxedMoney(net=price, gross=price)+ return TaxedMoney(net=price, gross=price)+++def show_taxes_on_storefront() -> bool:+ """Specify if taxes are enabled"""+ if settings.VATLAYER_ACCESS_KEY:+ return True+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:+ return False+ return False+++def checkout_are_taxes_handled() -> bool:+ if settings.VATLAYER_ACCESS_KEY:+ return True+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:+ return True+ return False+++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+ )+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:+ pass+ start = TaxedMoney(net=prices.start, gross=prices.start)+ stop = TaxedMoney(net=prices.stop, gross=prices.stop)+ return TaxedMoneyRange(start=start, stop=stop)+++def preprocess_order_creation(checkout: "Checkout"):+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:+ return avatax_interface.preprocess_order_creation(checkout)+++# FIXME this should be converted to the plugin action after we introduce plugin+# architecture+def postprocess_order_creation(order: "Order"):+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:+ return avatax_interface.postprocess_order_creation(order)+++def assign_tax_to_object_meta(obj: Union["Product", "ProductType"], tax_code: str):+ if settings.VATLAYER_ACCESS_KEY:+ vatlayer_interface.assign_tax_to_object_meta(obj, tax_code)+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:+ avatax_interface.assign_tax_to_object_meta(obj, tax_code)+++def get_tax_from_object_meta(obj: Union["Product", "ProductType"],) -> TaxType:+ if settings.VATLAYER_ACCESS_KEY:+ return vatlayer_interface.get_tax_from_object_meta(obj)+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:+ return avatax_interface.get_tax_from_object_meta(obj)+ return TaxType(code="", description="")diff --cc saleor/core/taxes/vatlayer/interface.pyindex f9e9b346ad,0000000000..2479b6c89cmode 100644,000000..100644--- a/saleor/core/taxes/vatlayer/interface.py+++ b/saleor/core/taxes/vatlayer/interface.py@@@ -1,139 -1,0 +1,140 @@@+from typing import TYPE_CHECKING, List, Union++from django_countries.fields import Country+from django_prices_vatlayer.utils import get_tax_rate_types+from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange++from .. import ZERO_TAXED_MONEY, TaxType+from . import (+ DEFAULT_TAX_RATE_NAME,+ TaxRateType,+ apply_tax_to_price,+ get_taxed_shipping_price,+ get_taxes_for_address,+ get_taxes_for_country,+)++if TYPE_CHECKING:- from ....discount.models import SaleQueryset+ from ....checkout.models import Checkout, CheckoutLine+ from ....product.models import Product+ from ....account.models import Address+ from ....order.models import Order, OrderLine+++META_FIELD = "vatlayer"+++def calculate_checkout_total(- checkout: "Checkout", discounts: "SaleQueryset"++ checkout: "Checkout", discounts: List["DiscountInfo"]+) -> TaxedMoney:+ """Calculate total gross for checkout by using vatlayer"""+ return (+ calculate_checkout_subtotal(checkout, discounts)+ + calculate_checkout_shipping(checkout, discounts)+ - checkout.discount_amount+ )+++def calculate_checkout_subtotal(- checkout: "Checkout", discounts: "SaleQueryset"++ checkout: "Checkout", discounts: List["DiscountInfo"]+) -> TaxedMoney:+ """Calculate subtotal gross for checkout"""+ address = checkout.shipping_address or checkout.billing_address+ lines = checkout.lines.prefetch_related("variant__product__product_type")+ lines_total = ZERO_TAXED_MONEY+ for line in lines:+ price = line.variant.get_price(discounts)+ lines_total += line.quantity * apply_taxes_to_product(+ line.variant.product, price, address.country if address else None+ )+ return lines_total++- def calculate_checkout_shipping(checkout: "Checkout", _: "SaleQueryset") -> TaxedMoney:++def calculate_checkout_shipping(++ checkout: "Checkout", _: List["DiscountInfo"]++) -> TaxedMoney:+ """Calculate shipping gross for checkout"""+ address = checkout.shipping_address or checkout.billing_address+ taxes = get_taxes_for_address(address)+ if not checkout.shipping_method:+ return ZERO_TAXED_MONEY+ return get_taxed_shipping_price(checkout.shipping_method.price, taxes)+++def calculate_order_shipping(order: "Order") -> TaxedMoney:+ address = order.shipping_address or order.billing_address+ taxes = get_taxes_for_address(address)+ if not order.shipping_method:+ return ZERO_TAXED_MONEY+ return get_taxed_shipping_price(order.shipping_method.price, taxes)+++def calculate_order_line_unit(order_line: "OrderLine") -> TaxedMoney:+ address = order_line.order.shipping_address or order_line.order.billing_address+ country = address.country if address else None+ variant = order_line.variant+ return apply_taxes_to_product(variant.product, order_line.unit_price_net, country)+++def calculate_checkout_line_total(- checkout_line: "CheckoutLine", discounts: "SaleQueryset"++ checkout_line: "CheckoutLine", discounts: List["DiscountInfo"]+):+ address = (+ checkout_line.checkout.shipping_address+ or checkout_line.checkout.billing_address+ )+ price = checkout_line.variant.get_price(discounts) * checkout_line.quantity+ country = address.country if address else None+ return apply_taxes_to_product(checkout_line.variant.product, price, country)+++def apply_taxes_to_shipping(price: Money, shipping_address: "Address"):+ taxes = get_taxes_for_country(shipping_address.country)+ return get_taxed_shipping_price(price, taxes)+++def get_tax_rate_type_choices() -> List[TaxType]:+ rate_types = get_tax_rate_types() + [DEFAULT_TAX_RATE_NAME]+ choices = [+ TaxType(code=rate_name, description=rate_name) for rate_name in rate_types+ ]+ # sort choices alphabetically by translations+ return sorted(choices, key=lambda x: x.code)+++def apply_taxes_to_product(+ product: "Product", price: Money, country: Country+) -> TaxedMoney:+ taxes = None+ if product.charge_taxes and country:+ taxes = get_taxes_for_country(country)+ product_tax_rate = get_tax_from_object_meta(product).code+ tax_rate = product_tax_rate or get_tax_from_object_meta(product.product_type).code+ return apply_tax_to_price(taxes, tax_rate, price)+++def apply_taxes_to_shipping_price_range(+ prices: MoneyRange, country: "Country"+) -> TaxedMoneyRange:+ taxes = None+ if country:+ taxes = get_taxes_for_country(country)+ return get_taxed_shipping_price(prices, taxes)+++def assign_tax_to_object_meta(obj: Union["Product", "ProductType"], tax_code: str):+ if tax_code not in dict(TaxRateType.CHOICES):+ return+ if not hasattr(obj, "meta"):+ return+ if "taxes" not in obj.meta:+ obj.meta["taxes"] = {}+ obj.meta["taxes"][META_FIELD] = {"code": tax_code, "description": tax_code}+++def get_tax_from_object_meta(obj: Union["Product", "ProductType"]) -> TaxType:+ if not hasattr(obj, "meta"):+ return TaxType(code="", description="")+ tax = obj.meta.get("taxes", {}).get(META_FIELD, {})++ return TaxType(code=tax.get("code", ""), description=tax.get("description", ""))diff --cc saleor/core/utils/random_data.pyindex 74415b234d,35cb14c455..e13014aba7--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@@ -1,4 -1,4 +1,5 @@@+ import datetime+import itertoolsimport jsonimport osimport random@@@ -24,9 -25,10 +24,10 @@@ from ...core.weight import zero_weighfrom ...dashboard.menu.utils import update_menufrom ...discount import DiscountValueType, VoucherTypefrom ...discount.models import Sale, Voucher+ from ...discount.utils import fetch_discountsfrom ...giftcard.models import GiftCardfrom ...menu.models import Menu-from ...order.models import Fulfillment, Order+from ...order.models import Fulfillment, Order, OrderLinefrom ...order.utils import update_order_statusfrom ...page.models import Pagefrom ...payment.utils import (@@@ -459,11 -444,10 +460,9 @@@ def create_users(how_many=10)def create_orders(how_many=10):- discounts = Sale.objects.active(date.today()).prefetch_related(- "products", "categories", "collections"- )- taxes = get_taxes_for_country(Country(settings.DEFAULT_COUNTRY))+ discounts = fetch_discounts(datetime.date.today())- for dummy in range(how_many):- order = create_fake_order(discounts, taxes)+ for _ in range(how_many):+ order = create_fake_order(discounts)yield "Order: %s" % (order,)diff --cc saleor/dashboard/product/views.pyindex 0f3a9f7e06,66bda40b05..33ddce517c--- a/saleor/dashboard/product/views.py+++ b/saleor/dashboard/product/views.py@@@ -10,9 -8,7 +8,8 @@@ from django.template.response import Tefrom django.utils.translation import npgettext_lazy, pgettext_lazyfrom django.views.decorators.http import require_POST+from ...core.taxes import interface as tax_interfacefrom ...core.utils import get_paginator_items- from ...discount.models import Salefrom ...product.models import (Attribute,AttributeValue,@@@ -314,11 -310,7 +311,9 @@@ def variant_details(request, product_pkimages = variant.images.all()margin = get_margin_for_variant(variant)- discounted_price = variant.get_price(discounts=request.discounts).gross+ discounted_price = tax_interface.apply_taxes_to_product(- variant.product,- variant.get_price(discounts=Sale.objects.active(date.today())),- request.country,++ variant.product, variant.get_price(discounts=request.discounts), request.country+ ).grossctx = {"images": images,"product": product,diff --cc saleor/data_feeds/google_merchant.pyindex e05a4d0291,148ecf6736..eca3bf4781--- a/saleor/data_feeds/google_merchant.py+++ b/saleor/data_feeds/google_merchant.py@@@ -8,8 -9,8 +9,9 @@@ from django.contrib.syndication.views ifrom django.core.files.storage import default_storagefrom django.utils.encoding import smart_text+from ..core.taxes import ZERO_MONEY- from ..discount.models import Sale+ from ..discount import DiscountInfo+ from ..discount.utils import fetch_discountsfrom ..product.models import Attribute, AttributeValue, Category, ProductVariantCATEGORY_SEPARATOR = " > "@@@ -125,11 -126,11 +127,11 @@@ def item_tax(item: ProductVariant, discRead more:https://support.google.com/merchants/answer/6324454"""- price = item.get_price(discounts=discounts)- return "US::%s:y" % price.tax+ # FIXME https://github.com/mirumee/saleor/issues/4311+ return "US::%s:y" % ZERO_MONEY- def item_group_id(item):+ def item_group_id(item: ProductVariant):return str(item.product.pk)@@@ -164,14 -165,14 +166,14 @@@ def item_google_product_category(item:return category_path- def item_price(item):+ def item_price(item: ProductVariant):price = item.get_price(discounts=None)- return "%s %s" % (price.gross.amount, price.currency)+ return "%s %s" % (price.amount, price.currency)- def item_sale_price(item, discounts):+ def item_sale_price(item: ProductVariant, discounts: Iterable[DiscountInfo]):sale_price = item.get_price(discounts=discounts)- return "%s %s" % (sale_price.gross.amount, sale_price.currency)+ return "%s %s" % (sale_price.amount, sale_price.currency)def item_attributes(diff --cc saleor/discount/utils.pyindex 6ead7177ad,e017d1b423..7a9f7fe797--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@@ -1,8 -5,9 +5,9 @@@ from typing import Iterablfrom django.db.models import Ffrom django.utils.translation import pgettext-from ..core.utils.taxes import ZERO_MONEY, ZERO_TAXED_MONEY+from ..core.taxes import ZERO_MONEY- from .models import NotApplicable+ from . import DiscountInfo+ from .models import NotApplicable, Saledef increase_voucher_usage(voucher):diff --cc saleor/product/models.pyindex 5857720c24,f4284ac22b..4b55f9abf4--- a/saleor/product/models.py+++ b/saleor/product/models.py@@@ -20,12 -21,15 +21,13 @@@ from prices import MoneyRangfrom text_unidecode import unidecodefrom versatileimagefield.fields import PPOIField, VersatileImageField-from saleor.core.utils import build_absolute_uri--from ..core import TaxRateTypefrom ..core.exceptions import InsufficientStockfrom ..core.models import PublishableModel, PublishedQuerySet, SortableModel-from ..core.utils.taxes import apply_tax_to_price+from ..core.utils import build_absolute_uri+from ..core.utils.json_serializer import CustomJsonEncoderfrom ..core.utils.translations import TranslationProxyfrom ..core.weight import WeightUnits, zero_weight+ from ..discount import DiscountInfofrom ..discount.utils import calculate_discounted_pricefrom ..seo.models import SeoModel, SeoModelTranslation@@@ -188,12 -192,18 +190,12 @@@ class Product(SeoModel, PublishableModeimages = list(self.images.all())return images[0] if images else None- def get_price_range(self, discounts=None):- def get_price_range(self, discounts: Iterable[DiscountInfo] = None, taxes=None):++ def get_price_range(self, discounts: Iterable[DiscountInfo] = None):if self.variants.all():- prices = [- variant.get_price(discounts=discounts, taxes=taxes) for variant in self- ]- return TaxedMoneyRange(min(prices), max(prices))+ prices = [variant.get_price(discounts) for variant in self]+ return MoneyRange(min(prices), max(prices))price = calculate_discounted_price(self, self.price, discounts)- if not self.charge_taxes:- taxes = None- tax_rate = self.tax_rate or self.product_type.tax_rate- price = apply_tax_to_price(taxes, tax_rate, price)- return TaxedMoneyRange(start=price, stop=price)+ return MoneyRange(start=price, stop=price)class ProductTranslation(SeoModelTranslation):@@@ -288,8 -298,12 +290,8 @@@ class ProductVariant(models.Model)else self.product.price)- def get_price(self, discounts=None):- def get_price(self, discounts: Iterable[DiscountInfo] = None, taxes=None):- price = calculate_discounted_price(self.product, self.base_price, discounts)- if not self.product.charge_taxes:- taxes = None- tax_rate = self.product.tax_rate or self.product.product_type.tax_rate- return apply_tax_to_price(taxes, tax_rate, price)++ def get_price(self, discounts: Iterable[DiscountInfo] = None):+ return calculate_discounted_price(self.product, self.base_price, discounts)def get_weight(self):return self.weight or self.product.weight or self.product.product_type.weightdiff --cc saleor/product/utils/availability.pyindex d2915e85c0,136eaa11a4..01cc082a83--- a/saleor/product/utils/availability.py+++ b/saleor/product/utils/availability.py@@@ -7,8 -7,8 +7,9 @@@ from prices import TaxedMoneyRangfrom saleor.graphql.core.types import MoneyRangefrom saleor.product.models import Product, ProductVariant+from ...core.taxes.interface import apply_taxes_to_productfrom ...core.utils import to_local_currency+ from ...discount import DiscountInfofrom .. import ProductAvailabilityStatus, VariantAvailabilityStatusProductAvailability = namedtuple(@@@ -108,19 -110,14 +109,22 @@@ def _get_product_price_rangedef get_product_availability(- product: Product, discounts=None, country=None, local_currency=None+ product: Product,+ discounts: Iterable[DiscountInfo] = None,- taxes=None,- local_currency: str = None,++ country=None,++ local_currency=None,) -> ProductAvailability:- discounted = product.get_price_range(discounts=discounts, taxes=taxes)- undiscounted = product.get_price_range(taxes=taxes)+ discounted_net_range = product.get_price_range(discounts=discounts)+ undiscounted_net_range = product.get_price_range()+ discounted = TaxedMoneyRange(+ start=apply_taxes_to_product(product, discounted_net_range.start, country),+ stop=apply_taxes_to_product(product, discounted_net_range.stop, country),+ )+ undiscounted = TaxedMoneyRange(+ start=apply_taxes_to_product(product, undiscounted_net_range.start, country),+ stop=apply_taxes_to_product(product, undiscounted_net_range.stop, country),+ )discount = _get_total_discount(undiscounted, discounted)price_range_local, discount_local_currency = _get_product_price_range(@@@ -141,13 -138,14 +145,16 @@@def get_variant_availability(- variant: ProductVariant, discounts=None, country=None, local_currency=None+ variant: ProductVariant,+ discounts: Iterable[DiscountInfo] = None,- taxes=None,++ country=None,+ local_currency=None,) -> VariantAvailability:- discounted = variant.get_price(discounts=discounts, taxes=taxes)- undiscounted = variant.get_price(taxes=taxes)+ discounted = apply_taxes_to_product(+ variant.product, variant.get_price(discounts=discounts), country+ )+ undiscounted = apply_taxes_to_product(variant.product, variant.get_price(), country)discount = _get_total_discount(undiscounted, discounted)diff --cc saleor/product/utils/variants_picker.pyindex 2bb9477d4b,59848a9ab9..5a99e6c390--- a/saleor/product/utils/variants_picker.py+++ b/saleor/product/utils/variants_picker.py@@@ -2,17 -3,17 +3,22 @@@ from typing import Iterablfrom django_prices.templatetags import prices_i18n+from ...core.taxes import display_gross_prices+from ...core.taxes.interface import apply_taxes_to_product, show_taxes_on_storefrontfrom ...core.utils import to_local_currency-from ...core.utils.taxes import display_gross_prices, get_tax_rate_by_name+ from ...discount import DiscountInfofrom ...seo.schema.product import variant_json_ldfrom .availability import get_product_availabilitydef get_variant_picker_data(- product, discounts=None, taxes=None, local_currency=None, country=None- product, discounts: Iterable[DiscountInfo] = None, taxes=None, local_currency=None++ product,++ discounts: Iterable[DiscountInfo] = None,++ taxes=None,++ local_currency=None,++ country=None,):- availability = get_product_availability(product, discounts, taxes, local_currency)+ availability = get_product_availability(product, discounts, country, local_currency)variants = product.variants.all()data = {"variantAttributes": [], "variants": []}diff --cc tests/api/test_checkout_promo_codes.pyindex b67e779a68,b0dd43dfe8..5688caee1d--- a/tests/api/test_checkout_promo_codes.py+++ b/tests/api/test_checkout_promo_codes.py@@@ -1,9 -1,6 +1,10 @@@from datetime import date, timedeltaimport graphene+from prices import TaxedMoney++from saleor.checkout.utils import add_voucher_to_checkout++from saleor.discount import DiscountInfofrom tests.api.test_checkout import (MUTATION_CHECKOUT_LINES_DELETE,MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE,@@@ -184,17 -184,27 +185,24 @@@ def test_checkout_totals_use_discounts(content = get_graphql_content(response)data = content["data"]["checkout"]- discounts = [sale]+ discounts = [+ DiscountInfo(+ sale=sale,+ product_ids={product.id},+ category_ids=set(),+ collection_ids=set(),+ )+ ]- assert (- data["totalPrice"]["gross"]["amount"]- == checkout.get_total(discounts=discounts).gross.amount- )- assert (- data["subtotalPrice"]["gross"]["amount"]- == checkout.get_subtotal(discounts=discounts).gross.amount- )+ total = checkout.get_total(discounts=discounts)+ taxed_total = TaxedMoney(total, total)+ assert data["totalPrice"]["gross"]["amount"] == taxed_total.gross.amount+ assert data["subtotalPrice"]["gross"]["amount"] == taxed_total.gross.amountline = checkout.lines.first()+ line_total = line.get_total(discounts=discounts)assert (data["lines"][0]["totalPrice"]["gross"]["amount"]- == line.get_total(discounts=discounts).gross.amount+ == TaxedMoney(line_total, line_total).gross.amount)diff --cc tests/conftest.pyindex 15790ba453,d88835633a..80e90fa084--- a/tests/conftest.py+++ b/tests/conftest.py@@@ -19,8 -20,9 +19,8 @@@ from saleor.account.models import Addrefrom saleor.checkout import utilsfrom saleor.checkout.models import Checkoutfrom saleor.checkout.utils import add_variant_to_checkout-from saleor.core.utils.taxes import DEFAULT_TAX_RATE_NAMEfrom saleor.dashboard.menu.utils import update_menu- from saleor.discount import VoucherType+ from saleor.discount import DiscountInfo, VoucherTypefrom saleor.discount.models import Sale, Voucher, VoucherTranslationfrom saleor.giftcard.models import GiftCardfrom saleor.menu.models import Menu, MenuItem@@@ -686,8 -682,8 +686,8 @@@ def order_with_lines(order, product_typis_shipping_required=variant.is_shipping_required(),quantity=3,variant=variant,- unit_price=variant.get_price(taxes=taxes),- tax_rate=taxes["standard"]["value"],+ unit_price=TaxedMoney(net=net, gross=gross),- tax_rate=0.23,++ tax_rate=23,)product = Product.objects.create(@@@ -712,8 -705,8 +712,8 @@@is_shipping_required=variant.is_shipping_required(),quantity=2,variant=variant,- unit_price=variant.get_price(taxes=taxes),- tax_rate=taxes["standard"]["value"],+ unit_price=TaxedMoney(net=net, gross=gross),- tax_rate=0.23,++ tax_rate=23,)order.shipping_address = order.billing_address.get_copy()diff --cc tests/test_discounts.pyindex 9103c860e5,c921603157..f463567404--- a/tests/test_discounts.py+++ b/tests/test_discounts.py@@@ -1,10 -1,11 +1,10 @@@from datetime import date, timedelta-from prices import Money, TaxedMoney-import pytest+from prices import Moneyfrom saleor.checkout.utils import get_voucher_discount_for_checkout- from saleor.discount import DiscountValueType, VoucherType+ from saleor.discount import DiscountInfo, DiscountValueType, VoucherTypefrom saleor.discount.models import NotApplicable, Sale, Voucherfrom saleor.discount.utils import (decrease_voucher_usage,@@@ -42,24 -43,38 +42,38 @@@ def test_valid_voucher_min_amount_spent@pytest.mark.django_db(transaction=True)def test_variant_discounts(product):variant = product.variants.get()- low_discount = Sale.objects.create(type=DiscountValueType.FIXED, value=5)- low_discount.products.add(product)- discount = Sale.objects.create(type=DiscountValueType.FIXED, value=8)- discount.products.add(product)- high_discount = Sale.objects.create(type=DiscountValueType.FIXED, value=50)- high_discount.products.add(product)- final_price = variant.get_price(discounts=Sale.objects.all())+ low_sale = Sale(type=DiscountValueType.FIXED, value=5)+ low_discount = DiscountInfo(+ sale=low_sale,+ product_ids={product.id},+ category_ids=set(),+ collection_ids=set(),+ )+ sale = Sale(type=DiscountValueType.FIXED, value=8)+ discount = DiscountInfo(+ sale=sale, product_ids={product.id}, category_ids=set(), collection_ids=set()+ )+ high_sale = Sale(type=DiscountValueType.FIXED, value=50)+ high_discount = DiscountInfo(+ sale=high_sale,+ product_ids={product.id},+ category_ids=set(),+ collection_ids=set(),+ )+ final_price = variant.get_price(discounts=[low_discount, discount, high_discount])- assert final_price.gross == Money(0, "USD")+ assert final_price == Money(0, "USD")@pytest.mark.integration@pytest.mark.django_db(transaction=True)def test_percentage_discounts(product):variant = product.variants.get()- discount = Sale.objects.create(type=DiscountValueType.PERCENTAGE, value=50)- discount.products.add(product)+ sale = Sale(type=DiscountValueType.PERCENTAGE, value=50)+ discount = DiscountInfo(+ sale=sale, product_ids={product.id}, category_ids=set(), collection_ids={}+ )final_price = variant.get_price(discounts=[discount])- assert final_price.gross == Money(5, "USD")+ assert final_price == Money(5, "USD")def test_voucher_queryset_active(voucher):diff --cc tests/test_product.pyindex a9a71e55f6,a8b617c3c8..73530cc0dd--- a/tests/test_product.py+++ b/tests/test_product.py@@@ -517,27 -516,52 +516,31 @@@ def test_create_product_thumbnails(mock@pytest.mark.parametrize(- "product_price, include_taxes_in_prices, include_taxes, include_discounts,"- "product_net, product_gross",- [- ("10.00", False, False, False, "10.00", "10.00"),- ("10.00", False, True, False, "10.00", "12.30"),- ("15.00", False, False, True, "10.00", "10.00"),- ("15.00", False, True, True, "10.00", "12.30"),- ("10.00", True, False, False, "10.00", "10.00"),- ("10.00", True, True, False, "8.13", "10.00"),- ("15.00", True, False, True, "10.00", "10.00"),- ("15.00", True, True, True, "8.13", "10.00"),- ],+ "expected_price, include_discounts",+ [(Decimal("10.00"), True), (Decimal("15.0"), False)],)def test_get_price(- product_type, category, sale, expected_price, include_discounts, site_settings+ product_type,+ category,- taxes,- discount_info,- product_price,- include_taxes_in_prices,- include_taxes,++ sale,++ expected_price,+ include_discounts,- product_net,- product_gross,+ site_settings,++ discount_info,):- site_settings.include_taxes_in_prices = include_taxes_in_prices- site_settings.save()product = models.Product.objects.create(- product_type=product_type, category=category, price=Money(product_price, "USD")+ product_type=product_type,+ category=category,+ price=Money(Decimal("15.00"), "USD"),)variant = product.variants.create()-- price = variant.get_price(- discounts=Sale.objects.all() if include_discounts else None- taxes=taxes if include_taxes else None,- discounts=[discount_info] if include_discounts else [],-- )++ price = variant.get_price(discounts=[discount_info] if include_discounts else [])- assert price == TaxedMoney(- net=Money(product_net, "USD"), gross=Money(product_gross, "USD")- )+ assert price.amount == expected_price-def test_product_get_price_variant_has_no_price(- product_type, category, taxes, site_settings-):+def test_product_get_price_variant_has_no_price(product_type, category, site_settings):site_settings.include_taxes_in_prices = Falsesite_settings.save()product = models.Product.objects.create(@@@ -581,13 -617,15 +584,13 @@@ def test_product_get_price_range_no_varproduct_type=product_type, category=category, price=Money("10.00", "USD"))- price = product.get_price_range(taxes=taxes)+ price = product.get_price_range()- expected_price = TaxedMoney(net=Money("10.00", "USD"), gross=Money("12.30", "USD"))- assert price == TaxedMoneyRange(start=expected_price, stop=expected_price)+ expected_price = Money("10.00", "USD")+ assert price == MoneyRange(start=expected_price, stop=expected_price)- def test_product_get_price_do_not_charge_taxes(product_type, category, sale):-def test_product_get_price_do_not_charge_taxes(- product_type, category, taxes, discount_info-):++def test_product_get_price_do_not_charge_taxes(product_type, category, discount_info):product = models.Product.objects.create(product_type=product_type,category=category,@@@ -596,11 -634,27 +599,27 @@@)variant = product.variants.create()- price = variant.get_price(discounts=Sale.objects.all())- price = variant.get_price(taxes=taxes, discounts=[discount_info])++ price = variant.get_price(discounts=[discount_info])- assert price == TaxedMoney(net=Money("5.00", "USD"), gross=Money("5.00", "USD"))+ assert price == Money("5.00", "USD")+ def test_product_get_price_range_do_not_charge_taxes(- product_type, category, taxes, discount_info++ product_type, category, discount_info+ ):+ product = models.Product.objects.create(+ product_type=product_type,+ category=category,+ price=Money("10.00", "USD"),+ charge_taxes=False,+ )+- price = product.get_price_range(taxes=taxes, discounts=[discount_info])++ price = product.get_price_range(discounts=[discount_info])+- expected_price = TaxedMoney(net=Money("5.00", "USD"), gross=Money("5.00", "USD"))- assert price == TaxedMoneyRange(start=expected_price, stop=expected_price)++ expected_price = MoneyRange(start=Money("5.00", "USD"), stop=Money("5.00", "USD"))++ assert price == expected_price++@pytest.mark.parametrize("price_override", ["15.00", "0.00"])def test_variant_base_price(product, price_override):variant = product.variants.get()