Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Merge branch 'master' into avatax_integration
Maciej Korycinski3a32853e2fb5
diff --cc saleor/checkout/utils.pyindex c45d41ce46,42c8f3cc07..51be829e38--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@@ -691,7 -681,9 +692,7 @@@ def get_checkout_context(checkout, discreturn context- def _get_shipping_voucher_discount_for_checkout(voucher, checkout):-def _get_shipping_voucher_discount_for_checkout(- voucher, checkout, discounts=None, taxes=None-):++def _get_shipping_voucher_discount_for_checkout(voucher, checkout, discounts=None):"""Calculate discount value for a voucher of shipping type."""if not checkout.is_shipping_required():msg = pgettext(@@@ -714,13 -706,15 +715,16 @@@raise NotApplicable(msg)return get_shipping_voucher_discount(- voucher, checkout.get_subtotal(), shipping_method.get_total()+ voucher,- checkout.get_subtotal(discounts, taxes),- shipping_method.get_total(taxes),++ calculate_checkout_subtotal(checkout, discounts).gross,++ calculate_checkout_shipping(checkout, discounts).gross,)def _get_products_voucher_discount(order_or_checkout, voucher):"""Calculate products discount value for a voucher, depending on its type."""++ prices = Noneif voucher.type == VoucherType.PRODUCT:prices = get_prices_of_discounted_products(order_or_checkout.lines.all(), voucher.products.all()@@@ -741,15 -735,19 +745,17 @@@return get_products_voucher_discount(voucher, prices)- def get_voucher_discount_for_checkout(voucher, checkout):-def get_voucher_discount_for_checkout(voucher, checkout, discounts=None, taxes=None):++def get_voucher_discount_for_checkout(voucher, checkout, discounts=None):"""Calculate discount value depending on voucher and discount types.Raise NotApplicable if voucher of given type cannot be applied."""if voucher.type == VoucherType.VALUE:- return get_value_voucher_discount(voucher, checkout.get_subtotal())+ return get_value_voucher_discount(- voucher, checkout.get_subtotal(discounts, taxes)++ voucher, calculate_checkout_subtotal(checkout, discounts).gross+ )if voucher.type == VoucherType.SHIPPING:- return _get_shipping_voucher_discount_for_checkout(voucher, checkout)- return _get_shipping_voucher_discount_for_checkout(- voucher, checkout, discounts, taxes- )++ return _get_shipping_voucher_discount_for_checkout(voucher, checkout, discounts)if voucher.type in (VoucherType.PRODUCT,VoucherType.COLLECTION,@@@ -783,7 -781,9 +789,7 @@@ def recalculate_checkout_discount(checkvoucher = get_voucher_for_checkout(checkout)if voucher is not None:try:- discount = get_voucher_discount_for_checkout(voucher, checkout)- discount = get_voucher_discount_for_checkout(- voucher, checkout, discounts, taxes- )++ discount = get_voucher_discount_for_checkout(voucher, checkout, discounts)except NotApplicable:remove_voucher_from_checkout(checkout)else:@@@ -806,20 -806,24 +812,20 @@@remove_voucher_from_checkout(checkout)- def add_promo_code_to_checkout(checkout: Checkout, promo_code: str):-def add_promo_code_to_checkout(- checkout: Checkout, promo_code: str, discounts=None, taxes=None-):++def add_promo_code_to_checkout(checkout: Checkout, promo_code: str, discounts=None):"""Add gift card or voucher data to checkout.Raise InvalidPromoCode if promo code does not match to any voucher or gift card."""if promo_code_is_voucher(promo_code):- add_voucher_code_to_checkout(checkout, promo_code)- add_voucher_code_to_checkout(checkout, promo_code, discounts, taxes)++ add_voucher_code_to_checkout(checkout, promo_code, discounts)elif promo_code_is_gift_card(promo_code):add_gift_card_code_to_checkout(checkout, promo_code)else:raise InvalidPromoCode()- def add_voucher_code_to_checkout(checkout: Checkout, voucher_code: str):-def add_voucher_code_to_checkout(- checkout: Checkout, voucher_code: str, discounts=None, taxes=None-):++def add_voucher_code_to_checkout(checkout: Checkout, voucher_code: str, discounts=None):"""Add voucher data to checkout by code.Raise InvalidPromoCode() if voucher of given type cannot be applied.@@@ -829,19 -833,23 +835,19 @@@except Voucher.DoesNotExist:raise InvalidPromoCode()try:- add_voucher_to_checkout(checkout, voucher)- add_voucher_to_checkout(checkout, voucher, discounts, taxes)++ add_voucher_to_checkout(checkout, voucher, discounts)except NotApplicable:raise ValidationError({"promo_code": "Voucher is not applicable to that checkout."})- def add_voucher_to_checkout(checkout: Checkout, voucher: Voucher):-def add_voucher_to_checkout(- checkout: Checkout, voucher: Voucher, discounts=None, taxes=None-):++def add_voucher_to_checkout(checkout: Checkout, voucher: Voucher, discounts=None):"""Add voucher data to checkout.Raise NotApplicable if voucher of given type cannot be applied."""- discount_amount = get_voucher_discount_for_checkout(voucher, checkout)- discount_amount = get_voucher_discount_for_checkout(- voucher, checkout, discounts, taxes- )++ discount_amount = get_voucher_discount_for_checkout(voucher, checkout, discounts)checkout.voucher_code = voucher.codecheckout.discount_name = voucher.namecheckout.translated_discount_name = (diff --cc saleor/core/taxes/interface.pyindex cd0a6a6030,0000000000..dd6e963810mode 100644,000000..100644--- a/saleor/core/taxes/interface.py+++ b/saleor/core/taxes/interface.py@@@ -1,179 -1,0 +1,179 @@@+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 ...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: 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: 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: 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()++ total = checkout.get_shipping_price()+ 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 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)+++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: 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, **kwargs+):+ if settings.VATLAYER_ACCESS_KEY:+ return vatlayer_interface.apply_taxes_to_product(+ product, price, country, **kwargs+ )+ 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/data_feeds/google_merchant.pyindex eca3bf4781,3e77188963..01b007fd06--- a/saleor/data_feeds/google_merchant.py+++ b/saleor/data_feeds/google_merchant.py@@@ -7,9 -6,9 +6,10 @@@ from django.conf import settingfrom django.contrib.sites.models import Sitefrom django.contrib.syndication.views import add_domainfrom django.core.files.storage import default_storage+ from django.utils import timezonefrom django.utils.encoding import smart_text+from ..core.taxes import ZERO_MONEYfrom ..discount import DiscountInfofrom ..discount.utils import fetch_discountsfrom ..product.models import Attribute, AttributeValue, Category, ProductVariantdiff --cc saleor/graphql/checkout/mutations.pyindex 3e69abc286,b3f782365e..9ce2322b15--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@@ -592,7 -603,9 +591,7 @@@ class CheckoutAddPromoCode(BaseMutationcheckout = cls.get_node_or_error(info, checkout_id, only_type=Checkout, field="checkout_id")- add_promo_code_to_checkout(checkout, promo_code)- add_promo_code_to_checkout(- checkout, promo_code, info.context.discounts, info.context.taxes- )++ add_promo_code_to_checkout(checkout, promo_code, info.context.discounts)return CheckoutAddPromoCode(checkout=checkout)diff --cc tests/conftest.pyindex e88af32601,c35022baf4..be74bb8294--- a/tests/conftest.py+++ b/tests/conftest.py@@@ -1,4 -1,4 +1,5 @@@+ import uuid+from decimal import Decimalfrom io import BytesIOfrom unittest.mock import MagicMock, Mock@@@ -19,8 -21,9 +20,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 DiscountInfo, VoucherType-from saleor.discount import DiscountValueType, DiscountInfo, VoucherType++from saleor.discount import DiscountInfo, DiscountValueType, VoucherTypefrom saleor.discount.models import Sale, Voucher, VoucherTranslationfrom saleor.giftcard.models import GiftCardfrom saleor.menu.models import Menu, MenuItem@@@ -91,14 -94,16 +92,24 @@@ def checkout_with_item(checkout, producreturn checkout+def checkout_with_single_item(checkout, product):+ variant = product.variants.get()+ add_variant_to_checkout(checkout, variant, 1)+ checkout.save()+ return checkout+++ @pytest.fixture+ def checkout_with_items(checkout, product_list, product):+ variant = product.variants.get()+ add_variant_to_checkout(checkout, variant, 1)+ for prod in product_list:+ variant = prod.variants.get()+ add_variant_to_checkout(checkout, variant, 1)+ return checkout++@pytest.fixturedef checkout_with_voucher(checkout, product, voucher):variant = product.variants.get()diff --cc tests/test_checkout.pyindex 9a3436beb2,83537e603f..50cd8520d4--- a/tests/test_checkout.py+++ b/tests/test_checkout.py@@@ -884,6 -922,6 +916,7 @@@ def test_get_discount_for_checkout_shipget_subtotal=Mock(return_value=subtotal),is_shipping_required=Mock(return_value=True),shipping_method=Mock(get_total=Mock(return_value=shipping_total)),++ get_shipping_price=Mock(return_value=shipping_total),shipping_address=Mock(country=Country(shipping_country_code)),)voucher = Voucher(@@@ -904,6 -942,6 +937,7 @@@ def test_get_discount_for_checkout_shipget_subtotal=Mock(return_value=subtotal),is_shipping_required=Mock(return_value=True),shipping_method=Mock(get_total=Mock(return_value=shipping_total)),++ get_shipping_price=Mock(return_value=shipping_total),shipping_address=Mock(country=Country("PL")),)voucher = Voucher(@@@ -996,10 -1034,11 +1030,11 @@@ def test_get_discount_for_checkout_shipsubtotal,error_msg,):- subtotal_price = TaxedMoney(net=subtotal, gross=subtotal)checkout = Mock(- get_subtotal=Mock(return_value=subtotal_price),+ get_subtotal=Mock(return_value=subtotal),is_shipping_required=Mock(return_value=is_shipping_required),shipping_method=shipping_method,++ get_shipping_price=Mock(return_value=Money(10, "USD")),)voucher = Voucher(code="unique",@@@ -1171,6 -1235,16 +1206,15 @@@ def test_recalculate_checkout_discountassert checkout_with_voucher.discount_amount == Money("10.00", "USD")+ def test_recalculate_checkout_discount_with_sale(+ checkout_with_voucher_percentage, discount_info+ ):+ checkout = checkout_with_voucher_percentage- recalculate_checkout_discount(checkout, [discount_info], None)++ recalculate_checkout_discount(checkout, [discount_info])+ assert checkout.discount_amount == Money("1.50", "USD")- total = TaxedMoney(net=Money("13.50", "USD"), gross=Money("13.50", "USD"))- assert checkout.get_total(discounts=[discount_info]) == total++ assert checkout.get_total(discounts=[discount_info]) == Money("13.50", "USD")++def test_recalculate_checkout_discount_voucher_not_applicable(checkout_with_voucher, voucher):diff --cc tests/test_discounts.pyindex f463567404,766a55ce6b..24734d2f7b--- a/tests/test_discounts.py+++ b/tests/test_discounts.py@@@ -1,7 -1,8 +1,8 @@@- from datetime import date, timedelta+ from datetime import timedeltaimport pytest+ from django.utils import timezone-from prices import Money, TaxedMoney+from prices import Moneyfrom saleor.checkout.utils import get_voucher_discount_for_checkoutfrom saleor.discount import DiscountInfo, DiscountValueType, VoucherType