Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add taxes to products lists and details pages

Rafał Pitoń1fc1bda385a4
diff --git a/saleor/core/middleware.py b/saleor/core/middleware.py
index 47331b86c7..a21c37fb17 100644
--- a/saleor/core/middleware.py
+++ b/saleor/core/middleware.py
@@ -7,7 +7,9 @@ from django_countries.fields import Country
from . import analytics
from ..discount.models import Sale
-from .utils import get_client_ip, get_country_by_ip, get_currency_for_country
+from .utils import (
+ get_client_ip, get_country_by_ip, get_currency_for_country,
+ get_taxes_for_country)
logger = logging.getLogger(__name__)
@@ -78,3 +80,14 @@ def site(get_response):
return get_response(request)
return middleware
+
+
+def taxes(get_response):
+ """Assign tax rates for default country to `request.taxes`."""
+ def middleware(request):
+ # fixme: find out if we should or can use request.country here
+ request.taxes = get_taxes_for_country(
+ Country(settings.DEFAULT_COUNTRY))
+ return get_response(request)
+
+ return middleware
diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.py
index f9dc43aa93..92f8fe254b 100644
--- a/saleor/core/utils/__init__.py
+++ b/saleor/core/utils/__init__.py
@@ -14,6 +14,8 @@ from django_babel.templatetags.babel import currencyfmt
from django_countries import countries
from django_countries.fields import Country
from django_prices_openexchangerates import exchange_currency
+from django_prices_vatlayer.utils import (
+ get_tax_rates_for_country, get_tax_for_rate)
from geolite2 import geolite2
from prices import Money, MoneyRange, TaxedMoney
from versatileimagefield.image_warmer import VersatileImageFieldWarmer
@@ -99,6 +101,32 @@ def format_money(money):
return currencyfmt(money.amount, money.currency)
+def get_taxes_for_country(country):
+ tax_rates = get_tax_rates_for_country(country.code)
+ if tax_rates is None:
+ return None
+
+ taxes = {'standard': get_tax_for_rate(tax_rates)}
+ if tax_rates['reduced_rates']:
+ taxes.update({
+ rate: get_tax_for_rate(tax_rates, rate)
+ for rate in tax_rates['reduced_rates']})
+ return taxes
+
+
+def apply_tax_to_price(taxes, rate_name, price):
+ if taxes is None:
+ # Naively convert Money to TaxedMoney for consistency with price
+ # handling logic across the codebase
+ return TaxedMoney(net=price, gross=price)
+ if rate_name in taxes:
+ tax_to_apply = taxes[rate_name]
+ else:
+ tax_to_apply = taxes['standard']
+ price_with_tax = tax_to_apply(price, not settings.BASE_PRICES_ARE_NET)
+ return price_with_tax
+
+
def to_local_currency(price, currency):
if not settings.OPENEXCHANGERATES_API_KEY:
return None
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 789c3f3728..ee57bd265c 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -18,6 +18,7 @@ from text_unidecode import unidecode
from versatileimagefield.fields import PPOIField, VersatileImageField
from ..core.exceptions import InsufficientStock
+from ..core.utils import apply_tax_to_price
from ..discount.utils import calculate_discounted_price
from ..seo.models import SeoModel
@@ -69,6 +70,9 @@ class ProductType(models.Model):
'ProductAttribute', related_name='product_variant_types', blank=True)
is_shipping_required = models.BooleanField(default=False)
+ # todo: replace this with proper tax rate field
+ tax_rate = 'standard'
+
class Meta:
app_label = 'product'
@@ -105,6 +109,9 @@ class Product(SeoModel):
updated_at = models.DateTimeField(auto_now=True, null=True)
is_featured = models.BooleanField(default=False)
+ # todo: replace this with proper tax rate field
+ tax_rate = None
+
objects = ProductQuerySet.as_manager()
class Meta:
@@ -153,16 +160,24 @@ class Product(SeoModel):
first_image = self.images.first()
return first_image.image if first_image else None
- def get_price_per_item(self, item, discounts=None):
- return item.get_price_per_item(discounts)
+ def get_attribute(self, pk):
+ return self.attributes.get(smart_text(pk))
+
+ def set_attribute(self, pk, value_pk):
+ self.attributes[smart_text(pk)] = smart_text(value_pk)
+
+ def get_price_per_item(self, item, discounts=None, taxes=None):
+ return item.get_price_per_item(discounts, taxes)
- def get_price_range(self, discounts=None):
+ def get_price_range(self, discounts=None, taxes=None):
if self.variants.exists():
prices = [
- self.get_price_per_item(variant, discounts=discounts)
+ self.get_price_per_item(
+ variant, discounts=discounts, taxes=taxes)
for variant in self]
return TaxedMoneyRange(min(prices), max(prices))
- price = TaxedMoney(net=self.price, gross=self.price)
+ tax_rate = self.tax_rate or self.product_type.tax_rate
+ price = apply_tax_to_price(taxes, tax_rate, self.price)
discounted_price = calculate_discounted_price(
self, price, discounts)
return TaxedMoneyRange(start=discounted_price, stop=discounted_price)
@@ -213,9 +228,11 @@ class ProductVariant(models.Model):
if quantity > self.quantity_available:
raise InsufficientStock(self)
- def get_price_per_item(self, discounts=None):
+ def get_price_per_item(self, discounts=None, taxes=None):
+ tax_rate = (
+ self.product.tax_rate or self.product.product_type.tax_rate)
price = self.price_override or self.product.price
- price = TaxedMoney(net=price, gross=price)
+ price = apply_tax_to_price(taxes, tax_rate, price)
price = calculate_discounted_price(self.product, price, discounts)
return price
diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.py
index ede7a70c1e..7fed3d0394 100644
--- a/saleor/product/utils/__init__.py
+++ b/saleor/product/utils/__init__.py
@@ -105,7 +105,8 @@ def get_product_list_context(request, filter_set):
products_paginated = get_paginator_items(
filter_set.qs, settings.PAGINATE_BY, request.GET.get('page'))
products_and_availability = list(products_with_availability(
- products_paginated, request.discounts, request.currency))
+ products_paginated, request.discounts, request.currency,
+ request.taxes))
now_sorted_by = get_now_sorted_by(filter_set)
arg_sort_by = request.GET.get('sort_by')
is_descending = arg_sort_by.startswith('-') if arg_sort_by else False
diff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.py
index f3de8b8922..23f4e1b22e 100644
--- a/saleor/product/utils/availability.py
+++ b/saleor/product/utils/availability.py
@@ -9,9 +9,10 @@ ProductAvailability = namedtuple(
'discount', 'price_range_local_currency', 'discount_local_currency'))
-def products_with_availability(products, discounts, local_currency):
+def products_with_availability(products, discounts, local_currency, taxes):
for product in products:
- yield product, get_availability(product, discounts, local_currency)
+ yield (product, get_availability(
+ product, discounts, local_currency, taxes))
def get_product_availability_status(product):
@@ -44,10 +45,10 @@ def get_variant_availability_status(variant):
return VariantAvailabilityStatus.AVAILABLE
-def get_availability(product, discounts=None, local_currency=None):
+def get_availability(product, discounts=None, local_currency=None, taxes=None):
# In default currency
- price_range = product.get_price_range(discounts=discounts)
- undiscounted = product.get_price_range()
+ price_range = product.get_price_range(discounts=discounts, taxes=taxes)
+ undiscounted = product.get_price_range(taxes=taxes)
if undiscounted.start > price_range.start:
discount = undiscounted.start - price_range.start
else:
diff --git a/saleor/product/utils/variants_picker.py b/saleor/product/utils/variants_picker.py
index 27b9af7726..7fbc08f759 100644
--- a/saleor/product/utils/variants_picker.py
+++ b/saleor/product/utils/variants_picker.py
@@ -7,8 +7,9 @@ from ...seo.schema.product import variant_json_ld
from .availability import get_availability
-def get_variant_picker_data(product, discounts=None, local_currency=None):
- availability = get_availability(product, discounts, local_currency)
+def get_variant_picker_data(
+ product, discounts=None, local_currency=None, taxes=None):
+ availability = get_availability(product, discounts, local_currency, taxes)
variants = product.variants.all()
data = {'variantAttributes': [], 'variants': []}
@@ -18,8 +19,8 @@ def get_variant_picker_data(product, discounts=None, local_currency=None):
filter_available_variants = defaultdict(list)
for variant in variants:
- price = variant.get_price_per_item(discounts)
- price_undiscounted = variant.get_price_per_item()
+ price = variant.get_price_per_item(discounts, taxes)
+ price_undiscounted = variant.get_price_per_item(taxes=taxes)
if local_currency:
price_local_currency = to_local_currency(price, local_currency)
else:
diff --git a/saleor/product/views.py b/saleor/product/views.py
index 196a4084f6..6efc85be7b 100644
--- a/saleor/product/views.py
+++ b/saleor/product/views.py
@@ -58,11 +58,12 @@ def product_details(request, slug, product_id, form=None):
product.available_on is None or product.available_on <= today)
if form is None:
form = handle_cart_form(request, product, create_cart=False)[0]
- availability = get_availability(product, discounts=request.discounts,
- local_currency=request.currency)
+ availability = get_availability(
+ product, discounts=request.discounts, local_currency=request.currency,
+ taxes=request.taxes)
product_images = get_product_images(product)
variant_picker_data = get_variant_picker_data(
- product, request.discounts, request.currency)
+ product, request.discounts, request.currency, request.taxes)
product_attributes = get_product_attributes_data(product)
# show_variant_picker determines if variant picker is used or select input
show_variant_picker = all([v.attributes for v in product.variants.all()])
diff --git a/saleor/settings.py b/saleor/settings.py
index a5c2ecc039..8749eade70 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -164,6 +164,7 @@ MIDDLEWARE = [
'saleor.core.middleware.country',
'saleor.core.middleware.currency',
'saleor.core.middleware.site',
+ 'saleor.core.middleware.taxes',
'social_django.middleware.SocialAuthExceptionMiddleware',
'impersonate.middleware.ImpersonateMiddleware']
@@ -271,7 +272,7 @@ AUTH_USER_MODEL = 'account.User'
LOGIN_URL = '/account/login/'
-DEFAULT_COUNTRY = 'US'
+DEFAULT_COUNTRY = 'PL' # fixme: revert back to USD before merge
DEFAULT_CURRENCY = 'USD'
DEFAULT_DECIMAL_PLACES = get_currency_fraction(DEFAULT_CURRENCY)
AVAILABLE_CURRENCIES = [DEFAULT_CURRENCY]
@@ -282,9 +283,8 @@ OPENEXCHANGERATES_API_KEY = os.environ.get('OPENEXCHANGERATES_API_KEY')
# Enabling vat requires valid vatlayer access key. By default prices entered in
# dashboard are treated as net amounts. If you wish to reverse that and use
# them as gross amounts instead change the BASE_PRICES_ARE_NET to False
-ENABLE_VAT = False
-BASE_PRICES_ARE_NET = True
VATLAYER_ACCESS_KEY = os.environ.get('VATLAYER_ACCESS_KEY')
+BASE_PRICES_ARE_NET = True
ACCOUNT_ACTIVATION_DAYS = 3
diff --git a/templates/product/_price_range.html b/templates/product/_price_range.html
index 1fcda92ab8..2cf10f2c0f 100644
--- a/templates/product/_price_range.html
+++ b/templates/product/_price_range.html
@@ -5,4 +5,7 @@
<span>
{% if price_range.start != price_range.stop %}{% trans "from" context "product price range" %} {% endif %}{{ price_range.start.gross|amount:'html' }}
</span>
+ <div class="small">
+ ({{ price_range.start.net|amount:'html' }} + {{ price_range.start.tax|amount:'html' }} VAT)
+ </div>
</span>