Skip to content

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

Improve passing taxes and dashboard amounts

Anna Siwik18b44777e8d9
diff --git a/saleor/cart/forms.py b/saleor/cart/forms.py
index 3706a500ad..94b843bb90 100644
--- a/saleor/cart/forms.py
+++ b/saleor/cart/forms.py
@@ -47,6 +47,7 @@ class AddToCartForm(forms.Form):
self.cart = kwargs.pop('cart')
self.product = kwargs.pop('product')
self.discounts = kwargs.pop('discounts', ())
+ self.taxes = kwargs.pop('taxes', {})
super().__init__(*args, **kwargs)
def clean(self):
@@ -153,7 +154,11 @@ class CountryForm(forms.Form):
label=pgettext_lazy('Country form field label', 'Country'),
choices=countries)
+ def __init__(self, *args, **kwargs):
+ self.taxes = kwargs.pop('taxes', {})
+ super().__init__(*args, **kwargs)
+
def get_shipment_options(self):
"""Return a list of shipping methods for the selected country."""
code = self.cleaned_data['country']
- return get_shipment_options(code)
+ return get_shipment_options(code, self.taxes)
diff --git a/saleor/cart/models.py b/saleor/cart/models.py
index e7526181a5..be1e1d5387 100644
--- a/saleor/cart/models.py
+++ b/saleor/cart/models.py
@@ -81,11 +81,6 @@ class Cart(models.Model):
class Meta:
ordering = ('-last_status_change',)
- 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):
"""Recalculate cart quantity based on lines."""
total_lines = self.count()['total_quantity']
@@ -127,8 +122,6 @@ class Cart(models.Model):
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, taxes) for line in self.lines.all()]
if not subtotals:
diff --git a/saleor/cart/urls.py b/saleor/cart/urls.py
index 4292f7fb9c..2416284603 100644
--- a/saleor/cart/urls.py
+++ b/saleor/cart/urls.py
@@ -6,5 +6,5 @@ urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^update/(?P<variant_id>\d+)/$', views.update, name='update-line'),
url(r'^summary/$', views.summary, name='cart-summary'),
- url(r'^shipingoptions/$', views.get_shipping_options,
+ url(r'^shipping-options/$', views.get_shipping_options,
name='shipping-options')]
diff --git a/saleor/cart/utils.py b/saleor/cart/utils.py
index fe249688b8..9bf96b6411 100644
--- a/saleor/cart/utils.py
+++ b/saleor/cart/utils.py
@@ -155,7 +155,6 @@ def get_or_create_cart_from_request(request, cart_queryset=Cart.objects.all()):
def get_cart_from_request(request, cart_queryset=Cart.objects.all()):
"""Fetch cart from database or return a new instance based on cookie."""
- discounts = request.discounts
if request.user.is_authenticated:
cart = get_user_cart(request.user, cart_queryset)
user = request.user
@@ -164,9 +163,8 @@ def get_cart_from_request(request, cart_queryset=Cart.objects.all()):
cart = get_anonymous_cart_from_token(token, cart_queryset)
user = None
if cart is not None:
- cart.discounts = discounts
return cart
- return Cart(user=user, discounts=discounts)
+ return Cart(user=user)
def get_or_create_db_cart(cart_queryset=Cart.objects.all()):
diff --git a/saleor/cart/views.py b/saleor/cart/views.py
index 254cbdbe3a..bb588625d5 100644
--- a/saleor/cart/views.py
+++ b/saleor/cart/views.py
@@ -36,8 +36,9 @@ def index(request, cart):
'variant__product__product_type__variant_attributes')
for line in lines:
initial = {'quantity': line.quantity}
- form = ReplaceCartLineForm(None, cart=cart, variant=line.variant,
- initial=initial, discounts=discounts)
+ form = ReplaceCartLineForm(
+ None, cart=cart, variant=line.variant, initial=initial,
+ discounts=discounts, taxes=taxes)
cart_lines.append({
'variant': line.variant,
'get_price': line.variant.get_price(discounts, taxes),
@@ -64,7 +65,7 @@ def index(request, cart):
@get_or_empty_db_cart(cart_queryset=Cart.objects.for_display())
def get_shipping_options(request, cart):
"""Display shipping options to get a price estimate."""
- country_form = CountryForm(request.POST or None)
+ country_form = CountryForm(request.POST or None, taxes=request.taxes)
if country_form.is_valid():
shipments = country_form.get_shipment_options()
else:
@@ -73,7 +74,7 @@ def get_shipping_options(request, cart):
'default_country_options': shipments,
'country_form': country_form}
cart_data = get_cart_data(
- cart, shipments, request.currency, request.discounts)
+ cart, shipments, request.currency, request.discounts, request.taxes)
ctx.update(cart_data)
return TemplateResponse(
request, 'cart/_subtotal_table.html', ctx)
@@ -89,7 +90,8 @@ def update(request, cart, variant_id):
taxes = request.taxes
status = None
form = ReplaceCartLineForm(
- request.POST, cart=cart, variant=variant, discounts=discounts)
+ request.POST, cart=cart, variant=variant, discounts=discounts,
+ taxes=taxes)
if form.is_valid():
form.save()
response = {
diff --git a/saleor/checkout/core.py b/saleor/checkout/core.py
index 1fe80f9e3d..175bee4692 100644
--- a/saleor/checkout/core.py
+++ b/saleor/checkout/core.py
@@ -2,13 +2,12 @@
from datetime import date
from functools import wraps
-from django.conf import settings
from django.contrib.sites.models import Site
from django.db import transaction
from django.forms.models import model_to_dict
from django.utils.encoding import smart_text
from django.utils.translation import get_language
-from prices import Money, TaxedMoney
+from prices import Money
from ..account.models import Address
from ..account.utils import store_user_address
@@ -42,25 +41,26 @@ class Checkout:
VERSION = '1.0.0'
- def __init__(self, cart, user, taxes, tracking_code):
+ def __init__(self, cart, user, discounts, taxes, tracking_code):
self.modified = False
self.cart = cart
- self.storage = {'version': self.VERSION}
- self.tracking_code = tracking_code
self.user = user
+ self.discounts = discounts
self.taxes = taxes
- self.discounts = cart.discounts
+ self.tracking_code = tracking_code
+ self.storage = {'version': self.VERSION}
self._shipping_method = None
self._shipping_address = None
@classmethod
- def from_storage(cls, storage_data, cart, user, taxes, tracking_code):
+ def from_storage(
+ cls, storage_data, cart, user, discounts, taxes, tracking_code):
"""Restore a previously serialized checkout session.
`storage_data` is the value previously returned by
`Checkout.for_storage()`.
"""
- checkout = cls(cart, user, taxes, tracking_code)
+ checkout = cls(cart, user, discounts, taxes, tracking_code)
checkout.storage = storage_data
try:
version = checkout.storage['version']
@@ -336,8 +336,8 @@ class Checkout:
for line in self.cart.lines.all():
add_variant_to_order(
- order, line.variant, line.quantity, self.cart.discounts,
- self.taxes, add_to_existing=False)
+ order, line.variant, line.quantity, self.discounts, self.taxes,
+ add_to_existing=False)
if voucher is not None:
increase_voucher_usage(voucher)
@@ -381,7 +381,7 @@ class Checkout:
def get_subtotal(self):
"""Calculate order total without shipping and discount."""
- return self.cart.get_total(discounts=self.discounts, taxes=self.taxes)
+ return self.cart.get_total(self.discounts, self.taxes)
def get_total(self):
"""Calculate order total with shipping and discount amount."""
@@ -410,7 +410,8 @@ def load_checkout(view):
session_data = ''
tracking_code = analytics.get_client_id(request)
checkout = Checkout.from_storage(
- session_data, cart, request.user, request.taxes, tracking_code)
+ session_data, cart, request.user, request.discounts, 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__.py
index 7f2c9b24cf..9af4a4d263 100644
--- a/saleor/core/utils/__init__.py
+++ b/saleor/core/utils/__init__.py
@@ -113,10 +113,10 @@ def get_taxes_for_country(country):
'tax': get_tax_for_rate(tax_rates)}}
if tax_rates['reduced_rates']:
taxes.update({
- rate: {
- 'value': tax_rates['reduced_rates'][rate],
- 'tax': get_tax_for_rate(tax_rates, rate)}
- for rate in tax_rates['reduced_rates']})
+ rate_name: {
+ 'value': tax_rates['reduced_rates'][rate_name],
+ 'tax': get_tax_for_rate(tax_rates, rate_name)}
+ for rate_name in tax_rates['reduced_rates']})
return taxes
diff --git a/saleor/core/views.py b/saleor/core/views.py
index 019a19224e..4034b143bf 100644
--- a/saleor/core/views.py
+++ b/saleor/core/views.py
@@ -15,8 +15,8 @@ from ..seo.schema.webpage import get_webpage_schema
def home(request):
products = products_for_homepage()[:8]
products = products_with_availability(
- products, discounts=request.discounts, local_currency=request.currency,
- taxes=request.taxes)
+ products, discounts=request.discounts, taxes=request.taxes,
+ local_currency=request.currency)
webpage_schema = get_webpage_schema(request)
return TemplateResponse(
request, 'home.html', {
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 14ff402d64..44db78cede 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -27,8 +27,8 @@ from ...shipping.models import ANY_COUNTRY, ShippingMethodCountry
from ..forms import AjaxSelect2ChoiceField
from ..widgets import PhonePrefixWidget
from .utils import (
- fulfill_order_line, get_voucher_discount_for_order,
- remove_customer_from_order, update_order_with_user_addresses)
+ fulfill_order_line, remove_customer_from_order,
+ update_order_with_user_addresses)
class CreateOrderFromDraftForm(forms.ModelForm):
@@ -181,7 +181,6 @@ class OrderShippingForm(forms.ModelForm):
self.instance.shipping_method_name = method.shipping_method.name
self.instance.shipping_price = method.get_total_price()
recalculate_order(self.instance)
- recalculate_order(self.instance)
return super().save(commit)
diff --git a/saleor/graphql/core/types.py b/saleor/graphql/core/types.py
index 025b72439f..a850df24f6 100644
--- a/saleor/graphql/core/types.py
+++ b/saleor/graphql/core/types.py
@@ -53,6 +53,16 @@ class Money(graphene.ObjectType):
return prices_i18n.amount(self)
+class MoneyRange(graphene.ObjectType):
+ start = graphene.Field(
+ Money, description='Lower bound of a price range.')
+ stop = graphene.Field(
+ Money, description='Upper bound of a price range.')
+
+ class Meta:
+ description = 'Represents a range of amounts of money.'
+
+
class TaxedMoney(graphene.ObjectType):
currency = graphene.String(description='Currency code.')
gross = graphene.Field(
diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.py
index f78a964037..c63c7d3e04 100644
--- a/saleor/graphql/product/types.py
+++ b/saleor/graphql/product/types.py
@@ -10,7 +10,7 @@ from ...product.utils.costs import get_product_costs_data
from ..core.decorators import permission_required
from ..core.filters import DistinctFilterSet
from ..core.types import (
- CountableDjangoObjectType, Money, TaxedMoney, TaxedMoneyRange)
+ CountableDjangoObjectType, Money, MoneyRange, TaxedMoney, TaxedMoneyRange)
from .filters import ProductFilterSet
@@ -106,7 +106,7 @@ class Product(CountableDjangoObjectType):
attributes = graphene.List(
SelectedAttribute,
description='List of product attributes assigned to this product.')
- purchase_cost = graphene.Field(TaxedMoneyRange)
+ purchase_cost = graphene.Field(MoneyRange)
gross_margin = graphene.List(GrossMargin)
class Meta:
@@ -126,7 +126,7 @@ class Product(CountableDjangoObjectType):
def resolve_availability(self, info):
context = info.context
availability = get_availability(
- self, context.discounts, context.currency)
+ self, context.discounts, context.taxes, context.currency)
return ProductAvailability(**availability._asdict())
def resolve_attributes(self, info):
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 38b70f086b..c28930f3d1 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -131,8 +131,15 @@ def attach_order_to_user(order, user):
def get_tax_rate_by_name(rate_name, taxes=None):
"""Return value of tax rate for current taxes."""
- tax = taxes.get(rate_name) or taxes.get(DEFAULT_TAX_RATE_NAME)
- return tax['value'] if tax else 0
+ if not taxes:
+ return 0
+
+ if rate_name in taxes:
+ tax_rate = taxes[rate_name]['value']
+ else:
+ tax_rate = taxes[DEFAULT_TAX_RATE_NAME]['value']
+
+ return tax_rate
def add_variant_to_order(
@@ -154,7 +161,7 @@ def add_variant_to_order(
return
if quantity_not_fulfilled > variant.quantity_available:
raise InsufficientStock(variant)
- price = variant.get_price(discounts, taxes=taxes)
+ price = variant.get_price(discounts, taxes)
order.lines.create(
product_name=variant.display_product(),
product_sku=variant.sku,
diff --git a/saleor/product/forms.py b/saleor/product/forms.py
index 2cebd77d04..12710bf28f 100644
--- a/saleor/product/forms.py
+++ b/saleor/product/forms.py
@@ -1,6 +1,7 @@
import json
from django import forms
+from django.contrib.sites.models import Site
from django.utils.encoding import smart_text
from django.utils.translation import pgettext_lazy
from django_prices.templatetags.prices_i18n import amount
@@ -10,22 +11,27 @@ from ..cart.forms import AddToCartForm
class VariantChoiceField(forms.ModelChoiceField):
discounts = None
+ taxes = None
+ display_gross = True
def label_from_instance(self, obj):
variant_label = smart_text(obj)
+ price = obj.get_price(self.discounts, self.taxes)
+ price = price.gross if self.display_gross else price.net
label = pgettext_lazy(
'Variant choice field label',
'%(variant_label)s - %(price)s') % {
- 'variant_label': variant_label,
- 'price': amount(
- obj.get_price(discounts=self.discounts).gross)}
+ 'variant_label': variant_label, 'price': amount(price)}
return label
- def update_field_data(self, variants, cart):
+ def update_field_data(self, variants, discounts, taxes):
"""Initialize variant picker metadata."""
self.queryset = variants
- self.discounts = cart.discounts
+ self.discounts = discounts
+ self.taxes = taxes
self.empty_label = None
+ self.display_gross = (
+ Site.objects.get_current().settings.display_gross_prices)
images_map = {
variant.pk: [
vi.image.image.url for vi in variant.variant_images.all()]
@@ -43,7 +49,8 @@ class ProductForm(AddToCartForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
variant_field = self.fields['variant']
- variant_field.update_field_data(self.product.variants, self.cart)
+ variant_field.update_field_data(
+ self.product.variants, self.discounts, self.taxes)
def get_variant(self, cleaned_data):
return cleaned_data.get('variant')
diff --git a/saleor/product/models.py b/saleor/product/models.py
index a1814edec4..5410383ccb 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -200,17 +200,17 @@ class ProductVariant(models.Model):
def quantity_available(self):
return max(self.quantity - self.quantity_allocated, 0)
- def get_total(self):
- if self.cost_price:
- return TaxedMoney(net=self.cost_price, gross=self.cost_price)
-
def check_quantity(self, quantity):
if quantity > self.quantity_available:
raise InsufficientStock(self)
+ @property
+ def base_price(self):
+ return self.price_override or self.product.price
+
def get_price(self, discounts=None, taxes=None):
- price = self.price_override or self.product.price
- price = calculate_discounted_price(self.product, price, discounts)
+ price = calculate_discounted_price(
+ self.product, self.base_price, discounts)
if not self.product.charge_taxes:
taxes = None
tax_rate = (
diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.py
index 7fed3d0394..96dbfd57fd 100644
--- a/saleor/product/utils/__init__.py
+++ b/saleor/product/utils/__init__.py
@@ -47,7 +47,7 @@ def handle_cart_form(request, product, create_cart=False):
cart = get_cart_from_request(request)
form = ProductForm(
cart=cart, product=product, data=request.POST or None,
- discounts=request.discounts)
+ discounts=request.discounts, taxes=request.taxes)
return form, cart
@@ -105,8 +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,
- request.taxes))
+ products_paginated, request.discounts, request.taxes,
+ request.currency))
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 23f4e1b22e..6a7c61aec5 100644
--- a/saleor/product/utils/availability.py
+++ b/saleor/product/utils/availability.py
@@ -9,10 +9,10 @@ ProductAvailability = namedtuple(
'discount', 'price_range_local_currency', 'discount_local_currency'))
-def products_with_availability(products, discounts, local_currency, taxes):
+def products_with_availability(products, discounts, taxes, local_currency):
for product in products:
yield (product, get_availability(
- product, discounts, local_currency, taxes))
+ product, discounts, taxes, local_currency))
def get_product_availability_status(product):
@@ -45,7 +45,7 @@ def get_variant_availability_status(variant):
return VariantAvailabilityStatus.AVAILABLE
-def get_availability(product, discounts=None, local_currency=None, taxes=None):
+def get_availability(product, discounts=None, taxes=None, local_currency=None):
# In default currency
price_range = product.get_price_range(discounts=discounts, taxes=taxes)
undiscounted = product.get_price_range(taxes=taxes)
diff --git a/saleor/product/utils/costs.py b/saleor/product/utils/costs.py
index 6644029ea9..b0edeeb544 100644
--- a/saleor/product/utils/costs.py
+++ b/saleor/product/utils/costs.py
@@ -1,10 +1,11 @@
-from prices import TaxedMoneyRange
+from django.conf import settings
+from prices import Money, MoneyRange
from ...core.utils import ZERO_TAXED_MONEY
def get_product_costs_data(product):
- purchase_costs_range = TaxedMoneyRange(
+ purchase_costs_range = MoneyRange(
start=ZERO_TAXED_MONEY, stop=ZERO_TAXED_MONEY)
gross_margin = (0, 0)
@@ -14,7 +15,7 @@ def get_product_costs_data(product):
variants = product.variants.all()
costs_data = get_cost_data_from_variants(variants)
if costs_data.costs:
- purchase_costs_range = TaxedMoneyRange(
+ purchase_costs_range = MoneyRange(
min(costs_data.costs), max(costs_data.costs))
if costs_data.margins:
gross_margin = (costs_data.margins[0], costs_data.margins[-1])
@@ -25,7 +26,7 @@ class CostsData:
__slots__ = ('costs', 'margins')
def __init__(self, costs, margins):
- self.costs = sorted(costs, key=lambda x: x.gross)
+ self.costs = sorted(costs)
self.margins = sorted(margins)
@@ -51,15 +52,14 @@ def get_variant_costs_data(variant):
def get_cost_price(variant):
if not variant.cost_price:
- return ZERO_TAXED_MONEY
- return variant.get_total()
+ return Money(0, settings.DEFAULT_CURRENCY)
+ return variant.cost_price
def get_margin_for_variant(variant):
- variant_cost = variant.get_total()
- if variant_cost is None:
+ if variant.cost_price is None:
return None
- price = variant.get_price()
- margin = price - variant_cost
- percent = round((margin.gross / price.gross) * 100, 0)
+ base_price = variant.base_price
+ margin = base_price - variant.cost_price
+ percent = round((margin / base_price) * 100, 0)
return percent
diff --git a/saleor/product/utils/variants_picker.py b/saleor/product/utils/variants_picker.py
index f0351d0ed2..7b48b57c5e 100644
--- a/saleor/product/utils/variants_picker.py
+++ b/saleor/product/utils/variants_picker.py
@@ -10,8 +10,8 @@ from .availability import get_availability
def get_variant_picker_data(
- product, discounts=None, local_currency=None, taxes=None):
- availability = get_availability(product, discounts, local_currency, taxes)
+ product, discounts=None, taxes=None, local_currency=None):
+ availability = get_availability(product, discounts, taxes, local_currency)
variants = product.variants.all()
data = {'variantAttributes': [], 'variants': []}
diff --git a/saleor/product/views.py b/saleor/product/views.py
index 6efc85be7b..0cbe285c4d 100644
--- a/saleor/product/views.py
+++ b/saleor/product/views.py
@@ -59,11 +59,11 @@ def product_details(request, slug, product_id, form=None):
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,
- taxes=request.taxes)
+ product, discounts=request.discounts, taxes=request.taxes,
+ local_currency=request.currency)
product_images = get_product_images(product)
variant_picker_data = get_variant_picker_data(
- product, request.discounts, request.currency, request.taxes)
+ product, request.discounts, request.taxes, request.currency)
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/search/views.py b/saleor/search/views.py
index 96b6e8c62a..5f0b9aec7b 100644
--- a/saleor/search/views.py
+++ b/saleor/search/views.py
@@ -21,8 +21,8 @@ def paginate_results(results, get_data, paginate_by=settings.PAGINATE_BY):
def evaluate_search_query(form, request):
results = products_with_details(request.user) & form.search()
return products_with_availability(
- results, discounts=request.discounts, local_currency=request.currency,
- taxes=request.taxes)
+ results, discounts=request.discounts, taxes=request.taxes,
+ local_currency=request.currency)
def search(request):
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index 3da19a1f26..9dc6958c03 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -45,7 +45,7 @@ class ShippingMethod(models.Model):
country.get_total_price()
for country in self.price_per_country.all()]
if prices:
- return MoneyRange(min(prices), max(prices))
+ return MoneyRange(min(prices).net, max(prices).net)
return None
@@ -99,8 +99,6 @@ class ShippingMethodCountry(models.Model):
self.shipping_method, self.get_country_code_display())
def get_total_price(self, taxes=None):
- if not taxes:
- return self.price
return get_taxed_shipping_price(self.price, taxes)
@property
diff --git a/templates/dashboard/product/detail.html b/templates/dashboard/product/detail.html
index 2f927342dc..f4374cbf61 100644
--- a/templates/dashboard/product/detail.html
+++ b/templates/dashboard/product/detail.html
@@ -120,9 +120,7 @@
<td>{{ variant }}</td>
<td class="wide">{% render_variant_availability_status variant %}</td>
<td class="right-align">
- {% with request.site.settings.include_taxes_in_prices as display_gross_prices %}
- {% taxed_price variant.get_price display_gross_prices %}
- {% endwith %}
+ {{ variant.base_price|amount:'html' }}
</td>
<td class="right-align">
{% margins_for_variant variant=variant as margins %}
@@ -206,7 +204,7 @@
{% trans "Purchase cost" context "Product field" %}
</td>
<td class="right-align">
- {% taxed_price purchase_cost display_gross_prices %}
+ {% taxed_price purchase_cost %}
</td>
</tr>
<tr>
diff --git a/tests/conftest.py b/tests/conftest.py
index a5c87a524d..f1f604af17 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -83,8 +83,6 @@ def request_cart(cart, monkeypatch):
monkeypatch.setattr(
utils, 'get_cart_from_request',
lambda request, cart_queryset=None: cart)
- cart.discounts = Sale.objects.all()
- cart.taxes = None
return cart
@@ -352,14 +350,14 @@ def product_with_images(product_type, default_category):
@pytest.fixture
-def anonymous_checkout():
- return Checkout((), AnonymousUser(), None, 'tracking_code')
+def checkout():
+ return Checkout(Mock(), AnonymousUser(), None, None, 'tracking_code')
@pytest.fixture
def checkout_with_items(request_cart_with_item, customer_user):
checkout = Checkout(
- request_cart_with_item, customer_user, None, 'tracking_code')
+ request_cart_with_item, customer_user, None, None, 'tracking_code')
checkout.shipping_address = customer_user.default_shipping_address
return checkout
diff --git a/tests/dashboard/test_product.py b/tests/dashboard/test_product.py
index d9389a0d73..0714b994b4 100644
--- a/tests/dashboard/test_product.py
+++ b/tests/dashboard/test_product.py
@@ -617,7 +617,7 @@ def test_hide_field_in_variant_choice_field_form():
variants, cart = MagicMock(), MagicMock()
variants.count.return_value = 1
variants.all()[0].pk = 'test'
- form.update_field_data(variants, cart)
+ form.update_field_data(variants, discounts=None, taxes=None)
assert isinstance(form.widget, HiddenInput)
assert form.widget.attrs.get('value') == 'test'
diff --git a/tests/test_cart.py b/tests/test_cart.py
index fff91c5dfc..4bed6d394e 100644
--- a/tests/test_cart.py
+++ b/tests/test_cart.py
@@ -8,7 +8,6 @@ from django.core import signing
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.urls import reverse
-from django_babel.templatetags.babel import currencyfmt
from prices import Money, TaxedMoney
from saleor.cart import CartStatus, forms, utils
@@ -196,9 +195,6 @@ def test_get_cart_from_request(
mock_get_for_user.assert_called_once_with(customer_user, queryset)
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(
'saleor.cart.utils.get_user_cart', mock_get_for_user)
@@ -293,13 +289,14 @@ def test_adding_zero_quantity(cart, product):
assert len(cart) == 0
-def test_adding_same_variant(cart, product):
+def test_adding_same_variant(cart, product, taxes):
variant = product.variants.get()
cart.add(variant, 1)
cart.add(variant, 2)
assert len(cart) == 1
assert cart.count() == {'total_quantity': 3}
- assert cart.get_total().gross == Money(30, 'USD')
+ cart_total = TaxedMoney(net=Money('24.39', 'USD'), gross=Money(30, 'USD'))
+ assert cart.get_total(taxes=taxes) == cart_total
def test_replacing_same_variant(cart, product):
@@ -494,7 +491,7 @@ def test_view_empty_cart(client, request_cart):
assert response.status_code == 200
-def test_view_cart(client, sale, product, request_cart):
+def test_view_cart_without_taxes(client, sale, product, request_cart):
variant = product.variants.get()
request_cart.add(variant, 1)
response = client.get(reverse('cart:index'))
@@ -578,14 +575,14 @@ def test_cart_page_with_openexchagerates(
assert context['local_cart_total'].currency == 'PLN'
-def test_cart_summary_page(client, product, request_cart):
+def test_cart_summary_page(client, product, request_cart, vatlayer, taxes):
variant = product.variants.get()
request_cart.add(variant, 1)
response = client.get(reverse('cart:cart-summary'))
assert response.status_code == 200
content = response.context
assert content['quantity'] == request_cart.quantity
- cart_total = request_cart.get_total()
+ cart_total = request_cart.get_total(taxes=taxes)
assert content['total'] == cart_total
assert len(content['lines']) == 1
cart_line = content['lines'][0]
@@ -600,16 +597,17 @@ def test_cart_summary_page_empty_cart(client, request_cart):
assert data['quantity'] == 0
-def test_total_with_discount(client, sale, request_cart, product):
+def test_cart_line_total_with_discount_and_taxes(
+ sale, request_cart, product, taxes):
sales = Sale.objects.all()
variant = product.variants.get()
request_cart.add(variant, 1)
line = request_cart.lines.first()
- assert line.get_total(discounts=sales) == TaxedMoney(
- net=Money(5, 'USD'), gross=Money(5, 'USD'))
+ assert line.get_total(discounts=sales, taxes=taxes) == TaxedMoney(
+ net=Money('4.07', 'USD'), gross=Money('5.00', 'USD'))
-def test_cart_queryset(customer_user):
+def test_cart_queryset():
canceled_cart = Cart.objects.create(status=CartStatus.CANCELED)
canceled = Cart.objects.canceled()
assert canceled.filter(pk=canceled_cart.pk).exists()
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index 2b1e33dd60..9c499fea7b 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -16,8 +16,7 @@ from saleor.discount.models import Voucher, NotApplicable
from saleor.shipping.models import ShippingMethodCountry
-def test_checkout_version():
- checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')
+def test_checkout_version(checkout):
storage = checkout.for_storage()
assert storage['version'] == Checkout.VERSION
@@ -32,30 +31,30 @@ 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(), None, 'tracking_code')
+ storage_data, Mock(), AnonymousUser(), None, None, 'tracking_code')
storage = checkout.for_storage()
assert storage == expected_storage
-def test_checkout_clear_storage():
- checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')
+def test_checkout_clear_storage(checkout):
checkout.storage['new'] = 1
checkout.clear_storage()
assert checkout.storage is None
assert checkout.modified is True
-def test_checkout_is_shipping_required():
+def test_checkout_is_shipping_required(checkout):
cart = Mock(is_shipping_required=Mock(return_value=True))
- checkout = Checkout(cart, AnonymousUser(), None, 'tracking_code')
+ checkout.cart = cart
assert checkout.is_shipping_required is True
@pytest.mark.parametrize('user, shipping', [
(Mock(default_shipping_address='user_shipping'), 'user_shipping'),
(AnonymousUser(), None)])
-def test_checkout_shipping_address_with_anonymous_user(user, shipping):
- checkout = Checkout(Mock(), user, None, 'tracking_code')
+def test_checkout_shipping_address_with_anonymous_user(
+ checkout, user, shipping):
+ checkout.user = user
assert checkout._shipping_address is None
assert checkout.shipping_address == shipping
assert checkout._shipping_address == shipping
@@ -65,17 +64,15 @@ def test_checkout_shipping_address_with_anonymous_user(user, shipping):
(Mock(get=Mock(return_value='shipping')), 'shipping'),
(Mock(get=Mock(side_effect=Address.DoesNotExist)), None)])
def test_checkout_shipping_address_with_storage(
- address_objects, shipping, monkeypatch):
+ checkout, address_objects, shipping, monkeypatch):
monkeypatch.setattr(
'saleor.checkout.core.Address.objects', address_objects)
- checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')
checkout.storage['shipping_address'] = {'id': 1}
assert checkout.shipping_address == shipping
-def test_checkout_shipping_address_setter():
+def test_checkout_shipping_address_setter(checkout):
address = Address(first_name='Jan', last_name='Kowalski')
- checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')
assert checkout._shipping_address is None
checkout.shipping_address = address
assert checkout._shipping_address == address
@@ -104,32 +101,29 @@ def test_checkout_shipping_address_setter():
(Mock(country=Mock(code='DE')), Mock(country_code='PL'), None),
(None, Mock(country_code='PL'), None)])
def test_checkout_shipping_method(
- shipping_address, shipping_method, value, monkeypatch):
+ checkout, shipping_address, shipping_method, value, monkeypatch):
queryset = Mock(get=Mock(return_value=shipping_method))
monkeypatch.setattr(Checkout, 'shipping_address', shipping_address)
monkeypatch.setattr(
'saleor.checkout.core.ShippingMethodCountry.objects', queryset)
- checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')
checkout.storage['shipping_method_country_id'] = 1
assert checkout._shipping_method is None
assert checkout.shipping_method == value
assert checkout._shipping_method == value
-def test_checkout_shipping_does_not_exists(monkeypatch):
+def test_checkout_shipping_does_not_exists(monkeypatch, checkout):
queryset = Mock(get=Mock(side_effect=ShippingMethodCountry.DoesNotExist))
monkeypatch.setattr(
'saleor.checkout.core.ShippingMethodCountry.objects', queryset)
- checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')
checkout.storage['shipping_method_country_id'] = 1
assert checkout.shipping_method is None
-def test_checkout_shipping_method_setter():
- shipping_method = Mock(id=1)
- checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')
+def test_checkout_shipping_method_setter(checkout):
assert checkout.modified is False
assert checkout._shipping_method is None
+ shipping_method = Mock(id=1)
checkout.shipping_method = shipping_method
assert checkout._shipping_method == shipping_method
assert checkout.modified is True
@@ -144,8 +138,8 @@ def test_checkout_shipping_method_setter():
addresses=Mock(
is_authenticated=Mock(return_value=True))),
'billing_address')])
-def test_checkout_billing_address(user, address):
- checkout = Checkout(Mock(), user, None, 'tracking_code')
+def test_checkout_billing_address(checkout, user, address):
+ checkout.user = user
assert checkout.billing_address == address
@@ -166,8 +160,8 @@ def test_checkout_billing_address(user, address):
__len__=Mock(return_value=0),
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(), None, 'tracking_code')
+def test_index_view(checkout, cart, status_code, url, rf, monkeypatch):
+ checkout.cart = cart
request = rf.get('checkout:index', follow=True)
request.user = checkout.user
request.session = {STORAGE_SESSION_KEY: checkout.for_storage()}
@@ -180,19 +174,22 @@ def test_index_view(cart, status_code, url, rf, monkeypatch):
assert response.url == url
-def test_checkout_discount(checkout_with_items, sale):
+def test_checkout_discount(checkout_with_items, sale, taxes):
+ checkout_with_items.discounts = (sale,)
+ checkout_with_items.taxes = taxes
assert checkout_with_items.get_total() == TaxedMoney(
- net=Money(5, 'USD'), gross=Money(5, 'USD'))
+ net=Money('4.07', 'USD'), gross=Money('5.00', 'USD'))
def test_checkout_create_order_insufficient_stock(
- request_cart, customer_user, product):
+ checkout, request_cart, customer_user, product):
product_type = product.product_type
product_type.is_shipping_required = False
product_type.save()
variant = product.variants.get()
request_cart.add(variant, quantity=10, check_quantity=False)
- checkout = Checkout(request_cart, customer_user, None, 'tracking_code')
+ checkout.cart = request_cart
+ checkout.user = customer_user
with pytest.raises(InsufficientStock):
checkout.create_order()
@@ -202,8 +199,7 @@ def test_checkout_create_order_insufficient_stock(
' ',
' test_note ',
'test_note'])
-def test_note_form(note_value):
- checkout = Checkout(Mock(), AnonymousUser(), None, 'tracking_code')
+def test_note_form(checkout, note_value):
form = NoteForm({'note': note_value}, checkout=checkout)
form.is_valid()
form.set_checkout_note()
diff --git a/tests/test_graphql.py b/tests/test_graphql.py
index b99e50420f..6e155eb885 100644
--- a/tests/test_graphql.py
+++ b/tests/test_graphql.py
@@ -177,14 +177,10 @@ def test_product_query(admin_client, product):
}
purchaseCost{
start{
- gross{
- amount
- }
+ amount
}
stop{
- gross{
- amount
- }
+ amount
}
}
grossMargin {
@@ -210,10 +206,10 @@ def test_product_query(admin_client, product):
assert float(gross['amount']) == float(product.price.amount)
from saleor.product.utils.costs import get_product_costs_data
purchase_cost, gross_margin = get_product_costs_data(product)
- assert purchase_cost.start.gross.amount == product_data[
- 'purchaseCost']['start']['gross']['amount']
- assert purchase_cost.stop.gross.amount == product_data[
- 'purchaseCost']['stop']['gross']['amount']
+ assert purchase_cost.start.amount == product_data[
+ 'purchaseCost']['start']['amount']
+ assert purchase_cost.stop.amount == product_data[
+ 'purchaseCost']['stop']['amount']
assert gross_margin[0] == product_data['grossMargin'][0]['start']
assert gross_margin[1] == product_data['grossMargin'][0]['stop']
diff --git a/tests/test_order.py b/tests/test_order.py
index 557eae9c7e..f275b66690 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -6,6 +6,7 @@ from payments import PaymentStatus
from prices import Money, TaxedMoney
from tests.utils import get_redirect_location
+from saleor.core.utils import DEFAULT_TAX_RATE_NAME
from saleor.order import FulfillmentStatus, OrderStatus, models
from saleor.order.forms import OrderNoteForm
from saleor.order.models import Order
@@ -48,7 +49,7 @@ def test_get_tax_rate_by_name_fallback_to_standard(taxes):
rate_name = 'unexisting tax rate'
tax_rate = get_tax_rate_by_name(rate_name, taxes)
- assert tax_rate == taxes[rate_name]['value']
+ assert tax_rate == taxes[DEFAULT_TAX_RATE_NAME]['value']
def test_get_tax_rate_by_name_empty_taxes(product):
diff --git a/tests/test_product.py b/tests/test_product.py
index 4a7d7bf510..e8c9cbc1bd 100644
--- a/tests/test_product.py
+++ b/tests/test_product.py
@@ -359,7 +359,7 @@ def test_product_filter_sorted_by_wrong_parameter(
def test_get_variant_picker_data_proper_variant_count(product):
data = get_variant_picker_data(
- product, discounts=None, local_currency=None)
+ product, discounts=None, taxes=None, local_currency=None)
assert len(data['variantAttributes'][0]['values']) == 1