Skip to content

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

WIP product and cart tax handling tests

Rafał Pitońaed1b802120c
diff --git a/saleor/cart/models.py b/saleor/cart/models.py
index 5151d2d80b..a4c0b649d6 100644
--- a/saleor/cart/models.py
+++ b/saleor/cart/models.py
@@ -83,6 +83,7 @@ class Cart(models.Model):
def __init__(self, *args, **kwargs):
self.discounts = kwargs.pop('discounts', None)
+ self.taxes = kwargs.pop('taxes', None)
super().__init__(*args, **kwargs)
def update_quantity(self):
@@ -124,11 +125,12 @@ class Cart(models.Model):
def __len__(self):
return self.lines.count()
- def get_total(self, discounts=None):
+ def get_total(self, discounts=None, taxes=None):
"""Return the total cost of the cart prior to shipping."""
if not discounts:
discounts = self.discounts
- subtotals = [line.get_total(discounts) for line in self.lines.all()]
+ subtotals = [
+ line.get_total(discounts, taxes) for line in self.lines.all()]
if not subtotals:
raise AttributeError('Calling get_total() on an empty cart')
return sum_prices(subtotals)
@@ -239,15 +241,16 @@ class CartLine(models.Model):
def __setstate__(self, data):
self.variant, self.quantity, self.data = data
- def get_total(self, discounts=None):
+ def get_total(self, discounts=None, taxes=None):
"""Return the total price of this line."""
- amount = self.get_price_per_item(discounts) * self.quantity
+ amount = self.get_price_per_item(discounts, taxes) * self.quantity
return amount.quantize(CENTS)
# pylint: disable=W0221
- def get_price_per_item(self, discounts=None):
+ def get_price_per_item(self, discounts=None, taxes=None):
"""Return the unit price of the line."""
- return self.variant.get_price_per_item(discounts=discounts)
+ return self.variant.get_price_per_item(
+ discounts=discounts, taxes=taxes)
def is_shipping_required(self):
"""Return `True` if the related product variant requires shipping."""
diff --git a/saleor/cart/utils.py b/saleor/cart/utils.py
index aefae7f340..7eac997fdf 100644
--- a/saleor/cart/utils.py
+++ b/saleor/cart/utils.py
@@ -209,7 +209,7 @@ def get_or_empty_db_cart(cart_queryset=Cart.objects.all()):
return get_cart
-def get_cart_data(cart, shipping_range, currency, discounts):
+def get_cart_data(cart, shipping_range, currency, discounts, taxes):
"""Return a JSON-serializable representation of the cart."""
cart_total = None
local_cart_total = None
@@ -217,7 +217,7 @@ def get_cart_data(cart, shipping_range, currency, discounts):
total_with_shipping = None
local_total_with_shipping = None
if cart:
- cart_total = cart.get_total(discounts=discounts)
+ cart_total = cart.get_total(discounts, taxes)
local_cart_total = to_local_currency(cart_total, currency)
shipping_required = cart.is_shipping_required()
total_with_shipping = TaxedMoneyRange(
diff --git a/saleor/cart/views.py b/saleor/cart/views.py
index ee28c6be86..eef90d372d 100644
--- a/saleor/cart/views.py
+++ b/saleor/cart/views.py
@@ -17,6 +17,7 @@ from .utils import (
def index(request, cart):
"""Display cart details."""
discounts = request.discounts
+ taxes = request.taxes
cart_lines = []
check_product_availability_and_warn(request, cart)
@@ -39,8 +40,8 @@ def index(request, cart):
initial=initial, discounts=discounts)
cart_lines.append({
'variant': line.variant,
- 'get_price_per_item': line.get_price_per_item(discounts),
- 'get_total': line.get_total(discounts=discounts),
+ 'get_price_per_item': line.get_price_per_item(discounts, taxes),
+ 'get_total': line.get_total(discounts, taxes),
'form': form})
default_country = get_user_shipping_country(request)
@@ -48,7 +49,7 @@ def index(request, cart):
default_country_options = get_shipment_options(default_country)
cart_data = get_cart_data(
- cart, default_country_options, request.currency, request.discounts)
+ cart, default_country_options, request.currency, discounts, taxes)
ctx = {
'cart_lines': cart_lines,
'country_form': country_form,
@@ -84,6 +85,7 @@ def update(request, cart, variant_id):
return redirect('cart:index')
variant = get_object_or_404(ProductVariant, pk=variant_id)
discounts = request.discounts
+ taxes = request.taxes
status = None
form = ReplaceCartLineForm(
request.POST, cart=cart, variant=variant, discounts=discounts)
@@ -99,9 +101,9 @@ def update(request, cart, variant_id):
updated_line = cart.get_line(form.cart_line.variant)
if updated_line:
response['subtotal'] = format_money(
- updated_line.get_total(discounts=discounts).gross)
+ updated_line.get_total(discounts, taxes).gross)
if cart:
- cart_total = cart.get_total(discounts=discounts)
+ cart_total = cart.get_total(discounts, taxes)
response['total'] = format_money(cart_total.gross)
local_cart_total = to_local_currency(cart_total, request.currency)
if local_cart_total is not None:
@@ -116,9 +118,12 @@ def update(request, cart, variant_id):
@get_or_empty_db_cart(cart_queryset=Cart.objects.for_display())
def summary(request, cart):
"""Display a cart summary suitable for displaying on all pages."""
+ discounts = request.discounts
+ taxes = request.taxes
+
def prepare_line_data(line):
first_image = line.variant.get_first_image()
- line_total = line.get_total(discounts=request.discounts)
+ line_total = line.get_total(discounts, taxes)
return {
'product': line.variant.product,
'variant': line.variant.name,
@@ -126,10 +131,11 @@ def summary(request, cart):
'image': first_image,
'line_total': format_money(line_total.gross),
'variant_url': line.variant.get_absolute_url()}
+
if cart.quantity == 0:
data = {'quantity': 0}
else:
- cart_total = cart.get_total(discounts=request.discounts)
+ cart_total = cart.get_total(discounts, taxes)
data = {
'quantity': cart.quantity,
'total': format_money(cart_total.gross),
diff --git a/saleor/settings.py b/saleor/settings.py
index 3de609dc3f..6d34709e7a 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -272,7 +272,7 @@ AUTH_USER_MODEL = 'account.User'
LOGIN_URL = '/account/login/'
-DEFAULT_COUNTRY = 'US'
+DEFAULT_COUNTRY = 'US' # fixme: revert back to US before merge
DEFAULT_CURRENCY = 'USD'
DEFAULT_DECIMAL_PLACES = get_currency_fraction(DEFAULT_CURRENCY)
AVAILABLE_CURRENCIES = [DEFAULT_CURRENCY]
diff --git a/tests/conftest.py b/tests/conftest.py
index 5e7493ff12..b3f18a3bec 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -9,6 +9,7 @@ from django.core.files import File
from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms import ModelForm
from django.utils.encoding import smart_text
+from django_prices_vatlayer.models import VAT
from django_prices_vatlayer.utils import get_tax_for_rate
from payments import FraudStatus, PaymentStatus
from PIL import Image
@@ -714,3 +715,10 @@ def taxes(tax_rates):
rate: get_tax_for_rate(tax_rates, rate)
for rate in tax_rates['reduced_rates']})
return taxes
+
+
+def vatlayer(db, settings, tax_rates, taxes):
+ settings.VATLAYER_ACCESS_KEY = 'testvatlayer'
+ VAT.objects.create(country_code=settings.DEFAULT_COUNTRY, data=tax_rates)
+ return taxes
diff --git a/tests/test_cart.py b/tests/test_cart.py
index c5da3d6747..1a7b06673c 100644
--- a/tests/test_cart.py
+++ b/tests/test_cart.py
@@ -29,6 +29,7 @@ def cart_request_factory(rf, monkeypatch):
else:
request.user = user
request.discounts = Sale.objects.all()
+ request.taxes = None
monkeypatch.setattr(
request, 'get_signed_cookie', Mock(return_value=token))
return request
@@ -186,6 +187,7 @@ def test_get_cart_from_request(
queryset = Cart.objects.all()
token = uuid4()
request = cart_request_factory(user=customer_user, token=token)
+
user_cart = Cart(user=customer_user)
mock_get_for_user = Mock(return_value=user_cart)
monkeypatch.setattr(
@@ -195,6 +197,7 @@ def test_get_cart_from_request(
assert returned_cart == user_cart
assert list(returned_cart.discounts) == list(request.discounts)
+ assert returned_cart.taxes == request.taxes
mock_get_for_user = Mock(return_value=None)
monkeypatch.setattr(
@@ -504,6 +507,17 @@ def test_view_cart(client, sale, product, request_cart):
assert response.status_code == 200
+def test_view_cart_with_taxes(client, sale, product, request_cart, vatlayer):
+ variant = product.variants.get()
+ request_cart.add(variant, 1)
+ response = client.get('/cart/')
+ response_cart_line = response.context[0]['cart_lines'][0]
+ cart_line = request_cart.lines.first()
+ assert response_cart_line['get_total'].tax.amount
+ assert not response_cart_line['get_total'] == cart_line.get_total()
+ assert response.status_code == 200
+
+
def test_view_update_cart_quantity(
client, local_currency, product, request_cart):
variant = product.variants.get()
@@ -515,6 +529,18 @@ def test_view_update_cart_quantity(
assert request_cart.quantity == 3
+def test_view_update_cart_quantity_with_taxes(
+ client, local_currency, product, request_cart, vatlayer):
+ variant = product.variants.get()
+ request_cart.add(variant, 1)
+ response = client.post(
+ '/cart/update/%s/' % (variant.pk,),
+ {'quantity': 3},
+ HTTP_X_REQUESTED_WITH='XMLHttpRequest')
+ assert response.status_code == 200
+ assert request_cart.quantity == 3
+
+
def test_view_invalid_update_cart(client, product, request_cart):
variant = product.variants.get()
request_cart.add(variant, 1)
@@ -684,7 +710,7 @@ def test_get_or_create_db_cart(customer_user, db, rf):
def test_get_cart_data(request_cart_with_item, shipping_method):
shipment_option = get_shipment_options('PL')
cart_data = utils.get_cart_data(
- request_cart_with_item, shipment_option, 'USD', None)
+ request_cart_with_item, shipment_option, 'USD', None, None)
assert cart_data['cart_total'] == TaxedMoney(
net=Money(10, 'USD'), gross=Money(10, 'USD'))
assert cart_data['total_with_shipping'].start == TaxedMoney(
@@ -694,7 +720,7 @@ def test_get_cart_data(request_cart_with_item, shipping_method):
def test_get_cart_data_no_shipping(request_cart_with_item):
shipment_option = get_shipment_options('PL')
cart_data = utils.get_cart_data(
- request_cart_with_item, shipment_option, 'USD', None)
+ request_cart_with_item, shipment_option, 'USD', None, None)
cart_total = cart_data['cart_total']
assert cart_total == TaxedMoney(
net=Money(10, 'USD'), gross=Money(10, 'USD'))