Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Show taxes during checkout process
Anna Siwikfa29c11a0533
diff --git a/saleor/checkout/core.py b/saleor/checkout/core.pyindex 2dc1aab532..63dd6ba1dd 100644--- a/saleor/checkout/core.py+++ b/saleor/checkout/core.py@@ -40,24 +40,25 @@ class Checkout:VERSION = '1.0.0'- def __init__(self, cart, user, tracking_code):+ def __init__(self, cart, user, taxes, tracking_code):self.modified = Falseself.cart = cartself.storage = {'version': self.VERSION}self.tracking_code = tracking_codeself.user = user+ self.taxes = taxesself.discounts = cart.discountsself._shipping_method = Noneself._shipping_address = None@classmethod- def from_storage(cls, storage_data, cart, user, tracking_code):+ def from_storage(cls, storage_data, cart, user, taxes, tracking_code):"""Restore a previously serialized checkout session.`storage_data` is the value previously returned by`Checkout.for_storage()`."""- checkout = cls(cart, user, tracking_code)+ checkout = cls(cart, user, taxes, tracking_code)checkout.storage = storage_datatry:version = checkout.storage['version']@@ -368,11 +369,11 @@ class Checkout:def get_subtotal(self):"""Calculate order total without shipping and discount."""- return self.cart.get_total()+ return self.cart.get_total(taxes=self.taxes)def get_total(self):"""Calculate order total with shipping and discount amount."""- total = self.cart.get_total()+ total = self.get_subtotal()if self.shipping_method and self.is_shipping_required:total += self.shipping_method.get_total_price()if self.discount:@@ -397,7 +398,7 @@ def load_checkout(view):session_data = ''tracking_code = analytics.get_client_id(request)checkout = Checkout.from_storage(- session_data, cart, request.user, tracking_code)+ session_data, cart, request.user, request.taxes, tracking_code)response = view(request, checkout, cart)if checkout.modified:request.session[STORAGE_SESSION_KEY] = checkout.for_storage()diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.pyindex 50dae577d2..283aa8700f 100644--- a/saleor/core/utils/__init__.py+++ b/saleor/core/utils/__init__.py@@ -128,9 +128,12 @@ def apply_tax_to_price(taxes, rate_name, base):return baseraise TypeError('Unknown base for flat_tax: %r' % (base,))- tax_to_apply = taxes.get(rate_name, taxes['standard'])+ if rate_name in taxes:+ tax_to_apply = taxes[rate_name]+ else:+ tax_to_apply = taxes['standard']- return tax_to_apply(base, not settings.INCLUDE_TAXES_IN_PRICES)+ return tax_to_apply(base, keep_gross=settings.INCLUDE_TAXES_IN_PRICES)def to_local_currency(price, currency):diff --git a/saleor/dashboard/order/utils.py b/saleor/dashboard/order/utils.pyindex f313e74320..cef6989bfe 100644--- a/saleor/dashboard/order/utils.py+++ b/saleor/dashboard/order/utils.py@@ -76,10 +76,11 @@ def update_order_with_user_addresses(order):def get_product_variants_and_prices(order, product):"""Get variants and unit prices from order lines matching the product."""lines = (- line for line in order if line.product == product)+ line for line in order+ if line.variant and line.variant.product == product)for line in lines:for dummy_i in range(line.quantity):- variant = line.product.variants.get(sku=line.product_sku)+ variant = line.variantif variant:yield variant, variant.get_price_per_item()@@ -90,7 +91,7 @@ def get_category_variants_and_prices(order, root_category):Product is assumed to be in the category if it belongs to any of itsdescendant subcategories."""- products = {line.product for line in order if line.product}+ products = {line.variant.product for line in order if line.variant}matching_products = set()for product in products:if product.category.is_descendant_of(root_category, include_self=True):diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex ece4bf4ac2..de0518b370 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -54,20 +54,15 @@ class ProductTypeSelectorForm(forms.Form):widget=forms.RadioSelect, empty_label=None)-class TaxRateTypeChoiceField(forms.ChoiceField):- """Choice field with choices filled up with available tax rate types."""-- def __init__(self, *args, **kwargs):- rate_types = get_tax_rate_types() + ['standard']- rate_types.sort()- kwargs['choices'] = [- (rate_type, VAT_RATE_TYPE_TRANSLATIONS.get(rate_type, rate_type))- for rate_type in rate_types]- super().__init__(*args, **kwargs)+def get_tax_rate_type_choices():+ rate_types = get_tax_rate_types() + ['standard']+ return [+ (rate_type, VAT_RATE_TYPE_TRANSLATIONS.get(rate_type, rate_type))+ for rate_type in rate_types]class ProductTypeForm(forms.ModelForm):- tax_rate = TaxRateTypeChoiceField()+ tax_rate = forms.ChoiceField(required=False)class Meta:model = ProductType@@ -91,6 +86,10 @@ class ProductTypeForm(forms.ModelForm):'tax_rate': pgettext_lazy('Product type tax rate type', 'Tax rate')}+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.fields['tax_rate'].choices = get_tax_rate_type_choices()+def clean(self):data = super().clean()has_variants = self.cleaned_data['has_variants']@@ -193,7 +192,7 @@ class AttributesMixin(object):class ProductForm(forms.ModelForm, AttributesMixin):- tax_rate = TaxRateTypeChoiceField()+ tax_rate = forms.ChoiceField(required=False)class Meta:model = Product@@ -240,6 +239,7 @@ class ProductForm(forms.ModelForm, AttributesMixin):'data-materialize': self['description'].html_name})self.fields['seo_title'] = SeoTitleField(extra_attrs={'data-bind': self['name'].auto_id})+ self.fields['tax_rate'].choices = get_tax_rate_type_choices()def clean_seo_description(self):seo_description = prepare_seo_description(diff --git a/saleor/product/migrations/0059_generate_variant_name_from_attrs.py b/saleor/product/migrations/0059_generate_variant_name_from_attrs.pyindex 5034a3ae63..91685704a4 100644--- a/saleor/product/migrations/0059_generate_variant_name_from_attrs.py+++ b/saleor/product/migrations/0059_generate_variant_name_from_attrs.py@@ -30,5 +30,5 @@ class Migration(migrations.Migration):]operations = [- migrations.RunPython(create_variant_name_based_on_attributes)+ migrations.RunPython(create_variant_name_based_on_attributes, migrations.RunPython.noop)]diff --git a/templates/cart_dropdown.html b/templates/cart_dropdown.htmlindex 5cb3c0cc69..f799b1f720 100644--- a/templates/cart_dropdown.html+++ b/templates/cart_dropdown.html@@ -34,7 +34,7 @@<div class="col-md-8"><h3>{% trans "Subtotal" context "Order subtotal" %}<br>- <span>{% trans "(Shipment calculated at checkout)" context "Cart dropdown text" %}</span></h3>+ <span>{% trans "(Shipment and taxes calculated at checkout)" context "Cart dropdown text" %}</span></h3></div><div class="col-md-4"><h3 class="float-md-right price {% if lines|length <= 2 %}single{% endif %}" data-quantity="{{ quantity }}">diff --git a/templates/checkout/details.html b/templates/checkout/details.htmlindex 0dbbf73632..bd5f584117 100644--- a/templates/checkout/details.html+++ b/templates/checkout/details.html@@ -32,18 +32,16 @@{% with total=checkout.get_total %}<div class="checkout__review"><h3 class="checkout__review__tittle">{% trans "Order review" context "Order review title" %}</h3>- {% for shipment, shipment_cost, total_with_shipment in checkout.deliveries %}- {% for item, item_price_per_item, item_price_total in shipment %}- <div class="row">- <div class="col-8">- <p><strong>{{ item.variant.product }}</strong> x {{ item.quantity }}<br>- <span class="checkout__review__variant">{{ item.variant }}</span></p>- </div>- <div class="col-4">- <p class="float-right">{{ item_price_total.net|amount }}</p>- </div>+ {% for line in checkout.cart.lines.all %}+ <div class="row">+ <div class="col-8">+ <p><strong>{{ line.variant.product }}</strong> x {{ line.quantity }}<br>+ <span class="checkout__review__variant">{{ line.variant }}</span></p></div>- {% endfor %}+ <div class="col-4">+ <p class="float-right">{{ line.get_total.gross|amount }}</p>+ </div>+ </div>{% endfor %}<div class="row checkout__review__section"><div class="col-8">@@ -66,6 +64,12 @@</div></div><div class="row checkout__review__section">+ <div class="col-8">+ <p>{% trans "Taxes" context "Order review section title" %}</p>+ </div>+ <div class="col-4">+ <p class="float-right">{{ total.tax|amount:'html' }}</p>+ </div><div class="col-8"><h3>{% trans "Total" context "Order review section title" %}</h3></div>diff --git a/templates/dashboard/product/product_type/form.html b/templates/dashboard/product/product_type/form.htmlindex 734e594e47..a218452e77 100644--- a/templates/dashboard/product/product_type/form.html+++ b/templates/dashboard/product/product_type/form.html@@ -98,9 +98,6 @@<div class="col s12 m8">{{ form.tax_rate|materializecss }}</div>- <div class="col s12 m4">- {{ form.charge_taxes|materializecss }}- </div></div></div>{% if perms.product.edit_properties %}diff --git a/templates/order/_ordered_items_table.html b/templates/order/_ordered_items_table.htmlindex 1b75a1ecd7..5d31896db5 100644--- a/templates/order/_ordered_items_table.html+++ b/templates/order/_ordered_items_table.html@@ -100,6 +100,17 @@</div>{% endif %}+<div class="table__row">+ <div class="row">+ <div class="col-8 order-details__table-footer">+ <p>{% trans "Taxes" context "Order details taxes text" %}</p>+ </div>+ <div class="col-4">+ <p class="float-right">{{ order.total.tax|amount:'html' }}</p>+ </div>+ </div>+</div>+<div class="order-details__total"><div class="row"><div class="col-8 order-details__table-footer">diff --git a/tests/conftest.py b/tests/conftest.pyindex 11f7ff2d05..3c9a80a732 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -353,12 +353,13 @@ def product_with_images(product_type, default_category):@pytest.fixturedef anonymous_checkout():- return Checkout((), AnonymousUser(), 'tracking_code')+ return Checkout((), AnonymousUser(), None, 'tracking_code')@pytest.fixturedef checkout_with_items(request_cart_with_item, customer_user):- checkout = Checkout(request_cart_with_item, customer_user, 'tracking_code')+ checkout = Checkout(+ request_cart_with_item, customer_user, None, 'tracking_code')checkout.shipping_address = customer_user.default_shipping_addressreturn checkoutdiff --git a/tests/test_checkout.py b/tests/test_checkout.pyindex 3a6bbfb955..2b1e33dd60 100644--- a/tests/test_checkout.py+++ b/tests/test_checkout.py@@ -17,7 +17,7 @@ from saleor.shipping.models import ShippingMethodCountrydef test_checkout_version():- checkout = Checkout(Mock(), AnonymousUser(), 'tracking_code')+ checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')storage = checkout.for_storage()assert storage['version'] == Checkout.VERSION@@ -32,13 +32,13 @@ def test_checkout_version():(None, {'version': Checkout.VERSION})])def test_checkout_version_with_from_storage(storage_data, expected_storage):checkout = Checkout.from_storage(- storage_data, Mock(), AnonymousUser(), 'tracking_code')+ storage_data, Mock(), AnonymousUser(), None, 'tracking_code')storage = checkout.for_storage()assert storage == expected_storagedef test_checkout_clear_storage():- checkout = Checkout(Mock(), AnonymousUser(), 'tracking_code')+ checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')checkout.storage['new'] = 1checkout.clear_storage()assert checkout.storage is None@@ -47,7 +47,7 @@ def test_checkout_clear_storage():def test_checkout_is_shipping_required():cart = Mock(is_shipping_required=Mock(return_value=True))- checkout = Checkout(cart, AnonymousUser(), 'tracking_code')+ checkout = Checkout(cart, AnonymousUser(), None, 'tracking_code')assert checkout.is_shipping_required is True@@ -55,7 +55,7 @@ def test_checkout_is_shipping_required():(Mock(default_shipping_address='user_shipping'), 'user_shipping'),(AnonymousUser(), None)])def test_checkout_shipping_address_with_anonymous_user(user, shipping):- checkout = Checkout(Mock(), user, 'tracking_code')+ checkout = Checkout(Mock(), user, None, 'tracking_code')assert checkout._shipping_address is Noneassert checkout.shipping_address == shippingassert checkout._shipping_address == shipping@@ -68,14 +68,14 @@ def test_checkout_shipping_address_with_storage(address_objects, shipping, monkeypatch):monkeypatch.setattr('saleor.checkout.core.Address.objects', address_objects)- checkout = Checkout(Mock(), AnonymousUser(), 'tracking_code')+ checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')checkout.storage['shipping_address'] = {'id': 1}assert checkout.shipping_address == shippingdef test_checkout_shipping_address_setter():address = Address(first_name='Jan', last_name='Kowalski')- checkout = Checkout(Mock(), AnonymousUser(), 'tracking_code')+ checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')assert checkout._shipping_address is Nonecheckout.shipping_address = addressassert checkout._shipping_address == address@@ -109,7 +109,7 @@ def test_checkout_shipping_method(monkeypatch.setattr(Checkout, 'shipping_address', shipping_address)monkeypatch.setattr('saleor.checkout.core.ShippingMethodCountry.objects', queryset)- checkout = Checkout(Mock(), AnonymousUser(), 'tracking_code')+ checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')checkout.storage['shipping_method_country_id'] = 1assert checkout._shipping_method is Noneassert checkout.shipping_method == value@@ -120,14 +120,14 @@ def test_checkout_shipping_does_not_exists(monkeypatch):queryset = Mock(get=Mock(side_effect=ShippingMethodCountry.DoesNotExist))monkeypatch.setattr('saleor.checkout.core.ShippingMethodCountry.objects', queryset)- checkout = Checkout(Mock(), AnonymousUser(), 'tracking_code')+ checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')checkout.storage['shipping_method_country_id'] = 1assert checkout.shipping_method is Nonedef test_checkout_shipping_method_setter():shipping_method = Mock(id=1)- checkout = Checkout(Mock(), AnonymousUser(), 'tracking_code')+ checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')assert checkout.modified is Falseassert checkout._shipping_method is Nonecheckout.shipping_method = shipping_method@@ -145,7 +145,7 @@ def test_checkout_shipping_method_setter():is_authenticated=Mock(return_value=True))),'billing_address')])def test_checkout_billing_address(user, address):- checkout = Checkout(Mock(), user, 'tracking_code')+ checkout = Checkout(Mock(), user, None, 'tracking_code')assert checkout.billing_address == address@@ -167,11 +167,12 @@ def test_checkout_billing_address(user, address):is_shipping_required=Mock(return_value=False)),302, reverse('cart:index'))])def test_index_view(cart, status_code, url, rf, monkeypatch):- checkout = Checkout(cart, AnonymousUser(), 'tracking_code')+ checkout = Checkout(cart, AnonymousUser(), None, 'tracking_code')request = rf.get('checkout:index', follow=True)request.user = checkout.userrequest.session = {STORAGE_SESSION_KEY: checkout.for_storage()}request.discounts = []+ request.taxes = Nonemonkeypatch.setattr('saleor.cart.utils.get_cart_from_request', lambda req, qs: cart)response = views.index_view(request)@@ -191,7 +192,7 @@ def test_checkout_create_order_insufficient_stock(product_type.save()variant = product.variants.get()request_cart.add(variant, quantity=10, check_quantity=False)- checkout = Checkout(request_cart, customer_user, 'tracking_code')+ checkout = Checkout(request_cart, customer_user, None, 'tracking_code')with pytest.raises(InsufficientStock):checkout.create_order()@@ -202,7 +203,7 @@ def test_checkout_create_order_insufficient_stock(' test_note ','test_note'])def test_note_form(note_value):- checkout = Checkout(Mock(), AnonymousUser(), 'tracking_code')+ checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')form = NoteForm({'note': note_value}, checkout=checkout)form.is_valid()form.set_checkout_note()diff --git a/tests/test_core.py b/tests/test_core.pyindex 9507b5a8f3..f5b38edc72 100644--- a/tests/test_core.py+++ b/tests/test_core.py@@ -32,7 +32,9 @@ type_schema = {'is_shipping_required': True}}-def test_apply_tax_to_price_include_tax(taxes):+def test_apply_tax_to_price_include_tax(settings, taxes):+ settings.INCLUDE_TAXES_IN_PRICES = False+money = Money(100, 'USD')assert apply_tax_to_price(taxes, 'standard', money) == TaxedMoney(net=Money(100, 'USD'), gross=Money(123, 'USD'))@@ -46,15 +48,16 @@ def test_apply_tax_to_price_include_tax(taxes):net=Money(100, 'USD'), gross=Money(108, 'USD'))-def test_apply_tax_to_price_include_tax_fallback_to_standard_rate(taxes):+def test_apply_tax_to_price_include_tax_fallback_to_standard_rate(+ settings, taxes):+ settings.INCLUDE_TAXES_IN_PRICES = False+money = Money(100, 'USD')taxed_money = TaxedMoney(net=Money(100, 'USD'), gross=Money(123, 'USD'))assert apply_tax_to_price(taxes, 'space suits', money) == taxed_money-def test_apply_tax_to_price_add_tax(settings, taxes):- settings.INCLUDE_TAXES_IN_PRICES = False-+def test_apply_tax_to_price_include_tax(taxes):money = Money(100, 'USD')assert apply_tax_to_price(taxes, 'standard', money) == TaxedMoney(net=Money('81.30', 'USD'), gross=Money(100, 'USD'))@@ -62,9 +65,7 @@ def test_apply_tax_to_price_add_tax(settings, taxes):net=Money('92.59', 'USD'), gross=Money(100, 'USD'))-def test_apply_tax_to_price_add_tax_fallback_to_standard_rate(- settings, taxes):- settings.INCLUDE_TAXES_IN_PRICES = False+def test_apply_tax_to_price_include_fallback_to_standard_rate(taxes):money = Money(100, 'USD')assert apply_tax_to_price(taxes, 'space suits', money) == TaxedMoney(net=Money('81.30', 'USD'), gross=Money(100, 'USD'))diff --git a/tests/test_product.py b/tests/test_product.pyindex e7e3c7b322..099948c483 100644--- a/tests/test_product.py+++ b/tests/test_product.py@@ -430,14 +430,14 @@ def test_create_product_thumbnails(@pytest.mark.parametrize('product_price, include_taxes_in_prices, include_taxes, include_discounts,''product_net, product_gross', [- ('10.00', True, False, False, '10.00', '10.00'),- ('10.00', True, True, False, '10.00', '12.30'),- ('15.00', True, False, True, '10.00', '10.00'),- ('15.00', True, True, True, '10.00', '12.30'),('10.00', False, False, False, '10.00', '10.00'),- ('10.00', False, True, False, '8.13', '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, '8.13', '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')])def test_get_price_per_item(settings, product_type, default_category, taxes, sale, product_price,include_taxes_in_prices, include_taxes, include_discounts,@@ -458,7 +458,8 @@ def test_get_price_per_item(def test_product_get_price_per_item_variant_has_no_price(- product_type, default_category, taxes):+ settings, product_type, default_category, taxes):+ settings.INCLUDE_TAXES_IN_PRICES = Falseproduct = models.Product.objects.create(product_type=product_type,category=default_category,@@ -472,7 +473,8 @@ def test_product_get_price_per_item_variant_has_no_price(def test_product_get_price_per_item_variant_with_price(- product_type, default_category, taxes):+ settings, product_type, default_category, taxes):+ settings.INCLUDE_TAXES_IN_PRICES = Falseproduct = models.Product.objects.create(product_type=product_type,category=default_category,@@ -486,7 +488,8 @@ def test_product_get_price_per_item_variant_with_price(def test_product_get_price_range_with_variants(- product_type, default_category, taxes):+ settings, product_type, default_category, taxes):+ settings.INCLUDE_TAXES_IN_PRICES = Falseproduct = models.Product.objects.create(product_type=product_type,category=default_category,@@ -505,7 +508,8 @@ def test_product_get_price_range_with_variants(def test_product_get_price_range_no_variants(- product_type, default_category, taxes):+ settings, product_type, default_category, taxes):+ settings.INCLUDE_TAXES_IN_PRICES = Falseproduct = models.Product.objects.create(product_type=product_type,category=default_category,