Skip to content

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

Update codebase to use updated prices libraries for money handling

Rafał Pitoń555933d90d7a
diff --git a/docs/architecture.rst b/docs/architecture.rst
index f36539d914..26c3ba32b2 100644
--- a/docs/architecture.rst
+++ b/docs/architecture.rst
@@ -4,6 +4,7 @@ Architecture
.. toctree::
:maxdepth: 1
+ architecture/money
architecture/products
architecture/stock
architecture/orders
diff --git a/docs/architecture/money.rst b/docs/architecture/money.rst
new file mode 100644
index 0000000000..c857ba78ae
--- /dev/null
+++ b/docs/architecture/money.rst
@@ -0,0 +1,33 @@
+Handling Money Amounts
+======================
+
+Saleor uses the `Prices <https://github.com/mirumee/prices/>`_ and `django-prices <https://github.com/mirumee/django-prices/>`_ libraries to store, calculate and display amounts of money, prices and ranges of those.
+
+Default currency
+----------------
+
+All prices are entered and stored in a single default currency controlled by the [DEFAULT_CURRENCY setting]. Saleor can display prices in a user's local currency (see [Open Exchange Rates integration]) but all purchases are charged in the default currency.
+
+.. warning::
+
+ The currency is not stored in the database. Changing the default currency in a production environment will not recalculate any existing orders. All numbers will remain the same and will be incorrectly displayed as the new currency.
+
+Money and TaxedMoney
+--------------------
+
+In Saleor's codebase, money amounts exist either as `Money` or `TaxedMoney` instances.
+
+`Money` is a type representing amount of money in specific currency: 100 USD is represented by `Money(100, currency='USD')`. This type doesn't hold any additional information useful for commerce but, unlike `Decimal`, it implements safeguards and checks for calculations and comparisions of monetary values. Money amounts are stored on model using `MoneyField` that provides its own safechecks on currency and precision of stored amount. If you ever need to get to the `Decimal` of your `Money` object, you'll find it on the `amount` property.
+
+Products and shipping methods prices are stored using `MoneyField` and are assumed to be gross amounts. Those amounts are then naively converted to `TaxedMoney` objects using the `TaxedAmount(net=item.price, gross=item.price)` approach with conversion happening before resolving item's final price (before taxes and discounts).
+
+.. note::
+
+ In future Saleor will support setting for store administrators to change this approach to use net values instead if this fits their business more.
+
+TaxedMoneyRange
+---------------
+
+Sometimes a product may be available under more than single price due to it's variants defining custom prices different from base brice. For such situations `Product` defines additional `get_price_range` and `get_gross_price_range` methods that return `TaxedMoneyRange` object defining minim and maximum prices on its `start` and `stop` attributes. This object is then used by the UI to differentatie between displaying price as "10 USD" or "from 10 USD" in case of products where prices differ between variants.
+
+TaxedMoneyRange is also used in for displaying other money ranges, like min and maximum cost and margin on product's variant in dashboard.
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
index aa3381308e..b548f756ed 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -37,8 +37,8 @@ django-js-asset==1.0.0 # via django-mptt
django-mptt==0.9.0
django-payments==0.12.1
django-phonenumber-field==2.0.0
-django-prices-openexchangerates==0.1.15
-django-prices==0.7.1
+django-prices-openexchangerates==1.0.0-beta3
+django-prices==1.0.0-beta6
django-redis==4.8.0
django-render-block==0.5 # via django-templated-email
django-storages==1.6.5
@@ -72,7 +72,7 @@ pdfrw==0.4 # via weasyprint
phonenumberslite==8.8.11
pillow==5.0.0 # via cairosvg, django-versatileimagefield
pluggy==0.6.0 # via pytest
-prices==0.5.9
+prices==1.0.0-beta3
promise==2.1 # via graphene, graphene-django, graphql-core, graphql-relay
psycopg2==2.7.4
purl==1.3.1
diff --git a/saleor/cart/migrations/0001_initial.py b/saleor/cart/migrations/0001_initial.py
index 252acd1865..74513ad4f6 100644
--- a/saleor/cart/migrations/0001_initial.py
+++ b/saleor/cart/migrations/0001_initial.py
@@ -1,12 +1,13 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
+import uuid
+
from django.db import models, migrations
import django.db.models.deletion
from django.conf import settings
import django.core.validators
import django_prices.models
-import uuid
class Migration(migrations.Migration):
@@ -27,7 +28,7 @@ class Migration(migrations.Migration):
('email', models.EmailField(max_length=254, null=True, blank=True)),
('token', models.UUIDField(primary_key=True, default=uuid.uuid4, serialize=False, editable=False, verbose_name='token')),
('checkout_data', models.TextField(null=True, editable=False)),
- ('total', django_prices.models.PriceField(default=0, currency='USD', max_digits=12, decimal_places=2)),
+ ('total', django_prices.models.MoneyField(default=0, currency='USD', max_digits=12, decimal_places=2)),
('quantity', models.PositiveIntegerField(default=0)),
('user', models.ForeignKey(related_name='carts', verbose_name='user', blank=True, to=settings.AUTH_USER_MODEL, null=True, on_delete=django.db.models.deletion.CASCADE)),
('voucher', models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, to='discount.Voucher', null=True)),
diff --git a/saleor/cart/migrations/0002_auto_20170206_0407.py b/saleor/cart/migrations/0002_auto_20170206_0407.py
index b9d67bfc90..48e1f9f780 100644
--- a/saleor/cart/migrations/0002_auto_20170206_0407.py
+++ b/saleor/cart/migrations/0002_auto_20170206_0407.py
@@ -41,7 +41,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='cart',
name='total',
- field=django_prices.models.PriceField(currency='USD', decimal_places=2, default=0, max_digits=12, verbose_name='total'),
+ field=django_prices.models.MoneyField(currency='USD', decimal_places=2, default=0, max_digits=12, verbose_name='total'),
),
migrations.AlterField(
model_name='cart',
diff --git a/saleor/cart/migrations/0005_auto_20180108_0814.py b/saleor/cart/migrations/0005_auto_20180108_0814.py
index c91ce4aad3..548d4afd31 100644
--- a/saleor/cart/migrations/0005_auto_20180108_0814.py
+++ b/saleor/cart/migrations/0005_auto_20180108_0814.py
@@ -2,13 +2,14 @@
# Generated by Django 1.11.5 on 2018-01-08 14:14
from __future__ import unicode_literals
+import uuid
+
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django_prices.models
import jsonfield.fields
-import uuid
class Migration(migrations.Migration):
@@ -56,7 +57,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='cart',
name='total',
- field=django_prices.models.PriceField(currency='USD', decimal_places=2, default=0, max_digits=12),
+ field=django_prices.models.MoneyField(currency='USD', decimal_places=2, default=0, max_digits=12),
),
migrations.AlterField(
model_name='cart',
diff --git a/saleor/cart/models.py b/saleor/cart/models.py
index f04dcd79ea..29204c5b9a 100644
--- a/saleor/cart/models.py
+++ b/saleor/cart/models.py
@@ -9,9 +9,9 @@ from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.utils.encoding import smart_str
from django.utils.timezone import now
-from django_prices.models import PriceField
+from django_prices.models import MoneyField
from jsonfield import JSONField
-from prices import Price
+from prices import sum as sum_prices
from . import CartStatus, logger
@@ -41,7 +41,7 @@ class ProductGroup(list):
if not subtotals:
raise AttributeError(
'Calling get_total() on an empty product group')
- return sum(subtotals[1:], subtotals[0])
+ return sum_prices(subtotals)
class CartQueryset(models.QuerySet):
@@ -89,7 +89,7 @@ class Cart(models.Model):
'discount.Voucher', null=True, related_name='+',
on_delete=models.SET_NULL)
checkout_data = JSONField(null=True, editable=False)
- total = PriceField(
+ total = MoneyField(
currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,
default=0)
quantity = models.PositiveIntegerField(default=0)
@@ -147,8 +147,7 @@ class Cart(models.Model):
subtotals = [line.get_total(discounts) for line in self.lines.all()]
if not subtotals:
raise AttributeError('Calling get_total() on an empty cart')
- zero = Price(0, currency=settings.DEFAULT_CURRENCY)
- return sum(subtotals, zero)
+ return sum_prices(subtotals)
def count(self):
"""Return the total quantity in cart."""
diff --git a/saleor/cart/utils.py b/saleor/cart/utils.py
index 00db83dea1..6417bc84a1 100644
--- a/saleor/cart/utils.py
+++ b/saleor/cart/utils.py
@@ -7,7 +7,7 @@ from django.contrib import messages
from django.db import transaction
from django.utils.timezone import now
from django.utils.translation import pgettext_lazy
-from prices import PriceRange
+from prices import TaxedMoneyRange
from . import CartStatus
from ..core.exceptions import InsufficientStock
@@ -220,7 +220,8 @@ def get_cart_data(cart, shipping_range, currency, discounts):
cart_total = cart.get_total(discounts=discounts)
local_cart_total = to_local_currency(cart_total, currency)
shipping_required = cart.is_shipping_required()
- total_with_shipping = PriceRange(cart_total)
+ total_with_shipping = TaxedMoneyRange(
+ start=cart_total, stop=cart_total)
if shipping_required and shipping_range:
total_with_shipping = shipping_range + cart_total
local_total_with_shipping = to_local_currency(
diff --git a/saleor/cart/views.py b/saleor/cart/views.py
index 5030002562..3cdb6a6fde 100644
--- a/saleor/cart/views.py
+++ b/saleor/cart/views.py
@@ -3,9 +3,9 @@ from django.http import JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.template.response import TemplateResponse
from django.urls import reverse
-from django_babel.templatetags.babel import currencyfmt
-from ..core.utils import get_user_shipping_country, to_local_currency
+from ..core.utils import (
+ format_money, get_user_shipping_country, to_local_currency)
from ..product.models import ProductVariant
from ..shipping.utils import get_shipment_options
from .forms import CountryForm, ReplaceCartLineForm
@@ -92,17 +92,14 @@ def update(request, cart, variant_id):
'numLines': len(cart)}}
updated_line = cart.get_line(form.cart_line.variant)
if updated_line:
- response['subtotal'] = currencyfmt(
- updated_line.get_total(discounts=discounts).gross,
- updated_line.get_total(discounts=discounts).currency)
+ response['subtotal'] = format_money(
+ updated_line.get_total(discounts=discounts).gross)
if cart:
cart_total = cart.get_total(discounts=discounts)
- response['total'] = currencyfmt(
- cart_total.gross, cart_total.currency)
+ response['total'] = format_money(cart_total.gross)
local_cart_total = to_local_currency(cart_total, request.currency)
- if local_cart_total:
- response['localTotal'] = currencyfmt(
- local_cart_total.gross, local_cart_total.currency)
+ if local_cart_total is not None:
+ response['localTotal'] = format_money(local_cart_total.gross)
status = 200
elif request.POST is not None:
response = {'error': form.errors}
@@ -125,9 +122,8 @@ def summary(request, cart):
'quantity': line.quantity,
'attributes': line.variant.display_variant_attributes(attributes),
'image': first_image,
- 'price_per_item': currencyfmt(
- price_per_item.gross, price_per_item.currency),
- 'line_total': currencyfmt(line_total.gross, line_total.currency),
+ 'price_per_item': format_money(price_per_item.gross),
+ 'line_total': format_money(line_total.gross),
'update_url': reverse(
'cart:update-line', kwargs={'variant_id': line.variant_id}),
'variant_url': line.variant.get_absolute_url()}
@@ -137,7 +133,7 @@ def summary(request, cart):
cart_total = cart.get_total(discounts=request.discounts)
data = {
'quantity': cart.quantity,
- 'total': currencyfmt(cart_total.gross, cart_total.currency),
+ 'total': format_money(cart_total.gross),
'lines': [prepare_line_data(line) for line in cart.lines.all()]}
return render(request, 'cart_dropdown.html', data)
diff --git a/saleor/checkout/core.py b/saleor/checkout/core.py
index c55e009194..b28952c76d 100644
--- a/saleor/checkout/core.py
+++ b/saleor/checkout/core.py
@@ -7,13 +7,14 @@ 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 FixedDiscount, Price
+from prices import Money, TaxedMoney
from ..account.models import Address
from ..account.utils import store_user_address
from ..cart.models import Cart
from ..cart.utils import get_or_empty_db_cart
from ..core import analytics
+from ..core.utils import ZERO_TAXED_MONEY
from ..discount.models import NotApplicable, Voucher
from ..discount.utils import (
increase_voucher_usage, get_voucher_discount_for_checkout)
@@ -106,9 +107,9 @@ class Checkout:
"""
for partition in self.cart.partition():
if self.shipping_method and partition.is_shipping_required():
- shipping_cost = self.shipping_method.get_total()
+ shipping_cost = self.shipping_method.get_total_price()
else:
- shipping_cost = Price(0, currency=settings.DEFAULT_CURRENCY)
+ shipping_cost = ZERO_TAXED_MONEY
total_with_shipping = partition.get_total(
discounts=self.cart.discounts) + shipping_cost
@@ -214,18 +215,14 @@ class Checkout:
"""Return a discount if any."""
value = self.storage.get('discount_value')
currency = self.storage.get('discount_currency')
- name = self.storage.get('discount_name')
- if value is not None and name is not None and currency is not None:
- amount = Price(value, currency=currency)
- return FixedDiscount(amount, name)
+ if value is not None and currency is not None:
+ return Money(value, currency=currency)
return None
@discount.setter
def discount(self, discount):
- amount = discount.amount
- self.storage['discount_value'] = smart_text(amount.net)
- self.storage['discount_currency'] = amount.currency
- self.storage['discount_name'] = discount.name
+ self.storage['discount_value'] = smart_text(discount.amount)
+ self.storage['discount_currency'] = discount.currency
self.modified = True
@discount.deleter
@@ -236,6 +233,19 @@ class Checkout:
if 'discount_currency' in self.storage:
del self.storage['discount_currency']
self.modified = True
+
+ @property
+ def discount_name(self):
+ """Return a discount name if any."""
+ return self.storage.get('discount_name')
+
+ @discount_name.setter
+ def discount_name(self, discount_name):
+ self.storage['discount_name'] = discount_name
+ self.modified = True
+
+ @discount_name.deleter
+ def discount_name(self):
if 'discount_name' in self.storage:
del self.storage['discount_name']
self.modified = True
@@ -305,9 +315,13 @@ class Checkout:
self._add_to_user_address_book(
self.billing_address, is_billing=True)
- shipping_price = (
- self.shipping_method.get_total() if self.shipping_method
- else Price(0, currency=settings.DEFAULT_CURRENCY))
+ if self.shipping_method:
+ shipping_price = self.shipping_method.get_total_price()
+ else:
+ shipping_price = TaxedMoney(
+ net=Money(0, currency=settings.DEFAULT_CURRENCY),
+ gross=Money(0, currency=settings.DEFAULT_CURRENCY))
+
order_data = {
'language_code': get_language(),
'billing_address': billing_address,
@@ -323,10 +337,9 @@ class Checkout:
order_data['user_email'] = self.email
if voucher is not None:
- discount = self.discount
order_data['voucher'] = voucher
- order_data['discount_amount'] = discount.amount
- order_data['discount_name'] = discount.name
+ order_data['discount_amount'] = self.discount
+ order_data['discount_name'] = self.discount_name
order = Order.objects.create(**order_data)
@@ -370,30 +383,33 @@ class Checkout:
try:
self.discount = get_voucher_discount_for_checkout(
voucher, self)
+ self.discount_name = voucher.name
except NotApplicable:
del self.discount
+ del self.discount_name
del self.voucher_code
else:
del self.discount
+ del self.discount_name
del self.voucher_code
def get_subtotal(self):
- """Calculate order total without shipping."""
- zero = Price(0, currency=settings.DEFAULT_CURRENCY)
+ """Calculate order total without shipping and discount."""
cost_iterator = (
total - shipping_cost
for shipment, shipping_cost, total in self.deliveries)
- total = sum(cost_iterator, zero)
+ total = sum(cost_iterator, ZERO_TAXED_MONEY)
return total
def get_total(self):
- """Calculate order total with shipping."""
- zero = Price(0, currency=settings.DEFAULT_CURRENCY)
+ """Calculate order total with shipping and discount amount."""
cost_iterator = (
total
for shipment, shipping_cost, total in self.deliveries)
- total = sum(cost_iterator, zero)
- return total if self.discount is None else self.discount.apply(total)
+ total = sum(cost_iterator, ZERO_TAXED_MONEY)
+ if self.discount:
+ return total - self.discount
+ return total
def load_checkout(view):
diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.py
index a98e4e7d22..d766de318c 100644
--- a/saleor/checkout/forms.py
+++ b/saleor/checkout/forms.py
@@ -2,8 +2,8 @@
from django import forms
from django.utils.safestring import mark_safe
from django.utils.translation import pgettext_lazy
-from django_prices.templatetags.prices_i18n import format_price
+from ..core.utils import format_money
from ..shipping.models import ShippingMethodCountry
@@ -68,7 +68,7 @@ class ShippingCountryChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
"""Return a friendly label for the shipping method."""
- price_html = format_price(obj.price.gross, obj.price.currency)
+ price_html = format_money(obj.price)
label = mark_safe('%s %s' % (obj.shipping_method, price_html))
return label
diff --git a/saleor/checkout/views/discount.py b/saleor/checkout/views/discount.py
index 508d7bdcec..1f06b0dcc1 100644
--- a/saleor/checkout/views/discount.py
+++ b/saleor/checkout/views/discount.py
@@ -28,6 +28,7 @@ def add_voucher_form(view):
return redirect(next_url)
else:
del checkout.discount
+ del checkout.discount_name
del checkout.voucher_code
# if only discount form was used we clear post for other forms
request.POST = {}
@@ -72,5 +73,6 @@ def remove_voucher_view(request, checkout, cart):
"""Clear the discount and remove the voucher."""
next_url = request.GET.get('next', request.META['HTTP_REFERER'])
del checkout.discount
+ del checkout.discount_name
del checkout.voucher_code
return redirect(next_url)
diff --git a/saleor/core/templatetags/materializecss.py b/saleor/core/templatetags/materializecss.py
index ceabb143da..13fe40f9f8 100644
--- a/saleor/core/templatetags/materializecss.py
+++ b/saleor/core/templatetags/materializecss.py
@@ -2,7 +2,7 @@ from django import forms, template
from django.template.loader import get_template
from django_filters.widgets import RangeWidget
-from ...dashboard.widgets import DateRangeWidget, PriceRangeWidget
+from ...dashboard.widgets import DateRangeWidget, MoneyRangeWidget
register = template.Library()
@@ -98,4 +98,4 @@ def is_date_range(field):
@register.filter
def is_price_range(field):
- return isinstance(field.field.widget, PriceRangeWidget)
+ return isinstance(field.field.widget, MoneyRangeWidget)
diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.py
index 330a346f37..5f3479719b 100644
--- a/saleor/core/utils/__init__.py
+++ b/saleor/core/utils/__init__.py
@@ -9,14 +9,19 @@ from django.contrib.sites.models import Site
from django.core.paginator import InvalidPage, Paginator
from django.http import Http404
from django.utils.encoding import iri_to_uri, smart_text
+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 geolite2 import geolite2
-from prices import PriceRange
+from prices import Money, TaxedMoney, MoneyRange
from ...account.models import User
+ZERO_TAXED_MONEY = TaxedMoney(
+ net=Money(0, currency=settings.DEFAULT_CURRENCY),
+ gross=Money(0, currency=settings.DEFAULT_CURRENCY))
+
georeader = geolite2.reader()
@@ -87,11 +92,15 @@ def get_paginator_items(items, paginate_by, page_number):
return items
+def format_money(money):
+ return currencyfmt(money.amount, money.currency)
+
+
def to_local_currency(price, currency):
if not settings.OPENEXCHANGERATES_API_KEY:
return None
- if isinstance(price, PriceRange):
- from_currency = price.min_price.currency
+ if isinstance(price, MoneyRange):
+ from_currency = price.start.currency
else:
from_currency = price.currency
if currency != from_currency:
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 01ce15d4a9..ffc459be58 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -11,7 +11,7 @@ from django.template.defaultfilters import slugify
from faker import Factory
from faker.providers import BaseProvider
from payments import PaymentStatus
-from prices import Price
+from prices import Money, TaxedMoney
from ...discount import DiscountValueType, VoucherType
from ...discount.models import Sale, Voucher
@@ -176,7 +176,7 @@ def get_price_override(schema, combinations_num, current_price):
prices = []
if schema.get('different_variant_prices'):
prices = sorted(
- [current_price + fake.price() for _ in range(combinations_num)],
+ [current_price + fake.money() for _ in range(combinations_num)],
reverse=True)
return prices
@@ -228,9 +228,10 @@ def create_products_by_schema(placeholder_dir, how_many, create_images,
class SaleorProvider(BaseProvider):
- def price(self):
- return Price(fake.pydecimal(2, 2, positive=True),
- currency=settings.DEFAULT_CURRENCY)
+ def money(self):
+ return Money(
+ fake.pydecimal(2, 2, positive=True),
+ currency=settings.DEFAULT_CURRENCY)
def delivery_region(self):
return random.choice(DELIVERY_REGIONS)
@@ -270,7 +271,7 @@ def get_or_create_collection(name, **kwargs):
def create_product(**kwargs):
defaults = {
'name': fake.company(),
- 'price': fake.price(),
+ 'price': fake.money(),
'description': '\n\n'.join(fake.paragraphs(5))}
defaults.update(kwargs)
return Product.objects.create(**defaults)
@@ -370,8 +371,8 @@ def create_payment(delivery_group):
variant='default',
transaction_id=str(fake.random_int(1, 100000)),
currency=settings.DEFAULT_CURRENCY,
- total=order.total.gross,
- delivery=order.shipping_price.gross,
+ total=order.total.gross.amount,
+ delivery=order.shipping_price.gross.amount,
customer_ip_address=fake.ipv4(),
billing_first_name=order.billing_address.first_name,
billing_last_name=order.billing_address.last_name,
@@ -391,7 +392,7 @@ def create_delivery_group(order):
region = ANY_COUNTRY
shipping_method = fake.shipping_method()
shipping_country = shipping_method.price_per_country.get_or_create(
- country_code=region, defaults={'price': fake.price()})[0]
+ country_code=region, defaults={'price': fake.money()})[0]
delivery_group = DeliveryGroup.objects.create(
status=random.choice([GroupStatus.NEW, GroupStatus.SHIPPED]),
order=order,
@@ -416,8 +417,7 @@ def create_order_line(delivery_group):
quantity=quantity,
stock=stock,
stock_location=stock.location.name,
- unit_price_net=product.price.net,
- unit_price_gross=product.price.gross)
+ unit_price=TaxedMoney(net=product.price, gross=product.price))
def create_order_lines(delivery_group, how_many=10):
@@ -483,10 +483,10 @@ def create_product_sales(how_many=5):
def create_shipping_methods():
shipping_method = ShippingMethod.objects.create(name='UPC')
- shipping_method.price_per_country.create(price=fake.price())
+ shipping_method.price_per_country.create(price=fake.money())
yield 'Shipping method #%d' % shipping_method.id
shipping_method = ShippingMethod.objects.create(name='DHL')
- shipping_method.price_per_country.create(price=fake.price())
+ shipping_method.price_per_country.create(price=fake.money())
yield 'Shipping method #%d' % shipping_method.id
diff --git a/saleor/dashboard/discount/forms.py b/saleor/dashboard/discount/forms.py
index 6464a11a4a..a39530bad8 100644
--- a/saleor/dashboard/discount/forms.py
+++ b/saleor/dashboard/discount/forms.py
@@ -4,7 +4,8 @@ from django import forms
from django.conf import settings
from django.urls import reverse_lazy
from django.utils.translation import pgettext_lazy
-from django_prices.forms import PriceField
+from django_prices.forms import MoneyField
+from prices import Money
from ...discount import DiscountValueType, VoucherApplyToProduct
from ...discount.models import Sale, Voucher
@@ -106,8 +107,9 @@ def country_choices():
class ShippingVoucherForm(forms.ModelForm):
- limit = PriceField(
- min_value=0, required=False, currency=settings.DEFAULT_CURRENCY)
+ limit = MoneyField(
+ min_value=Money(0, currency=settings.DEFAULT_CURRENCY),
+ required=False, currency=settings.DEFAULT_CURRENCY)
apply_to = forms.ChoiceField(
choices=country_choices,
required=False)
@@ -131,8 +133,9 @@ class ShippingVoucherForm(forms.ModelForm):
class ValueVoucherForm(forms.ModelForm):
- limit = PriceField(
- min_value=0, required=False, currency=settings.DEFAULT_CURRENCY)
+ limit = MoneyField(
+ min_value=Money(0, currency=settings.DEFAULT_CURRENCY),
+ required=False, currency=settings.DEFAULT_CURRENCY)
class Meta:
model = Voucher
diff --git a/saleor/dashboard/order/filters.py b/saleor/dashboard/order/filters.py
index 5ede5171c5..14ab6d39a7 100644
--- a/saleor/dashboard/order/filters.py
+++ b/saleor/dashboard/order/filters.py
@@ -9,7 +9,7 @@ from payments import PaymentStatus
from ...core.filters import SortedFilterSet
from ...order import OrderStatus
from ...order.models import Order
-from ..widgets import DateRangeWidget, PriceRangeWidget
+from ..widgets import DateRangeWidget, MoneyRangeWidget
SORT_BY_FIELDS = [
('pk', 'pk'),
@@ -50,7 +50,7 @@ class OrderFilter(SortedFilterSet):
widget=forms.Select)
total_net = RangeFilter(
label=pgettext_lazy('Order list filter label', 'Total'),
- widget=PriceRangeWidget)
+ widget=MoneyRangeWidget)
sort_by = OrderingFilter(
label=pgettext_lazy('Order list filter label', 'Sort by'),
fields=SORT_BY_FIELDS,
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 0aa20192b3..5ad1b75480 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -3,7 +3,7 @@ from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
from django.urls import reverse_lazy
from django.utils.translation import npgettext_lazy, pgettext_lazy
-from django_prices.forms import PriceField
+from django_prices.forms import MoneyField
from payments import PaymentError, PaymentStatus
from ...account.i18n import (
@@ -42,7 +42,7 @@ class OrderNoteForm(forms.ModelForm):
class ManagePaymentForm(forms.Form):
- amount = PriceField(
+ amount = MoneyField(
label=pgettext_lazy(
'Payment management form (capture, refund, release)', 'Amount'),
max_digits=12,
@@ -60,13 +60,12 @@ class ManagePaymentForm(forms.Form):
def payment_error(self, message):
self.add_error(
None, pgettext_lazy(
- 'Payment form error',
- 'Payment gateway error: %s') % message)
+ 'Payment form error', 'Payment gateway error: %s') % message)
def try_payment_action(self, action):
- amount = self.cleaned_data['amount']
+ money = self.cleaned_data['amount']
try:
- action(amount.gross)
+ action(money.amount)
except (PaymentError, ValueError) as e:
self.payment_error(str(e))
return False
diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.py
index ebb4db7141..9980229023 100644
--- a/saleor/dashboard/order/views.py
+++ b/saleor/dashboard/order/views.py
@@ -7,12 +7,12 @@ from django.shortcuts import get_object_or_404, redirect
from django.template.context_processors import csrf
from django.template.response import TemplateResponse
from django.utils.translation import pgettext_lazy
-from django_prices.templatetags.prices_i18n import gross
+from django_prices.templatetags import prices_i18n
from payments import PaymentStatus
-from prices import Price
+from prices import Money, TaxedMoney
from ...core.exceptions import InsufficientStock
-from ...core.utils import get_paginator_items
+from ...core.utils import ZERO_TAXED_MONEY, get_paginator_items
from ...order import GroupStatus
from ...order.models import DeliveryGroup, Order, OrderLine, OrderNote
from ...product.models import StockLocation
@@ -53,7 +53,7 @@ def order_details(request, order_pk):
all_payments = order.payments.exclude(status=PaymentStatus.INPUT)
payment = order.payments.last()
groups = list(order)
- captured = preauthorized = Price(0, currency=order.total.currency)
+ captured = preauthorized = ZERO_TAXED_MONEY
balance = captured - order.total
if payment:
can_capture = (
@@ -69,7 +69,6 @@ def order_details(request, order_pk):
balance = captured - order.total
else:
can_capture = can_release = can_refund = False
-
is_many_stock_locations = StockLocation.objects.count() > 1
ctx = {'order': order, 'all_payments': all_payments, 'payment': payment,
'notes': notes, 'groups': groups, 'captured': captured,
@@ -116,7 +115,7 @@ def capture_payment(request, order_pk, payment_pk):
amount = form.cleaned_data['amount']
msg = pgettext_lazy(
'Dashboard message related to a payment',
- 'Captured %(amount)s') % {'amount': gross(amount)}
+ 'Captured %(amount)s') % {'amount': prices_i18n.amount(amount)}
order.history.create(content=msg, user=request.user)
messages.success(request, msg)
return redirect('dashboard:order-details', order_pk=order.pk)
@@ -139,7 +138,7 @@ def refund_payment(request, order_pk, payment_pk):
amount = form.cleaned_data['amount']
msg = pgettext_lazy(
'Dashboard message related to a payment',
- 'Refunded %(amount)s') % {'amount': gross(amount)}
+ 'Refunded %(amount)s') % {'amount': prices_i18n.amount(amount)}
order.history.create(content=msg, user=request.user)
messages.success(request, msg)
return redirect('dashboard:order-details', order_pk=order.pk)
diff --git a/saleor/dashboard/product/filters.py b/saleor/dashboard/product/filters.py
index 8fe827a44b..92a8845ac1 100644
--- a/saleor/dashboard/product/filters.py
+++ b/saleor/dashboard/product/filters.py
@@ -7,7 +7,7 @@ from django_filters import (
from ...core.filters import SortedFilterSet
from ...product.models import (
Category, Product, ProductAttribute, ProductType, StockLocation)
-from ..widgets import PriceRangeWidget
+from ..widgets import MoneyRangeWidget
PRODUCT_SORT_BY_FIELDS = {
'name': pgettext_lazy('Product list sorting option', 'name'),
@@ -46,7 +46,7 @@ class ProductFilter(SortedFilterSet):
price = RangeFilter(
label=pgettext_lazy('Product list filter label', 'Price'),
name='price',
- widget=PriceRangeWidget)
+ widget=MoneyRangeWidget)
is_published = ChoiceFilter(
label=pgettext_lazy('Product list filter label', 'Is published'),
choices=PUBLISHED_CHOICES,
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.py
index d2018adddb..1e35d91f15 100644
--- a/saleor/dashboard/product/forms.py
+++ b/saleor/dashboard/product/forms.py
@@ -205,7 +205,7 @@ class ProductVariantForm(forms.ModelForm):
super().__init__(*args, **kwargs)
if self.instance.product.pk:
self.fields['price_override'].widget.attrs[
- 'placeholder'] = self.instance.product.price.gross
+ 'placeholder'] = self.instance.product.price.amount
class CachingModelChoiceIterator(ModelChoiceIterator):
diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.py
index e6a6355033..1ba490f3a6 100644
--- a/saleor/dashboard/product/views.py
+++ b/saleor/dashboard/product/views.py
@@ -7,7 +7,7 @@ from django.shortcuts import get_object_or_404, redirect, reverse
from django.template.response import TemplateResponse
from django.utils.translation import npgettext_lazy, pgettext_lazy
from django.views.decorators.http import require_POST
-from django_prices.templatetags.prices_i18n import gross
+from django_prices.templatetags import prices_i18n
from . import forms
from ...core.utils import get_paginator_items
@@ -475,10 +475,17 @@ def variant_details(request, product_pk, variant_pk):
stock = variant.stock.all()
images = variant.images.all()
costs_data = get_variant_costs_data(variant)
+ if costs_data['costs']:
+ costs = {
+ 'min': costs_data['costs'][0],
+ 'max': costs_data['costs'][-1]}
+ else:
+ costs = {}
+
ctx = {
'images': images, 'product': product, 'stock': stock,
- 'variant': variant, 'costs': costs_data['costs'],
- 'margins': costs_data['margins'], 'is_empty': not stock.exists()}
+ 'variant': variant, 'costs': costs, 'margins': costs_data['margins'],
+ 'is_empty': not stock.exists()}
return TemplateResponse(
request,
'dashboard/product/product_variant/detail.html',
@@ -786,7 +793,7 @@ def ajax_available_variants_list(request):
def get_variant_label(variant, discounts):
return '%s, %s, %s' % (
variant.sku, variant.display_product(),
- gross(variant.get_price_per_item(discounts)))
+ prices_i18n.amount(variant.get_price_per_item(discounts).gross))
available_products = Product.objects.available_products()
queryset = ProductVariant.objects.filter(
diff --git a/saleor/dashboard/widgets.py b/saleor/dashboard/widgets.py
index 58336c94af..80e00d3407 100644
--- a/saleor/dashboard/widgets.py
+++ b/saleor/dashboard/widgets.py
@@ -2,7 +2,7 @@ from django import forms
from django.conf import settings
from django.forms import Textarea
from django_filters.widgets import RangeWidget
-from django_prices.widgets import PriceInput
+from django_prices.widgets import MoneyInput
from ..account.widgets import (
PhonePrefixWidget as StorefrontPhonePrefixWidget)
@@ -15,10 +15,10 @@ class DateRangeWidget(RangeWidget):
super(RangeWidget, self).__init__(widgets, attrs)
-class PriceRangeWidget(RangeWidget):
+class MoneyRangeWidget(RangeWidget):
def __init__(self, attrs=None):
self.currency = getattr(settings, 'DEFAULT_CURRENCY')
- widgets = (PriceInput(self.currency), PriceInput(self.currency))
+ widgets = (MoneyInput(self.currency), MoneyInput(self.currency))
# pylint: disable=bad-super-call
super(RangeWidget, self).__init__(widgets, attrs)
diff --git a/saleor/data_feeds/google_merchant.py b/saleor/data_feeds/google_merchant.py
index e5687c93d4..f983f7f652 100644
--- a/saleor/data_feeds/google_merchant.py
+++ b/saleor/data_feeds/google_merchant.py
@@ -147,12 +147,12 @@ def item_google_product_category(item, category_paths):
def item_price(item):
price = item.get_price_per_item(discounts=None)
- return '%s %s' % (price.gross, price.currency)
+ return '%s %s' % (price.gross.amount, price.currency)
def item_sale_price(item, discounts):
sale_price = item.get_price_per_item(discounts=discounts)
- return '%s %s' % (sale_price.gross, sale_price.currency)
+ return '%s %s' % (sale_price.gross.amount, sale_price.currency)
def item_attributes(item, categories, category_paths, current_site,
diff --git a/saleor/discount/forms.py b/saleor/discount/forms.py
index 81c5b8bd84..1dc2a2b8a3 100644
--- a/saleor/discount/forms.py
+++ b/saleor/discount/forms.py
@@ -45,12 +45,15 @@ class CheckoutDiscountForm(forms.Form):
discount = get_voucher_discount_for_checkout(
voucher, self.checkout)
cleaned_data['discount'] = discount
+ cleaned_data['discount_name'] = voucher.name
except NotApplicable as e:
self.add_error('voucher', smart_text(e))
return cleaned_data
def apply_discount(self):
discount = self.cleaned_data['discount']
+ discount_name = self.cleaned_data['discount_name']
voucher = self.cleaned_data['voucher']
self.checkout.discount = discount
+ self.checkout.discount_name = discount_name
self.checkout.voucher_code = voucher.code
diff --git a/saleor/discount/migrations/0002_voucher.py b/saleor/discount/migrations/0002_voucher.py
index 4c599e2828..77c0bdb492 100644
--- a/saleor/discount/migrations/0002_voucher.py
+++ b/saleor/discount/migrations/0002_voucher.py
@@ -30,7 +30,7 @@ class Migration(migrations.Migration):
('discount_value_type', models.CharField(choices=[('fixed', 'USD'), ('percentage', '%')], default='fixed', max_length=10)),
('discount_value', models.DecimalField(decimal_places=2, max_digits=12)),
('apply_to', models.CharField(blank=True, max_length=20, null=True)),
- ('limit', django_prices.models.PriceField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True)),
+ ('limit', django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True)),
('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='product.Category')),
('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='product.Product')),
],
diff --git a/saleor/discount/migrations/0004_auto_20170206_0407.py b/saleor/discount/migrations/0004_auto_20170206_0407.py
index 43ef544345..04cd2f0ee7 100644
--- a/saleor/discount/migrations/0004_auto_20170206_0407.py
+++ b/saleor/discount/migrations/0004_auto_20170206_0407.py
@@ -60,7 +60,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='voucher',
name='limit',
- field=django_prices.models.PriceField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True, verbose_name='limit'),
+ field=django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True, verbose_name='limit'),
),
migrations.AlterField(
model_name='voucher',
diff --git a/saleor/discount/migrations/0007_auto_20180108_0814.py b/saleor/discount/migrations/0007_auto_20180108_0814.py
index c50e67e6fd..890a781c5b 100644
--- a/saleor/discount/migrations/0007_auto_20180108_0814.py
+++ b/saleor/discount/migrations/0007_auto_20180108_0814.py
@@ -73,7 +73,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='voucher',
name='limit',
- field=django_prices.models.PriceField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
+ field=django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
),
migrations.AlterField(
model_name='voucher',
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 2e117026a3..5f5bf5d1c3 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -1,5 +1,6 @@
from datetime import date
from decimal import Decimal
+from functools import partial
from django.conf import settings
from django.db import models
@@ -7,9 +8,9 @@ from django.db.models import F, Q
from django.utils.encoding import smart_text
from django.utils.translation import pgettext, pgettext_lazy
from django_countries import countries
-from django_prices.models import PriceField
-from django_prices.templatetags.prices_i18n import net
-from prices import FixedDiscount, Price, percentage_discount
+from django_prices.models import MoneyField
+from django_prices.templatetags.prices_i18n import amount
+from prices import Money, fixed_discount, percentage_discount
from . import DiscountValueType, VoucherApplyToProduct, VoucherType
@@ -55,9 +56,9 @@ class Voucher(models.Model):
category = models.ForeignKey(
'product.Category', blank=True, null=True, on_delete=models.CASCADE)
apply_to = models.CharField(max_length=20, blank=True, null=True)
- limit = PriceField(
- max_digits=12, decimal_places=2, null=True, blank=True,
- currency=settings.DEFAULT_CURRENCY)
+ limit = MoneyField(
+ currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,
+ null=True, blank=True)
objects = VoucherQueryset.as_manager()
@@ -109,31 +110,30 @@ class Voucher(models.Model):
return choices[self.apply_to]
return None
- def get_fixed_discount_for(self, amount):
+ def get_discount(self):
if self.discount_value_type == DiscountValueType.FIXED:
- discount_price = Price(
- net=self.discount_value, currency=settings.DEFAULT_CURRENCY)
- discount = FixedDiscount(
- amount=discount_price, name=smart_text(self))
- elif self.discount_value_type == DiscountValueType.PERCENTAGE:
- discount = percentage_discount(
- value=self.discount_value, name=smart_text(self))
- fixed_discount_value = amount - discount.apply(amount)
- discount = FixedDiscount(
- amount=fixed_discount_value, name=smart_text(self))
- else:
- raise NotImplementedError('Unknown discount value type')
- if discount.amount > amount:
- return FixedDiscount(amount, name=smart_text(self))
- return discount
+ discount_amount = Money(
+ self.discount_value, currency=settings.DEFAULT_CURRENCY)
+ return partial(fixed_discount, discount=discount_amount)
+ if self.discount_value_type == DiscountValueType.PERCENTAGE:
+ return partial(percentage_discount, percentage=self.discount_value)
+ raise NotImplementedError('Unknown discount type')
+
+ def get_discount_amount_for(self, price):
+ discount = self.get_discount()
+ gross_price = price.gross
+ gross_after_discount = discount(gross_price)
+ if gross_after_discount.amount < 0:
+ return gross_price
+ return gross_price - gross_after_discount
def validate_limit(self, value):
- limit = self.limit or value
- if value < limit:
+ limit = self.limit or value.gross
+ if value.gross < limit:
msg = pgettext(
'Voucher not applicable',
'This offer is only valid for orders over %(amount)s.')
- raise NotApplicable(msg % {'amount': net(limit)}, limit=limit)
+ raise NotApplicable(msg % {'amount': amount(limit)}, limit=limit)
class Sale(models.Model):
@@ -162,9 +162,9 @@ class Sale(models.Model):
def get_discount(self):
if self.type == DiscountValueType.FIXED:
- discount_price = Price(
- net=self.value, currency=settings.DEFAULT_CURRENCY)
- return FixedDiscount(amount=discount_price, name=self.name)
+ discount_amount = Money(
+ self.value, currency=settings.DEFAULT_CURRENCY)
+ return partial(fixed_discount, discount=discount_amount)
if self.type == DiscountValueType.PERCENTAGE:
- return percentage_discount(value=self.value, name=self.name)
+ return partial(percentage_discount, percentage=self.value)
raise NotImplementedError('Unknown discount type')
diff --git a/saleor/discount/templatetags/voucher.py b/saleor/discount/templatetags/voucher.py
index 7ed48e5856..c3460c4797 100644
--- a/saleor/discount/templatetags/voucher.py
+++ b/saleor/discount/templatetags/voucher.py
@@ -1,11 +1,11 @@
from django import template
-from django_prices.templatetags.prices_i18n import gross
-from prices import Price
+from django_prices.templatetags import prices_i18n
+from prices import Money
register = template.Library()
@register.simple_tag
def discount_as_negative(discount, html=False):
- zero = Price(0, currency=discount.amount.currency)
- return gross(zero - discount.amount, html=html)
+ zero = Money(0, currency=discount.currency)
+ return prices_i18n.amount(zero - discount, 'html' if html else 'text')
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index ed7a169c11..eb48fb05c1 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -2,11 +2,11 @@ from django.conf import settings
from django.db.models import F
from django.utils.encoding import smart_text
from django.utils.translation import pgettext
-from prices import FixedDiscount, Price
-
+from prices import Money, TaxedMoney
from ..cart.utils import (
get_category_variants_and_prices, get_product_variants_and_prices)
+from ..core.utils import ZERO_TAXED_MONEY
from .models import NotApplicable
from . import VoucherApplyToProduct, VoucherType
@@ -57,10 +57,9 @@ def get_product_discounts(product, discounts):
def calculate_discounted_price(product, price, discounts):
"""Return minimum product's price of all prices with discounts applied."""
if discounts:
- discounts = list(
- get_product_discounts(product, discounts))
+ discounts = list(get_product_discounts(product, discounts))
if discounts:
- price = min(price | discount for discount in discounts)
+ price = min(discount(price) for discount in discounts)
return price
@@ -68,7 +67,7 @@ def _get_value_voucher_discount_for_checkout(voucher, checkout):
"""Calculate discount value for a voucher of value type."""
cart_total = checkout.get_subtotal()
voucher.validate_limit(cart_total)
- return voucher.get_fixed_discount_for(cart_total)
+ return voucher.get_discount_amount_for(cart_total)
def _get_shipping_voucher_discount_for_checkout(voucher, checkout):
@@ -94,7 +93,7 @@ def _get_shipping_voucher_discount_for_checkout(voucher, checkout):
msg % {'country': voucher.get_apply_to_display()})
cart_total = checkout.get_subtotal()
voucher.validate_limit(cart_total)
- return voucher.get_fixed_discount_for(shipping_method.price)
+ return voucher.get_discount_amount_for(shipping_method.get_total_price())
def _get_product_or_category_voucher_discount_for_checkout(voucher, checkout):
@@ -114,14 +113,12 @@ def _get_product_or_category_voucher_discount_for_checkout(voucher, checkout):
raise NotApplicable(msg)
if voucher.apply_to == VoucherApplyToProduct.ALL_PRODUCTS:
discounts = (
- voucher.get_fixed_discount_for(price) for price in prices)
- discount_total = sum(
- (discount.amount for discount in discounts),
- Price(0, currency=settings.DEFAULT_CURRENCY))
- return FixedDiscount(discount_total, smart_text(voucher))
- product_total = sum(
- prices, Price(0, currency=settings.DEFAULT_CURRENCY))
- return voucher.get_fixed_discount_for(product_total)
+ voucher.get_discount_amount_for(price) for price in prices)
+ total_amount = sum(
+ discounts, Money(0, currency=settings.DEFAULT_CURRENCY))
+ return total_amount
+ product_total = sum(prices, ZERO_TAXED_MONEY)
+ return voucher.get_discount_amount_for(product_total)
def get_voucher_discount_for_checkout(voucher, checkout):
diff --git a/saleor/graphql/core/types.py b/saleor/graphql/core/types.py
index 7a3b926072..d426877e47 100644
--- a/saleor/graphql/core/types.py
+++ b/saleor/graphql/core/types.py
@@ -33,20 +33,21 @@ class Error(graphene.ObjectType):
message = graphene.String()
-class Price(graphene.ObjectType):
+class Money(graphene.ObjectType):
currency = graphene.String()
- gross = graphene.Float()
- gross_localized = graphene.String()
- net = graphene.Float()
- net_localized = graphene.String()
+ amount = graphene.Float()
+ localized = graphene.String()
- def resolve_gross_localized(self, info):
- return prices_i18n.gross(self)
+ def resolve_localized(self, info):
+ return prices_i18n.amount(self)
- def resolve_net_localized(self, info):
- return prices_i18n.net(self)
+
+class TaxedMoney(graphene.ObjectType):
+ currency = graphene.String()
+ gross = graphene.Field(Money)
+ net = graphene.Field(Money)
-class PriceRange(graphene.ObjectType):
- max_price = graphene.Field(Price)
- min_price = graphene.Field(Price)
+class TaxedMoneyRange(graphene.ObjectType):
+ start = graphene.Field(TaxedMoney)
+ stop = graphene.Field(TaxedMoney)
diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.py
index 6a7904be4c..df42a60280 100644
--- a/saleor/graphql/product/types.py
+++ b/saleor/graphql/product/types.py
@@ -7,7 +7,8 @@ from ...product import models
from ...product.templatetags.product_images import product_first_image
from ...product.utils import get_availability
from ..core.filters import DistinctFilterSet
-from ..core.types import CountableDjangoObjectType, Price, PriceRange
+from ..core.types import (
+ CountableDjangoObjectType, Money, TaxedMoney, TaxedMoneyRange)
from ..utils import get_node
from .filters import ProductFilterSet
@@ -15,11 +16,11 @@ from .filters import ProductFilterSet
class ProductAvailability(graphene.ObjectType):
available = graphene.Boolean()
on_sale = graphene.Boolean()
- discount = graphene.Field(Price)
- discount_local_currency = graphene.Field(Price)
- price_range = graphene.Field(PriceRange)
- price_range_undiscounted = graphene.Field(PriceRange)
- price_range_local_currency = graphene.Field(PriceRange)
+ discount = graphene.Field(TaxedMoney)
+ discount_local_currency = graphene.Field(TaxedMoney)
+ price_range = graphene.Field(TaxedMoneyRange)
+ price_range_undiscounted = graphene.Field(TaxedMoneyRange)
+ price_range_local_currency = graphene.Field(TaxedMoneyRange)
class Product(CountableDjangoObjectType):
@@ -31,7 +32,7 @@ class Product(CountableDjangoObjectType):
images = graphene.List(lambda: ProductImage)
variants = graphene.List(lambda: ProductVariant)
availability = graphene.Field(ProductAvailability)
- price = graphene.Field(Price)
+ price = graphene.Field(Money)
class Meta:
model = models.Product
@@ -98,7 +99,7 @@ class Category(CountableDjangoObjectType):
class ProductVariant(CountableDjangoObjectType):
stock_quantity = graphene.Int()
- price_override = graphene.Field(Price)
+ price_override = graphene.Field(Money)
class Meta:
model = models.ProductVariant
diff --git a/saleor/order/migrations/0001_initial.py b/saleor/order/migrations/0001_initial.py
index 7c61161bb6..39ff15d6bf 100644
--- a/saleor/order/migrations/0001_initial.py
+++ b/saleor/order/migrations/0001_initial.py
@@ -4,9 +4,9 @@ from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
from django.conf import settings
-import django.utils.timezone
import django_prices.models
import django.core.validators
+import django.utils.timezone
class Migration(migrations.Migration):
@@ -24,7 +24,7 @@ class Migration(migrations.Migration):
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('status', models.CharField(default='new', max_length=32, verbose_name='delivery status', choices=[('new', 'Processing'), ('cancelled', 'Cancelled'), ('shipped', 'Shipped')])),
('shipping_required', models.BooleanField(default=True, verbose_name='shipping required')),
- ('shipping_price', django_prices.models.PriceField(decimal_places=4, default=0, editable=False, currency=b'USD', max_digits=12, verbose_name='shipping price')),
+ ('shipping_price', django_prices.models.MoneyField(decimal_places=4, default=0, editable=False, currency=b'USD', max_digits=12, verbose_name='shipping price')),
],
),
migrations.CreateModel(
diff --git a/saleor/order/migrations/0003_auto_20150825_1433.py b/saleor/order/migrations/0003_auto_20150825_1433.py
index d3be4908ae..b213c4e657 100644
--- a/saleor/order/migrations/0003_auto_20150825_1433.py
+++ b/saleor/order/migrations/0003_auto_20150825_1433.py
@@ -15,7 +15,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='deliverygroup',
name='shipping_price',
- field=django_prices.models.PriceField(verbose_name='shipping price', decimal_places=4, default=0, currency='USD', max_digits=12, editable=False),
+ field=django_prices.models.MoneyField(verbose_name='shipping price', decimal_places=4, default=0, currency='USD', max_digits=12, editable=False),
),
migrations.AlterField(
model_name='payment',
diff --git a/saleor/order/migrations/0004_order_total.py b/saleor/order/migrations/0004_order_total.py
index 08e1375a1f..c97b557bde 100644
--- a/saleor/order/migrations/0004_order_total.py
+++ b/saleor/order/migrations/0004_order_total.py
@@ -15,6 +15,6 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='order',
name='total',
- field=django_prices.models.PriceField(decimal_places=2, currency=b'USD', max_digits=12, blank=True, null=True, verbose_name='total'),
+ field=django_prices.models.MoneyField(decimal_places=2, currency='USD', max_digits=12, blank=True, null=True, verbose_name='total'),
),
]
diff --git a/saleor/order/migrations/0009_auto_20151201_0820.py b/saleor/order/migrations/0009_auto_20151201_0820.py
index ba94f97ed3..04a51ff777 100644
--- a/saleor/order/migrations/0009_auto_20151201_0820.py
+++ b/saleor/order/migrations/0009_auto_20151201_0820.py
@@ -20,7 +20,7 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='order',
name='total_tax',
- field=django_prices.models.PriceField(decimal_places=2, currency=b'USD', max_digits=12, blank=True, null=True, verbose_name='total'),
+ field=django_prices.models.MoneyField(decimal_places=2, currency='USD', max_digits=12, blank=True, null=True, verbose_name='total'),
),
migrations.AlterField(
model_name='deliverygroup',
diff --git a/saleor/order/migrations/0011_auto_20160207_0534.py b/saleor/order/migrations/0011_auto_20160207_0534.py
index 98731aaf6c..fd91b04350 100644
--- a/saleor/order/migrations/0011_auto_20160207_0534.py
+++ b/saleor/order/migrations/0011_auto_20160207_0534.py
@@ -18,7 +18,7 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='order',
name='discount_amount',
- field=django_prices.models.PriceField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
+ field=django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
),
migrations.AddField(
model_name='order',
diff --git a/saleor/order/migrations/0013_auto_20160906_0741.py b/saleor/order/migrations/0013_auto_20160906_0741.py
index d2d3485e07..a58b4f5ded 100644
--- a/saleor/order/migrations/0013_auto_20160906_0741.py
+++ b/saleor/order/migrations/0013_auto_20160906_0741.py
@@ -26,12 +26,12 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='order',
name='total_net',
- field=django_prices.models.PriceField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True, verbose_name='total'),
+ field=django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True, verbose_name='total'),
),
migrations.AlterField(
model_name='order',
name='total_tax',
- field=django_prices.models.PriceField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True, verbose_name='total'),
+ field=django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True, verbose_name='total'),
),
migrations.AlterField(
model_name='orderhistoryentry',
diff --git a/saleor/order/migrations/0015_auto_20170206_0407.py b/saleor/order/migrations/0015_auto_20170206_0407.py
index 5452c3773e..1b79351b2b 100644
--- a/saleor/order/migrations/0015_auto_20170206_0407.py
+++ b/saleor/order/migrations/0015_auto_20170206_0407.py
@@ -62,7 +62,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='order',
name='discount_amount',
- field=django_prices.models.PriceField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True, verbose_name='discount amount'),
+ field=django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True, verbose_name='discount amount'),
),
migrations.AlterField(
model_name='order',
@@ -77,12 +77,12 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='order',
name='total_net',
- field=django_prices.models.PriceField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True, verbose_name='total net'),
+ field=django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True, verbose_name='total net'),
),
migrations.AlterField(
model_name='order',
name='total_tax',
- field=django_prices.models.PriceField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True, verbose_name='total tax'),
+ field=django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True, verbose_name='total tax'),
),
migrations.AlterField(
model_name='order',
diff --git a/saleor/order/migrations/0026_auto_20171218_0428.py b/saleor/order/migrations/0026_auto_20171218_0428.py
index fdd25834f9..886e1034df 100644
--- a/saleor/order/migrations/0026_auto_20171218_0428.py
+++ b/saleor/order/migrations/0026_auto_20171218_0428.py
@@ -24,7 +24,7 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='order',
name='shipping_price',
- field=django_prices.models.PriceField(currency='USD', decimal_places=4, default=0, editable=False, max_digits=12, verbose_name='shipping price'),
+ field=django_prices.models.MoneyField(currency='USD', decimal_places=4, default=0, editable=False, max_digits=12, verbose_name='shipping price'),
),
migrations.AlterField(
model_name='orderhistoryentry',
diff --git a/saleor/order/migrations/0027_auto_20180108_0814.py b/saleor/order/migrations/0027_auto_20180108_0814.py
index 364fa6fba5..b00436efad 100644
--- a/saleor/order/migrations/0027_auto_20180108_0814.py
+++ b/saleor/order/migrations/0027_auto_20180108_0814.py
@@ -50,7 +50,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='order',
name='discount_amount',
- field=django_prices.models.PriceField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
+ field=django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
),
migrations.AlterField(
model_name='order',
@@ -70,7 +70,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='order',
name='shipping_price',
- field=django_prices.models.PriceField(currency='USD', decimal_places=4, default=0, editable=False, max_digits=12),
+ field=django_prices.models.MoneyField(currency='USD', decimal_places=4, default=0, editable=False, max_digits=12),
),
migrations.AlterField(
model_name='order',
@@ -80,12 +80,12 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='order',
name='total_net',
- field=django_prices.models.PriceField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
+ field=django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
),
migrations.AlterField(
model_name='order',
name='total_tax',
- field=django_prices.models.PriceField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
+ field=django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
),
migrations.AlterField(
model_name='order',
diff --git a/saleor/order/migrations/0034_auto_20180221_1056.py b/saleor/order/migrations/0034_auto_20180221_1056.py
new file mode 100644
index 0000000000..1fc7aed906
--- /dev/null
+++ b/saleor/order/migrations/0034_auto_20180221_1056.py
@@ -0,0 +1,29 @@
+# Generated by Django 2.0.2 on 2018-02-21 16:56
+
+from django.db import migrations
+import django_prices.models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('order', '0033_auto_20180123_0832'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='order',
+ name='total_gross',
+ field=django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
+ ),
+ migrations.AlterField(
+ model_name='orderline',
+ name='unit_price_gross',
+ field=django_prices.models.MoneyField(currency='USD', decimal_places=4, max_digits=12),
+ ),
+ migrations.AlterField(
+ model_name='orderline',
+ name='unit_price_net',
+ field=django_prices.models.MoneyField(currency='USD', decimal_places=4, max_digits=12),
+ ),
+ ]
diff --git a/saleor/order/migrations/0035_auto_20180221_1057.py b/saleor/order/migrations/0035_auto_20180221_1057.py
new file mode 100644
index 0000000000..b150c53ebf
--- /dev/null
+++ b/saleor/order/migrations/0035_auto_20180221_1057.py
@@ -0,0 +1,35 @@
+# Generated by Django 2.0.2 on 2018-02-21 16:57
+
+from django.db import migrations
+
+
+def populate_orders_total_gross(apps, schema_editor):
+ Order = apps.get_model('order', 'Order')
+ orders_with_total = Order.objects.filter(
+ total_net__isnull=False).iterator()
+
+ for order in orders_with_total:
+ order.total_gross = order.total_net + order.total_tax
+ order.save()
+
+
+def populate_orders_total_tax(apps, schema_editor):
+ Order = apps.get_model('order', 'Order')
+ orders_with_total = Order.objects.filter(
+ total_net__isnull=False).iterator()
+
+ for order in orders_with_total:
+ order.total_tax = order.total_gross - order.total_net
+ order.save()
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('order', '0034_auto_20180221_1056'),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ populate_orders_total_gross, populate_orders_total_tax),
+ ]
diff --git a/saleor/order/migrations/0036_remove_order_total_tax.py b/saleor/order/migrations/0036_remove_order_total_tax.py
new file mode 100644
index 0000000000..30e713dc92
--- /dev/null
+++ b/saleor/order/migrations/0036_remove_order_total_tax.py
@@ -0,0 +1,17 @@
+# Generated by Django 2.0.2 on 2018-02-21 17:04
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('order', '0035_auto_20180221_1057'),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name='order',
+ name='total_tax',
+ ),
+ ]
diff --git a/saleor/order/migrations/0037_auto_20180228_0450.py b/saleor/order/migrations/0037_auto_20180228_0450.py
new file mode 100644
index 0000000000..2b94f5142c
--- /dev/null
+++ b/saleor/order/migrations/0037_auto_20180228_0450.py
@@ -0,0 +1,29 @@
+# Generated by Django 2.0.2 on 2018-02-28 10:50
+
+from django.db import migrations
+import django_prices.models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('order', '0036_remove_order_total_tax'),
+ ]
+
+ operations = [
+ migrations.RenameField(
+ model_name='order',
+ old_name='shipping_price',
+ new_name='shipping_price_gross',
+ ),
+ migrations.AlterField(
+ model_name='order',
+ name='shipping_price_gross',
+ field=django_prices.models.MoneyField(currency='USD', decimal_places=2, default=0, editable=False, max_digits=12),
+ ),
+ migrations.AddField(
+ model_name='order',
+ name='shipping_price_net',
+ field=django_prices.models.MoneyField(currency='USD', decimal_places=2, default=0, editable=False, max_digits=12),
+ ),
+ ]
diff --git a/saleor/order/migrations/0038_auto_20180228_0451.py b/saleor/order/migrations/0038_auto_20180228_0451.py
new file mode 100644
index 0000000000..d449c0702d
--- /dev/null
+++ b/saleor/order/migrations/0038_auto_20180228_0451.py
@@ -0,0 +1,28 @@
+# Generated by Django 2.0.2 on 2018-02-28 10:51
+
+from django.db import migrations
+
+
+def populate_orders_shipping_price_net(apps, schema_editor):
+ Order = apps.get_model('order', 'Order')
+ orders_with_shipping_price_gross = Order.objects.filter(
+ shipping_price_gross__isnull=False).iterator()
+
+ for order in orders_with_shipping_price_gross:
+ # At the time of writing this migration we lack information to reliably
+ # calculate shipping's net price, so we equal it to gross
+ order.shipping_price_net = order.shipping_price_gross
+ order.save()
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('order', '0037_auto_20180228_0450'),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ populate_orders_shipping_price_net,
+ migrations.RunPython.noop),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 12aa887458..e115fe7211 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -9,14 +9,14 @@ from django.urls import reverse
from django.utils.timezone import now
from django.utils.translation import pgettext_lazy
from django_fsm import FSMField, transition
-from django_prices.models import PriceField
+from django_prices.models import MoneyField, TaxedMoneyField
from payments import PaymentStatus, PurchasedItem
from payments.models import BasePayment
-from prices import FixedDiscount, Price
+from prices import Money, TaxedMoney
from . import GroupStatus, OrderStatus
from ..account.models import Address
-from ..core.utils import build_absolute_uri
+from ..core.utils import ZERO_TAXED_MONEY, build_absolute_uri
from ..discount.models import Voucher
from ..product.models import Product
from .transitions import (
@@ -55,19 +55,25 @@ class Order(models.Model):
on_delete=models.PROTECT)
user_email = models.EmailField(
blank=True, default='', editable=False)
- shipping_price = PriceField(
- currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=4,
+ shipping_price_net = MoneyField(
+ currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,
+ default=0, editable=False)
+ shipping_price_gross = MoneyField(
+ currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,
default=0, editable=False)
+ shipping_price = TaxedMoneyField(
+ net_field='shipping_price_net', gross_field='shipping_price_gross')
token = models.CharField(max_length=36, unique=True)
- total_net = PriceField(
+ total_net = MoneyField(
currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,
blank=True, null=True)
- total_tax = PriceField(
+ total_gross = MoneyField(
currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,
blank=True, null=True)
+ total = TaxedMoneyField(net_field='total_net', gross_field='total_gross')
voucher = models.ForeignKey(
Voucher, null=True, related_name='+', on_delete=models.SET_NULL)
- discount_amount = PriceField(
+ discount_amount = MoneyField(
currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,
blank=True, null=True)
discount_name = models.CharField(max_length=255, default='', blank=True)
@@ -92,9 +98,13 @@ class Order(models.Model):
def is_fully_paid(self):
total_paid = sum(
- [payment.total for payment in
- self.payments.filter(status=PaymentStatus.CONFIRMED)], Decimal())
- return total_paid >= self.total.gross
+ [
+ payment.get_total_price() for payment in
+ self.payments.filter(status=PaymentStatus.CONFIRMED)],
+ TaxedMoney(
+ net=Money(0, currency=settings.DEFAULT_CURRENCY),
+ gross=Money(0, currency=settings.DEFAULT_CURRENCY)))
+ return total_paid.gross >= self.total.gross
def get_user_current_email(self):
return self.user.email if self.user else self.user_email
@@ -114,11 +124,6 @@ class Order(models.Model):
def __str__(self):
return '#%d' % (self.id,)
- @property
- def discount(self):
- return FixedDiscount(
- amount=self.discount_amount, name=self.discount_name)
-
def get_absolute_url(self):
return reverse('order:details', kwargs={'token': self.token})
@@ -156,24 +161,9 @@ class Order(models.Model):
"""Order status display text."""
return dict(OrderStatus.CHOICES)[self.status]
- @property
- def total(self):
- if self.total_net is not None:
- gross = self.total_net.net + self.total_tax.gross
- return Price(
- net=self.total_net.net, gross=gross,
- currency=settings.DEFAULT_CURRENCY)
- return None
-
- @total.setter
- def total(self, price):
- self.total_net = price
- self.total_tax = Price(price.tax, currency=price.currency)
-
- def get_subtotal_without_voucher(self):
- if self.get_lines():
- return self.total
- return Price(net=0, currency=settings.DEFAULT_CURRENCY)
+ def get_subtotal(self):
+ subtotal_iterator = (line.get_total() for line in self.get_lines())
+ return sum(subtotal_iterator, ZERO_TAXED_MONEY)
def can_cancel(self):
return self.status == OrderStatus.OPEN
@@ -260,19 +250,18 @@ class OrderLine(models.Model):
'product.Stock', on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(
validators=[MinValueValidator(0), MaxValueValidator(999)])
- unit_price_net = models.DecimalField(max_digits=12, decimal_places=4)
- unit_price_gross = models.DecimalField(max_digits=12, decimal_places=4)
+ unit_price_net = MoneyField(
+ currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=4)
+ unit_price_gross = MoneyField(
+ currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=4)
+ unit_price = TaxedMoneyField(
+ net_field='unit_price_net', gross_field='unit_price_gross')
def __str__(self):
return self.product_name
- def get_price_per_item(self):
- return Price(
- net=self.unit_price_net, gross=self.unit_price_gross,
- currency=settings.DEFAULT_CURRENCY)
-
def get_total(self):
- return self.get_price_per_item() * self.quantity
+ return self.unit_price * self.quantity
class PaymentQuerySet(models.QuerySet):
@@ -317,16 +306,19 @@ class Payment(BasePayment):
name=self.order.discount_name,
sku='DISCOUNT',
quantity=1,
- price=-self.order.discount_amount.net,
+ price=-self.order.discount_amount.amount,
currency=self.currency))
return lines
def get_total_price(self):
- net = self.total - self.tax
- return Price(net, gross=self.total, currency=self.currency)
+ return TaxedMoney(
+ net=Money(self.total - self.tax, currency=self.currency),
+ gross=Money(self.total, currency=self.currency))
def get_captured_price(self):
- return Price(self.captured_amount, currency=self.currency)
+ return TaxedMoney(
+ net=Money(self.captured_amount, currency=self.currency),
+ gross=Money(self.captured_amount, currency=self.currency))
class OrderHistoryEntry(models.Model):
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 0d11a6ef39..5bd7f09866 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -4,11 +4,12 @@ from django.conf import settings
from django.db.models import F
from django.shortcuts import get_object_or_404, redirect
from django.utils.translation import pgettext_lazy
-from prices import Price
+from prices import Money, TaxedMoney, fixed_discount
from . import GroupStatus
from ..account.utils import store_user_address
from ..core.exceptions import InsufficientStock
+from ..core.utils import ZERO_TAXED_MONEY
from ..product.utils import allocate_stock
@@ -42,16 +43,15 @@ def cancel_order(order):
def recalculate_order(order):
"""Recalculate and assign total price of order.
- Total price is a sum of items in shipment groups and order shipping price.
+ Total price is a sum of items in shipment groups and order shipping price
+ minus discount amount.
"""
prices = [
group.get_total() for group in order
if group.status != GroupStatus.CANCELLED]
- total_net = sum(p.net for p in prices)
- total_gross = sum(p.gross for p in prices)
- total = Price(
- net=total_net, gross=total_gross, currency=settings.DEFAULT_CURRENCY)
- total += order.shipping_price
+ total = sum(prices, order.shipping_price)
+ if order.discount_amount:
+ total -= order.discount_amount
order.total = total
order.save()
@@ -97,8 +97,7 @@ def add_variant_to_delivery_group(
is_shipping_required=(
variant.product.product_type.is_shipping_required),
quantity=quantity,
- unit_price_net=price.net,
- unit_price_gross=price.gross,
+ unit_price=price,
stock=stock,
stock_location=stock.location.name)
allocate_stock(stock, quantity)
diff --git a/saleor/order/views.py b/saleor/order/views.py
index c8bd9d266c..e36fcc8b21 100644
--- a/saleor/order/views.py
+++ b/saleor/order/views.py
@@ -85,10 +85,10 @@ def start_payment(request, order, variant):
billing = order.billing_address
total = order.total
defaults = {
- 'total': total.gross,
- 'tax': total.tax,
+ 'total': total.gross.amount,
+ 'tax': total.tax.amount,
'currency': total.currency,
- 'delivery': order.shipping_price.gross,
+ 'delivery': order.shipping_price.gross.amount,
'billing_first_name': billing.first_name,
'billing_last_name': billing.last_name,
'billing_address_1': billing.street_address_1,
diff --git a/saleor/product/filters.py b/saleor/product/filters.py
index cbb063fcde..e075cc0cc1 100644
--- a/saleor/product/filters.py
+++ b/saleor/product/filters.py
@@ -4,7 +4,7 @@ from django.db.models import Q
from django.forms import CheckboxSelectMultiple, ValidationError
from django.utils.translation import pgettext_lazy
from django_filters import MultipleChoiceFilter, OrderingFilter, RangeFilter
-from django_prices.models import PriceField
+from django_prices.models import MoneyField
from ..core.filters import SortedFilterSet
from .models import Product, ProductAttribute
@@ -23,7 +23,7 @@ class ProductFilter(SortedFilterSet):
class Meta:
model = Product
fields = ['price']
- filter_overrides = {PriceField: {'filter_class': RangeFilter}}
+ filter_overrides = {MoneyField: {'filter_class': RangeFilter}}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
diff --git a/saleor/product/forms.py b/saleor/product/forms.py
index df7b23eeeb..5f9faf43ba 100644
--- a/saleor/product/forms.py
+++ b/saleor/product/forms.py
@@ -3,7 +3,7 @@ import json
from django import forms
from django.utils.encoding import smart_text
from django.utils.translation import pgettext_lazy
-from django_prices.templatetags.prices_i18n import gross
+from django_prices.templatetags.prices_i18n import amount
from ..cart.forms import AddToCartForm
@@ -17,8 +17,8 @@ class VariantChoiceField(forms.ModelChoiceField):
'Variant choice field label',
'%(variant_label)s - %(price)s') % {
'variant_label': variant_label,
- 'price': gross(
- obj.get_price_per_item(discounts=self.discounts))}
+ 'price': amount(
+ obj.get_price_per_item(discounts=self.discounts).gross)}
return label
def update_field_data(self, variants, cart):
diff --git a/saleor/product/migrations/0001_initial.py b/saleor/product/migrations/0001_initial.py
index 8dabecb05b..7256e52c9c 100644
--- a/saleor/product/migrations/0001_initial.py
+++ b/saleor/product/migrations/0001_initial.py
@@ -1,10 +1,11 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
+from decimal import Decimal
+
from django.db import models, migrations
import django.db.models.deletion
import versatileimagefield.fields
-from decimal import Decimal
import django.core.validators
import django_prices.models
@@ -47,7 +48,7 @@ class Migration(migrations.Migration):
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=255)),
- ('discount', django_prices.models.PriceField(currency=b'USD', verbose_name='discount value', max_digits=12, decimal_places=2)),
+ ('discount', django_prices.models.MoneyField(currency='USD', verbose_name='discount value', max_digits=12, decimal_places=2)),
],
),
migrations.CreateModel(
@@ -56,7 +57,7 @@ class Migration(migrations.Migration):
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=128, verbose_name='name')),
('description', models.TextField(verbose_name='description')),
- ('price', django_prices.models.PriceField(currency=b'USD', verbose_name='price', max_digits=12, decimal_places=2)),
+ ('price', django_prices.models.MoneyField(currency='USD', verbose_name='price', max_digits=12, decimal_places=2)),
('weight', models.DecimalField(verbose_name='weight', max_digits=6, decimal_places=2)),
('available_on', models.DateField(null=True, verbose_name='available on', blank=True)),
],
@@ -92,7 +93,7 @@ class Migration(migrations.Migration):
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('sku', models.CharField(unique=True, max_length=32, verbose_name='SKU')),
('name', models.CharField(max_length=100, verbose_name='variant name', blank=True)),
- ('price_override', django_prices.models.PriceField(decimal_places=2, currency=b'USD', max_digits=12, blank=True, null=True, verbose_name='price override')),
+ ('price_override', django_prices.models.MoneyField(decimal_places=2, currency='USD', max_digits=12, blank=True, null=True, verbose_name='price override')),
('weight_override', models.DecimalField(decimal_places=2, max_digits=6, blank=True, null=True, verbose_name='weight override')),
('attributes', models.TextField(default='{}', verbose_name='attributes')),
('product', models.ForeignKey(related_name='variants', to='product.Product', on_delete=django.db.models.deletion.CASCADE)),
@@ -104,7 +105,7 @@ class Migration(migrations.Migration):
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('location', models.CharField(max_length=100, verbose_name='location')),
('quantity', models.IntegerField(default=Decimal('1'), verbose_name='quantity', validators=[django.core.validators.MinValueValidator(0)])),
- ('cost_price', django_prices.models.PriceField(decimal_places=2, currency=b'USD', max_digits=12, blank=True, null=True, verbose_name='cost price')),
+ ('cost_price', django_prices.models.MoneyField(decimal_places=2, currency='USD', max_digits=12, blank=True, null=True, verbose_name='cost price')),
('variant', models.ForeignKey(related_name='stock', verbose_name='variant', to='product.ProductVariant', on_delete=django.db.models.deletion.CASCADE)),
],
),
diff --git a/saleor/product/migrations/0005_auto_20150825_1433.py b/saleor/product/migrations/0005_auto_20150825_1433.py
index ec3fc84134..cdf3c8d0e0 100644
--- a/saleor/product/migrations/0005_auto_20150825_1433.py
+++ b/saleor/product/migrations/0005_auto_20150825_1433.py
@@ -15,12 +15,12 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='fixedproductdiscount',
name='discount',
- field=django_prices.models.PriceField(verbose_name='discount value', max_digits=12, decimal_places=2, currency='USD'),
+ field=django_prices.models.MoneyField(verbose_name='discount value', max_digits=12, decimal_places=2, currency='USD'),
),
migrations.AlterField(
model_name='product',
name='price',
- field=django_prices.models.PriceField(verbose_name='price', max_digits=12, decimal_places=2, currency='USD'),
+ field=django_prices.models.MoneyField(verbose_name='price', max_digits=12, decimal_places=2, currency='USD'),
),
migrations.AlterField(
model_name='product',
@@ -30,7 +30,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='productvariant',
name='price_override',
- field=django_prices.models.PriceField(verbose_name='price override', decimal_places=2, blank=True, currency='USD', max_digits=12, null=True),
+ field=django_prices.models.MoneyField(verbose_name='price override', decimal_places=2, blank=True, currency='USD', max_digits=12, null=True),
),
migrations.AlterField(
model_name='productvariant',
@@ -40,6 +40,6 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='stock',
name='cost_price',
- field=django_prices.models.PriceField(verbose_name='cost price', decimal_places=2, blank=True, currency='USD', max_digits=12, null=True),
+ field=django_prices.models.MoneyField(verbose_name='cost price', decimal_places=2, blank=True, currency='USD', max_digits=12, null=True),
),
]
diff --git a/saleor/product/migrations/0044_auto_20180108_0814.py b/saleor/product/migrations/0044_auto_20180108_0814.py
index 11ae245282..c4a2873383 100644
--- a/saleor/product/migrations/0044_auto_20180108_0814.py
+++ b/saleor/product/migrations/0044_auto_20180108_0814.py
@@ -3,6 +3,7 @@
from __future__ import unicode_literals
from decimal import Decimal
+
import django.contrib.postgres.fields.hstore
import django.core.validators
from django.db import migrations, models
@@ -91,7 +92,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='product',
name='price',
- field=django_prices.models.PriceField(currency='USD', decimal_places=2, max_digits=12),
+ field=django_prices.models.MoneyField(currency='USD', decimal_places=2, max_digits=12),
),
migrations.AlterField(
model_name='product',
@@ -181,7 +182,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='productvariant',
name='price_override',
- field=django_prices.models.PriceField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
+ field=django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
),
migrations.AlterField(
model_name='productvariant',
@@ -191,7 +192,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='stock',
name='cost_price',
- field=django_prices.models.PriceField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
+ field=django_prices.models.MoneyField(blank=True, currency='USD', decimal_places=2, max_digits=12, null=True),
),
migrations.AlterField(
model_name='stock',
diff --git a/saleor/product/models.py b/saleor/product/models.py
index e6b9400de0..fd645568aa 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -10,10 +10,10 @@ from django.urls import reverse
from django.utils.encoding import smart_text
from django.utils.text import slugify
from django.utils.translation import pgettext_lazy
-from django_prices.models import Price, PriceField
+from django_prices.models import MoneyField
from mptt.managers import TreeManager
from mptt.models import MPTTModel
-from prices import PriceRange
+from prices import Money, TaxedMoney, TaxedMoneyRange
from text_unidecode import unidecode
from versatileimagefield.fields import PPOIField, VersatileImageField
@@ -94,7 +94,7 @@ class Product(models.Model):
description = models.TextField()
category = models.ForeignKey(
Category, related_name='products', on_delete=models.CASCADE)
- price = PriceField(
+ price = MoneyField(
currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2)
available_on = models.DateField(blank=True, null=True)
is_published = models.BooleanField(default=True)
@@ -164,9 +164,11 @@ class Product(models.Model):
prices = [
self.get_price_per_item(variant, discounts=discounts)
for variant in self]
- return PriceRange(min(prices), max(prices))
- price = calculate_discounted_price(self, self.price, discounts)
- return PriceRange(price, price)
+ return TaxedMoneyRange(min(prices), max(prices))
+ price = TaxedMoney(net=self.price, gross=self.price)
+ discounted_price = calculate_discounted_price(
+ self, price, discounts)
+ return TaxedMoneyRange(start=discounted_price, stop=discounted_price)
def get_gross_price_range(self, discounts=None):
grosses = [
@@ -175,13 +177,13 @@ class Product(models.Model):
if not grosses:
return None
grosses = sorted(grosses, key=lambda x: x.tax)
- return PriceRange(min(grosses), max(grosses))
+ return TaxedMoneyRange(min(grosses), max(grosses))
class ProductVariant(models.Model):
sku = models.CharField(max_length=32, unique=True)
name = models.CharField(max_length=100, blank=True)
- price_override = PriceField(
+ price_override = MoneyField(
currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,
blank=True, null=True)
product = models.ForeignKey(
@@ -205,6 +207,7 @@ class ProductVariant(models.Model):
def get_price_per_item(self, discounts=None):
price = self.price_override or self.product.price
+ price = TaxedMoney(net=price, gross=price)
price = calculate_discounted_price(self.product, price, discounts)
return price
@@ -261,7 +264,7 @@ class ProductVariant(models.Model):
stock = [
stock_item for stock_item in self.stock.all()
if stock_item.quantity_available >= quantity]
- zero_price = Price(0, currency=settings.DEFAULT_CURRENCY)
+ zero_price = Money(0, currency=settings.DEFAULT_CURRENCY)
stock = sorted(
stock, key=(lambda s: s.cost_price or zero_price), reverse=False)
if stock:
@@ -300,7 +303,7 @@ class Stock(models.Model):
validators=[MinValueValidator(0)], default=Decimal(1))
quantity_allocated = models.IntegerField(
validators=[MinValueValidator(0)], default=Decimal(0))
- cost_price = PriceField(
+ cost_price = MoneyField(
currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,
blank=True, null=True)
@@ -315,6 +318,10 @@ class Stock(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)
+
class ProductAttribute(models.Model):
slug = models.SlugField(max_length=50, unique=True)
diff --git a/saleor/product/utils.py b/saleor/product/utils.py
index 6079a93615..d2e4643b19 100644
--- a/saleor/product/utils.py
+++ b/saleor/product/utils.py
@@ -6,11 +6,12 @@ from django.contrib.auth.models import AnonymousUser
from django.db.models import F
from django.utils.encoding import smart_text
from django_prices.templatetags import prices_i18n
-from prices import Price, PriceRange
+from prices import Money, TaxedMoney, TaxedMoneyRange
from . import ProductAvailabilityStatus, VariantAvailabilityStatus
from ..cart.utils import get_cart_from_request, get_or_create_cart_from_request
-from ..core.utils import get_paginator_items, to_local_currency
+from ..core.utils import (
+ ZERO_TAXED_MONEY, get_paginator_items, to_local_currency)
from ..core.utils.filters import get_now_sorted_by
from .forms import ProductForm
@@ -60,8 +61,8 @@ def get_availability(product, discounts=None, local_currency=None):
# In default currency
price_range = product.get_price_range(discounts=discounts)
undiscounted = product.get_price_range()
- if undiscounted.min_price > price_range.min_price:
- discount = undiscounted.min_price - price_range.min_price
+ if undiscounted.start > price_range.start:
+ discount = undiscounted.start - price_range.start
else:
discount = None
@@ -72,9 +73,9 @@ def get_availability(product, discounts=None, local_currency=None):
undiscounted_local = to_local_currency(
undiscounted, local_currency)
if (undiscounted_local and
- undiscounted_local.min_price > price_range_local.min_price):
+ undiscounted_local.start > price_range_local.start):
discount_local_currency = (
- undiscounted_local.min_price - price_range_local.min_price)
+ undiscounted_local.start - price_range_local.start)
else:
discount_local_currency = None
else:
@@ -84,7 +85,7 @@ def get_availability(product, discounts=None, local_currency=None):
is_available = product.is_in_stock() and product.is_available()
is_on_sale = (
product.is_available() and discount is not None and
- undiscounted.min_price != price_range.min_price)
+ undiscounted.start != price_range.start)
return ProductAvailability(
available=is_available,
@@ -134,7 +135,7 @@ def product_json_ld(product, attributes=None):
'@type': 'Offer',
'availability': available,
'itemCondition': 'http://schema.org/NewCondition',
- 'price': price.gross,
+ 'price': price.gross.amount,
'priceCurrency': price.currency,
'sku': variant.sku}
data['offers'].append(variant_data)
@@ -174,7 +175,7 @@ def get_variant_picker_data(product, discounts=None, local_currency=None):
schema_data = {'@type': 'Offer',
'itemCondition': 'http://schema.org/NewCondition',
'priceCurrency': price.currency,
- 'price': price.net}
+ 'price': price.net.amount}
in_stock = variant.is_in_stock()
if in_stock:
schema_data['availability'] = 'http://schema.org/InStock'
@@ -227,20 +228,22 @@ def get_product_attributes_data(product):
def price_as_dict(price):
- if not price:
+ if price is None:
return None
- return {'currency': price.currency,
- 'gross': price.gross,
- 'grossLocalized': prices_i18n.gross(price),
- 'net': price.net,
- 'netLocalized': prices_i18n.net(price)}
+ return {
+ 'currency': price.currency,
+ 'gross': price.gross.amount,
+ 'grossLocalized': prices_i18n.amount(price.gross),
+ 'net': price.net.amount,
+ 'netLocalized': prices_i18n.amount(price.net)}
def price_range_as_dict(price_range):
if not price_range:
return None
- return {'maxPrice': price_as_dict(price_range.max_price),
- 'minPrice': price_as_dict(price_range.min_price)}
+ return {
+ 'maxPrice': price_as_dict(price_range.start),
+ 'minPrice': price_as_dict(price_range.stop)}
def get_variant_url_from_product(product, attributes):
@@ -311,9 +314,8 @@ def get_variant_availability_status(variant):
def get_product_costs_data(product):
- zero_price = Price(0, 0, currency=settings.DEFAULT_CURRENCY)
- zero_price_range = PriceRange(zero_price, zero_price)
- purchase_costs_range = zero_price_range
+ purchase_costs_range = TaxedMoneyRange(
+ start=ZERO_TAXED_MONEY, stop=ZERO_TAXED_MONEY)
gross_margin = (0, 0)
if not product.variants.exists():
@@ -323,7 +325,7 @@ def get_product_costs_data(product):
costs, margins = get_cost_data_from_variants(variants)
if costs:
- purchase_costs_range = PriceRange(min(costs), max(costs))
+ purchase_costs_range = TaxedMoneyRange(min(costs), max(costs))
if margins:
gross_margin = (margins[0], margins[-1])
return purchase_costs_range, gross_margin
@@ -359,17 +361,17 @@ def get_variant_costs_data(variant):
def get_cost_price(stock):
- zero_price = Price(0, 0, currency=settings.DEFAULT_CURRENCY)
if not stock.cost_price:
- return zero_price
- return stock.cost_price
+ return ZERO_TAXED_MONEY
+ return stock.get_total()
def get_margin_for_variant(stock):
- if not stock.cost_price:
+ stock_price = stock.get_total()
+ if stock_price is None:
return None
price = stock.variant.get_price_per_item()
- margin = price - stock.cost_price
+ margin = price - stock_price
percent = round((margin.gross / price.gross) * 100, 0)
return percent
diff --git a/saleor/product/views.py b/saleor/product/views.py
index 50a3193d6b..f6467b62bb 100644
--- a/saleor/product/views.py
+++ b/saleor/product/views.py
@@ -65,18 +65,18 @@ def product_details(request, slug, product_id, form=None):
show_variant_picker = all([v.attributes for v in product.variants.all()])
json_ld_data = product_json_ld(product, product_attributes)
return TemplateResponse(
- request, 'product/details.html',
- {'is_visible': is_visible,
- 'form': form,
- 'availability': availability,
- 'product': product,
- 'product_attributes': product_attributes,
- 'product_images': product_images,
- 'show_variant_picker': show_variant_picker,
- 'variant_picker_data': json.dumps(
- variant_picker_data, default=serialize_decimal),
- 'json_ld_product_data': json.dumps(
- json_ld_data, default=serialize_decimal)})
+ request, 'product/details.html', {
+ 'is_visible': is_visible,
+ 'form': form,
+ 'availability': availability,
+ 'product': product,
+ 'product_attributes': product_attributes,
+ 'product_images': product_images,
+ 'show_variant_picker': show_variant_picker,
+ 'variant_picker_data': json.dumps(
+ variant_picker_data, default=serialize_decimal),
+ 'json_ld_product_data': json.dumps(
+ json_ld_data, default=serialize_decimal)})
def product_add_to_cart(request, slug, product_id):
diff --git a/saleor/shipping/migrations/0001_initial.py b/saleor/shipping/migrations/0001_initial.py
index e051b52576..c47178f2c5 100644
--- a/saleor/shipping/migrations/0001_initial.py
+++ b/saleor/shipping/migrations/0001_initial.py
@@ -29,7 +29,7 @@ class Migration(migrations.Migration):
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('country_code', models.CharField(blank=True, choices=[(b'', b'Any country'), ('AF', 'Afghanistan'), ('AX', '\xc5land Islands'), ('AL', 'Albania'), ('DZ', 'Algeria'), ('AS', 'American Samoa'), ('AD', 'Andorra'), ('AO', 'Angola'), ('AI', 'Anguilla'), ('AQ', 'Antarctica'), ('AG', 'Antigua And Barbuda'), ('AR', 'Argentina'), ('AM', 'Armenia'), ('AW', 'Aruba'), ('AU', 'Australia'), ('AT', 'Austria'), ('AZ', 'Azerbaijan'), ('BS', 'Bahamas'), ('BH', 'Bahrain'), ('BD', 'Bangladesh'), ('BB', 'Barbados'), ('BY', 'Belarus'), ('BE', 'Belgium'), ('BZ', 'Belize'), ('BJ', 'Benin'), ('BM', 'Bermuda'), ('BT', 'Bhutan'), ('BO', 'Bolivia'), ('BQ', 'Bonaire, Saint Eustatius And Saba'), ('BA', 'Bosnia And Herzegovina'), ('BW', 'Botswana'), ('BV', 'Bouvet Island'), ('BR', 'Brazil'), ('IO', 'British Indian Ocean Territory'), ('BN', 'Brunei Darussalam'), ('BG', 'Bulgaria'), ('BF', 'Burkina Faso'), ('BI', 'Burundi'), ('KH', 'Cambodia'), ('CM', 'Cameroon'), ('CA', 'Canada'), ('CV', 'Cape Verde'), ('KY', 'Cayman Islands'), ('CF', 'Central African Republic'), ('TD', 'Chad'), ('CL', 'Chile'), ('CN', 'China'), ('CX', 'Christmas Island'), ('CC', 'Cocos (Keeling) Islands'), ('CO', 'Colombia'), ('KM', 'Comoros'), ('CG', 'Congo'), ('CD', 'Congo, The Democratic Republic of the'), ('CK', 'Cook Islands'), ('CR', 'Costa Rica'), ('CI', "C\xf4te D'Ivoire"), ('HR', 'Croatia'), ('CU', 'Cuba'), ('CW', 'Cura\xe7o'), ('CY', 'Cyprus'), ('CZ', 'Czech Republic'), ('DK', 'Denmark'), ('DJ', 'Djibouti'), ('DM', 'Dominica'), ('DO', 'Dominican Republic'), ('EC', 'Ecuador'), ('EG', 'Egypt'), ('SV', 'El Salvador'), ('GQ', 'Equatorial Guinea'), ('ER', 'Eritrea'), ('EE', 'Estonia'), ('ET', 'Ethiopia'), ('FK', 'Falkland Islands (Malvinas)'), ('FO', 'Faroe Islands'), ('FJ', 'Fiji'), ('FI', 'Finland'), ('FR', 'France'), ('GF', 'French Guiana'), ('PF', 'French Polynesia'), ('TF', 'French Southern Territories'), ('GA', 'Gabon'), ('GM', 'Gambia'), ('GE', 'Georgia'), ('DE', 'Germany'), ('GH', 'Ghana'), ('GI', 'Gibraltar'), ('GR', 'Greece'), ('GL', 'Greenland'), ('GD', 'Grenada'), ('GP', 'Guadeloupe'), ('GU', 'Guam'), ('GT', 'Guatemala'), ('GG', 'Guernsey'), ('GN', 'Guinea'), ('GW', 'Guinea-Bissau'), ('GY', 'Guyana'), ('HT', 'Haiti'), ('HM', 'Heard Island And Mcdonald Islands'), ('VA', 'Holy See (Vatican City State)'), ('HN', 'Honduras'), ('HK', 'Hong Kong'), ('HU', 'Hungary'), ('IS', 'Iceland'), ('IN', 'India'), ('ID', 'Indonesia'), ('IR', 'Iran, Islamic Republic of'), ('IQ', 'Iraq'), ('IE', 'Ireland'), ('IM', 'Isle of Man'), ('IL', 'Israel'), ('IT', 'Italy'), ('JM', 'Jamaica'), ('JP', 'Japan'), ('JE', 'Jersey'), ('JO', 'Jordan'), ('KZ', 'Kazakhstan'), ('KE', 'Kenya'), ('KI', 'Kiribati'), ('KP', "Korea, Democratic People's Republic of"), ('KR', 'Korea, Republic of'), ('KW', 'Kuwait'), ('KG', 'Kyrgyzstan'), ('LA', "Lao People's Democratic Republic"), ('LV', 'Latvia'), ('LB', 'Lebanon'), ('LS', 'Lesotho'), ('LR', 'Liberia'), ('LY', 'Libya'), ('LI', 'Liechtenstein'), ('LT', 'Lithuania'), ('LU', 'Luxembourg'), ('MO', 'Macao'), ('MK', 'Macedonia, The Former Yugoslav Republic of'), ('MG', 'Madagascar'), ('MW', 'Malawi'), ('MY', 'Malaysia'), ('MV', 'Maldives'), ('ML', 'Mali'), ('MT', 'Malta'), ('MH', 'Marshall Islands'), ('MQ', 'Martinique'), ('MR', 'Mauritania'), ('MU', 'Mauritius'), ('YT', 'Mayotte'), ('MX', 'Mexico'), ('FM', 'Micronesia, Federated States of'), ('MD', 'Moldova, Republic of'), ('MC', 'Monaco'), ('MN', 'Mongolia'), ('ME', 'Montenegro'), ('MS', 'Montserrat'), ('MA', 'Morocco'), ('MZ', 'Mozambique'), ('MM', 'Myanmar'), ('NA', 'Namibia'), ('NR', 'Nauru'), ('NP', 'Nepal'), ('NL', 'Netherlands'), ('NC', 'New Caledonia'), ('NZ', 'New Zealand'), ('NI', 'Nicaragua'), ('NE', 'Niger'), ('NG', 'Nigeria'), ('NU', 'Niue'), ('NF', 'Norfolk Island'), ('MP', 'Northern Mariana Islands'), ('NO', 'Norway'), ('OM', 'Oman'), ('PK', 'Pakistan'), ('PW', 'Palau'), ('PS', 'Palestinian Territory, Occupied'), ('PA', 'Panama'), ('PG', 'Papua New Guinea'), ('PY', 'Paraguay'), ('PE', 'Peru'), ('PH', 'Philippines'), ('PN', 'Pitcairn'), ('PL', 'Poland'), ('PT', 'Portugal'), ('PR', 'Puerto Rico'), ('QA', 'Qatar'), ('RE', 'R\xe9union'), ('RO', 'Romania'), ('RU', 'Russian Federation'), ('RW', 'Rwanda'), ('BL', 'Saint Barth\xe9lemy'), ('SH', 'Saint Helena, Ascension And Tristan Da Cunha'), ('KN', 'Saint Kitts And Nevis'), ('LC', 'Saint Lucia'), ('MF', 'Saint Martin (French Part)'), ('PM', 'Saint Pierre And Miquelon'), ('VC', 'Saint Vincent And the Grenadines'), ('WS', 'Samoa'), ('SM', 'San Marino'), ('ST', 'Sao Tome And Principe'), ('SA', 'Saudi Arabia'), ('SN', 'Senegal'), ('RS', 'Serbia'), ('SC', 'Seychelles'), ('SL', 'Sierra Leone'), ('SG', 'Singapore'), ('SX', 'Sint Maarten (Dutch Part)'), ('SK', 'Slovakia'), ('SI', 'Slovenia'), ('SB', 'Solomon Islands'), ('SO', 'Somalia'), ('ZA', 'South Africa'), ('GS', 'South Georgia and the South Sandwich Islands'), ('ES', 'Spain'), ('LK', 'Sri Lanka'), ('SD', 'Sudan'), ('SR', 'Suriname'), ('SJ', 'Svalbard and Jan Mayen'), ('SZ', 'Swaziland'), ('SE', 'Sweden'), ('CH', 'Switzerland'), ('SY', 'Syria'), ('TW', 'Taiwan'), ('TJ', 'Tajikistan'), ('TZ', 'Tanzania'), ('TH', 'Thailand'), ('TL', 'Timor-Leste'), ('TG', 'Togo'), ('TK', 'Tokelau'), ('TO', 'Tonga'), ('TT', 'Trinidad And Tobago'), ('TN', 'Tunisia'), ('TR', 'Turkey'), ('TM', 'Turkmenistan'), ('TC', 'Turks And Caicos Islands'), ('TV', 'Tuvalu'), ('UG', 'Uganda'), ('UA', 'Ukraine'), ('AE', 'United Arab Emirates'), ('GB', 'United Kingdom'), ('US', 'United States'), ('UM', 'United States Minor Outlying Islands'), ('UY', 'Uruguay'), ('UZ', 'Uzbekistan'), ('VU', 'Vanuatu'), ('VE', 'Venezuela'), ('VN', 'Viet Nam'), ('VG', 'Virgin Islands, British'), ('VI', 'Virgin Islands, U.S.'), ('WF', 'Wallis And Futuna'), ('EH', 'Western Sahara'), ('YE', 'Yemen'), ('ZM', 'Zambia'), ('ZW', 'Zimbabwe')], default=b'', max_length=2)),
- ('price', django_prices.models.PriceField(currency='USD', decimal_places=2, max_digits=12, verbose_name='price')),
+ ('price', django_prices.models.MoneyField(currency='USD', decimal_places=2, max_digits=12, verbose_name='price')),
('shipping_method', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='price_per_country', to='shipping.ShippingMethod')),
],
managers=[
diff --git a/saleor/shipping/migrations/0008_auto_20180108_0814.py b/saleor/shipping/migrations/0008_auto_20180108_0814.py
index f6b0b242b3..643238cb95 100644
--- a/saleor/shipping/migrations/0008_auto_20180108_0814.py
+++ b/saleor/shipping/migrations/0008_auto_20180108_0814.py
@@ -32,7 +32,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='shippingmethodcountry',
name='price',
- field=django_prices.models.PriceField(currency='USD', decimal_places=2, max_digits=12),
+ field=django_prices.models.MoneyField(currency='USD', decimal_places=2, max_digits=12),
),
migrations.AlterField(
model_name='shippingmethodcountry',
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index be7367ef8e..66a2e43b78 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -6,8 +6,8 @@ from django.db import models
from django.db.models import Q
from django.utils.translation import pgettext_lazy
from django_countries import countries
-from django_prices.models import PriceField
-from prices import PriceRange
+from django_prices.models import MoneyField
+from prices import TaxedMoney, TaxedMoneyRange
ANY_COUNTRY = ''
ANY_COUNTRY_DISPLAY = pgettext_lazy('Country choice', 'Rest of World')
@@ -37,9 +37,11 @@ class ShippingMethod(models.Model):
@property
def price_range(self):
- prices = [country.price for country in self.price_per_country.all()]
+ prices = [
+ country.get_total_price()
+ for country in self.price_per_country.all()]
if prices:
- return PriceRange(min(prices), max(prices))
+ return TaxedMoneyRange(min(prices), max(prices))
return None
@@ -75,7 +77,7 @@ class ShippingMethodCountry(models.Model):
country_code = models.CharField(
choices=COUNTRY_CODE_CHOICES, max_length=2, blank=True,
default=ANY_COUNTRY)
- price = PriceField(
+ price = MoneyField(
currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2)
shipping_method = models.ForeignKey(
ShippingMethod, related_name='price_per_country',
@@ -91,5 +93,5 @@ class ShippingMethodCountry(models.Model):
return '%s %s' % (
self.shipping_method, self.get_country_code_display())
- def get_total(self):
- return self.price
+ def get_total_price(self):
+ return TaxedMoney(net=self.price, gross=self.price)
diff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.py
index 054596bd1c..b5b40ff48a 100644
--- a/saleor/shipping/utils.py
+++ b/saleor/shipping/utils.py
@@ -1,4 +1,4 @@
-from prices import PriceRange
+from prices import TaxedMoney, TaxedMoneyRange
from .models import ShippingMethodCountry
@@ -11,6 +11,8 @@ def get_shipment_options(country_code):
shipping_methods = shipping_methods_qs.filter(country_code='')
if shipping_methods:
shipping_methods = shipping_methods.values_list('price', flat=True)
- return PriceRange(
- min_price=min(shipping_methods), max_price=max(shipping_methods))
- return None
+ min_amount = min(shipping_methods)
+ max_amount = max(shipping_methods)
+ return TaxedMoneyRange(
+ start=TaxedMoney(net=min_amount, gross=min_amount),
+ stop=TaxedMoney(net=max_amount, gross=max_amount))
diff --git a/templates/account/details.html b/templates/account/details.html
index 953e25b04a..0a24baf0aa 100644
--- a/templates/account/details.html
+++ b/templates/account/details.html
@@ -1,9 +1,8 @@
{% extends "base.html" %}
{% load i18n %}
{% load i18n_address_tags %}
+{% load prices_i18n %}
{% load staticfiles %}
-{% load gross from prices_i18n %}
-{% load discount_amount_for from prices %}
{% load status %}
{% load bootstrap_form from bootstrap4 %}
{% load bootstrap_pagination from bootstrap4 %}
@@ -76,7 +75,7 @@
{{ order.created }}
</div>
<div class="col-md-2 col-4">
- <span class="float-right">{% gross order.total html=True %}</span>
+ <span class="float-right">{{ order.total.gross|amount:'html' }}</span>
</div>
<div class="col-md-4 d-none d-md-block">
{% render_status order.status order.get_status_display %}
diff --git a/templates/cart/_subtotal_table.html b/templates/cart/_subtotal_table.html
index 725bbdfdb8..bdeb55d53f 100644
--- a/templates/cart/_subtotal_table.html
+++ b/templates/cart/_subtotal_table.html
@@ -1,6 +1,6 @@
{% load i18n %}
{% load price_range from price_ranges %}
-{% load gross from prices_i18n %}
+{% load prices_i18n %}
{% if shipping_required %}
<div class="table__row">
@@ -9,14 +9,14 @@
<h3>{% trans "Subtotal" context "Order subtotal" %}</h3>
</div>
<div class="col-4">
- <h3 class="text-right cart-subtotal" data-value="{% gross cart_total %}" {% if local_cart_total %}data-value-local="{% gross local_cart_total %}"{% endif %}>
+ <h3 class="text-right cart-subtotal" data-value="{{ cart_total.gross|amount }}" {% if local_cart_total is not None %}data-value-local="{{ local_cart_total.gross|amount }}"{% endif %}>
{% spaceless %}
- {% gross cart_total html=True %}
- {% if local_cart_total %}
+ {{ cart_total.gross|amount:'html' }}
+ {% if local_cart_total is not None and local_cart_total.gross %}
<br>
<small>
&asymp;
- {% gross local_cart_total html=True %}
+ {{ local_cart_total.gross|amount:'html' }}
</small>
{% endif %}
{% endspaceless %}
diff --git a/templates/cart/index.html b/templates/cart/index.html
index 5ea311c914..adcd54590b 100644
--- a/templates/cart/index.html
+++ b/templates/cart/index.html
@@ -1,6 +1,6 @@
{% extends "base.html" %}
-{% load gross from prices_i18n %}
{% load i18n %}
+{% load prices_i18n %}
{% load staticfiles %}
{% load get_thumbnail from product_images %}
@@ -63,7 +63,7 @@
<small class="cart__line__quantity-error text-danger"></small>
</div>
<div class="cart-item-price col-md-5 col-12" data-product-id="{{ line.variant.pk }}">
- <p class="text-right">{% gross line.get_total html=True %}</p>
+ <p class="text-right">{{ line.get_total.gross|amount:'html' }}</p>
</div>
</div>
</div>
diff --git a/templates/cart_dropdown.html b/templates/cart_dropdown.html
index 6abb15d199..5cb3c0cc69 100644
--- a/templates/cart_dropdown.html
+++ b/templates/cart_dropdown.html
@@ -1,6 +1,5 @@
{% load i18n %}
{% load staticfiles %}
-{% load gross from prices_i18n %}
{% load get_thumbnail from product_images %}
{% load placeholder %}
diff --git a/templates/checkout/details.html b/templates/checkout/details.html
index 8756cfb8eb..0dbbf73632 100644
--- a/templates/checkout/details.html
+++ b/templates/checkout/details.html
@@ -1,8 +1,8 @@
{% extends "base.html" %}
{% load i18n %}
+{% load prices_i18n %}
{% load staticfiles %}
-{% load gross net tax from prices_i18n %}
{% block title %}{% trans "Checkout" context "Checkout page title" %} — {{ block.super }}{% endblock %}
@@ -40,7 +40,7 @@
<span class="checkout__review__variant">{{ item.variant }}</span></p>
</div>
<div class="col-4">
- <p class="float-right">{% net item_price_total %}</p>
+ <p class="float-right">{{ item_price_total.net|amount }}</p>
</div>
</div>
{% endfor %}
@@ -50,17 +50,19 @@
<p>{% trans "Shipment" context "Order review section" %}</p>
</div>
<div class="col-4">
- <p class="float-right">{% if checkout.shipping_method %}
- {% net checkout.shipping_method.get_total %}
- {% else %}
- &mdash;
- {% endif %}</p>
+ <p class="float-right">
+ {% if checkout.shipping_method %}
+ {{ checkout.shipping_method.get_total_price.gross|amount }}
+ {% else %}
+ &mdash;
+ {% endif %}
+ </p>
</div>
</div>
<div class="row checkout__review__section">
<div class="col-12">
<h3>{% trans "Promo code" context "Order review section title" %}</h3>
- {% include "checkout/snippets/voucher_form.html" with discount=checkout.discount form=voucher_form %}
+ {% include "checkout/snippets/voucher_form.html" with checkout=checkout form=voucher_form %}
</div>
</div>
<div class="row checkout__review__section">
@@ -68,7 +70,7 @@
<h3>{% trans "Total" context "Order review section title" %}</h3>
</div>
<div class="col-4">
- <h3 class="float-right">{% gross total html=True %}</h3>
+ <h3 class="float-right">{{ total.gross|amount:'html' }}</h3>
</div>
</div>
</div>
diff --git a/templates/checkout/shipping_method.html b/templates/checkout/shipping_method.html
index ed5fe492b3..c53cccfb3d 100644
--- a/templates/checkout/shipping_method.html
+++ b/templates/checkout/shipping_method.html
@@ -1,7 +1,6 @@
{% extends "checkout/details.html" %}
{% load i18n %}
{% load i18n_address_tags %}
-{% load gross from prices_i18n %}
{% load bootstrap_form from bootstrap4 %}
{% block forms %}
diff --git a/templates/checkout/snippets/voucher_form.html b/templates/checkout/snippets/voucher_form.html
index 7f62fab474..2cd5565f3f 100644
--- a/templates/checkout/snippets/voucher_form.html
+++ b/templates/checkout/snippets/voucher_form.html
@@ -1,15 +1,14 @@
{% load bootstrap_field bootstrap_button from bootstrap4 %}
{% load trans from i18n %}
-{% load gross from prices_i18n %}
{% load discount_as_negative from voucher %}
{% if form %}
- {% if discount %}
+ {% if checkout.discount %}
<form action="{% url "checkout:remove-voucher" %}?next={{ request.path }}"
method="post"
class="float-left input-btn">
{% csrf_token %}
- <span>{{ discount.name }}</span>
+ <span>{{ checkout.discount_name }}</span>
<button type="submit"
class="btn btn-link btn-voucher-remove"
aria-label="{% trans "Remove" context "Checkout voucher form action" %}">
@@ -17,7 +16,7 @@
</button>
</form>
<div class="float-right">
- {% discount_as_negative discount %}
+ {% discount_as_negative checkout.discount %}
</div>
{% else %}
<form action="{{ request.path }}?next={{ request.path }}" method="post">
diff --git a/templates/dashboard/customer/detail.html b/templates/dashboard/customer/detail.html
index b33d463251..0a74cdf28b 100644
--- a/templates/dashboard/customer/detail.html
+++ b/templates/dashboard/customer/detail.html
@@ -110,7 +110,7 @@
{% render_status order.status order.get_status_display %}
</td>
<td class="right-align">
- {% gross order.total html=True %}
+ {{ order.total.gross|amount:'html' }}
</td>
</tr>
{% endfor %}
diff --git a/templates/dashboard/discount/voucher/list.html b/templates/dashboard/discount/voucher/list.html
index e81add7d7c..4d79a1ae11 100644
--- a/templates/dashboard/discount/voucher/list.html
+++ b/templates/dashboard/discount/voucher/list.html
@@ -92,7 +92,7 @@
</td>
<td class="right-align">
{% if voucher.limit %}
- {% gross voucher.limit html=True %}
+ {{ voucher.limit|amount:'html' }}
{% else %}
-
{% endif %}
diff --git a/templates/dashboard/index.html b/templates/dashboard/index.html
index a88c642fcd..54c9ee226b 100644
--- a/templates/dashboard/index.html
+++ b/templates/dashboard/index.html
@@ -48,7 +48,7 @@
{{ payment.order.user|default:_("Guest") }}
</td>
<td class="right-align">
- {% gross payment.get_total_price html=True %}
+ {{ payment.get_total_price.gross|amount:'html' }}
</td>
</tr>
{% endfor %}
@@ -113,7 +113,7 @@
{% render_status order.get_last_payment_status order.get_last_payment_status_display %}
</td>
<td class="right-align">
- {% gross order.total html=True %}
+ {{ order.total.gross|amount:'html' }}
</td>
</tr>
{% endfor %}
diff --git a/templates/dashboard/order/detail.html b/templates/dashboard/order/detail.html
index f6ba0b5e03..ecb01a150a 100644
--- a/templates/dashboard/order/detail.html
+++ b/templates/dashboard/order/detail.html
@@ -6,7 +6,7 @@
{% load materializecss %}
{% load status %}
{% load staticfiles %}
-{% load discount_amount_for from prices %}
+{% load voucher %}
{% block title %}
{{ order }} - {% trans "Orders" context "Dashboard orders list" %} - {{ block.super }}
@@ -159,7 +159,7 @@
</td>
<td class="right-align">
<strong>
- {% gross balance html=True %}
+ {{ balance.gross|amount:'html' }}
</strong>
</td>
</tr>
@@ -170,8 +170,8 @@
{% trans "Preauthorized amount" context "Order summary card header" %}
</td>
<td class="right-align">
- {% if preauthorized %}
- {% gross preauthorized html=True %}
+ {% if preauthorized.gross %}
+ {{ preauthorized.gross|amount:'html' }}
{% else %}
{% trans "N/A" context "Preauthorized amount not available" %}
{% endif %}
@@ -182,7 +182,7 @@
{% trans "Captured amount" context "Order summary card header" %}
</td>
<td class="right-align">
- {% gross captured html=True %}
+ {{ captured.gross|amount:'html' }}
</td>
</tr>
</tbody>
@@ -300,7 +300,7 @@
</span>
</td>
<td class="right-align">
- {% gross line.get_price_per_item html=True %}
+ {{ line.unit_price.gross|amount:'html' }}
</td>
<td class="right-align">
{% if group.can_edit_lines %}
@@ -337,7 +337,7 @@
{% endif %}
</td>
<td class="right-align">
- {% gross line.get_total html=True %}
+ {{ line.get_total.gross|amount:'html' }}
</td>
</tr>
{% endfor %}
@@ -386,7 +386,7 @@
{% trans "Grand total" context "Order totals header" %}
</td>
<td>
- {% gross order.total html=True %}
+ {{ order.total.gross|amount:'html' }}
</td>
</tr>
</tfoot>
@@ -396,7 +396,7 @@
{% trans "Subtotal" context "Order subtotal" %}
</td>
<td class="right-align">
- {% gross order.get_subtotal_without_voucher html=True %}
+ {{ order.get_subtotal.gross|amount:'html' }}
</td>
</tr>
<tr>
@@ -404,10 +404,10 @@
{% trans "Shipping" context "Order totals header" %}
</td>
<td class="right-align">
- {% gross order.shipping_price html=True %}
+ {{ order.shipping_price.gross|amount:'html' }}
</td>
</tr>
- {% if order.discount_amount.gross %}
+ {% if order.discount_amount %}
<tr>
<td>
<a class="dropdown-button" href="#" data-activates="voucher-actions" data-constrainwidth="false">
@@ -426,7 +426,7 @@
</ul>
</td>
<td class="right-align">
- {% gross order.discount|discount_amount_for:order.total html=True %}
+ {% discount_as_negative order.discount_amount html=True %}
</td>
</tr>
{% endif %}
diff --git a/templates/dashboard/order/list.html b/templates/dashboard/order/list.html
index 59a22056d8..8213d7d4f7 100644
--- a/templates/dashboard/order/list.html
+++ b/templates/dashboard/order/list.html
@@ -62,7 +62,7 @@
{% render_status order.get_last_payment_status order.get_last_payment_status_display %}
</td>
<td class="right-align">
- {% gross order.total html=True %}
+ {{ order.total.gross|amount:'html' }}
</td>
</tr>
{% endfor %}
diff --git a/templates/dashboard/order/modal/cancel_line.html b/templates/dashboard/order/modal/cancel_line.html
index 1c22da69a0..bfd43bd293 100644
--- a/templates/dashboard/order/modal/cancel_line.html
+++ b/templates/dashboard/order/modal/cancel_line.html
@@ -47,13 +47,13 @@
{{ item.product_sku }}
</td>
<td class="right-align">
- {% gross item.get_price_per_item html=True %}
+ {{ item.unit_price.gross|amount:'html' }}
</td>
<td class="right-align">
{{ item.quantity }}
</td>
<td class="right-align">
- {% gross item.get_total html=True %}
+ {{ item.get_total.gross|amount:'html' }}
</td>
</tr>
</tbody>
diff --git a/templates/dashboard/order/modal/capture.html b/templates/dashboard/order/modal/capture.html
index 1635e4bd60..458c7b55bf 100644
--- a/templates/dashboard/order/modal/capture.html
+++ b/templates/dashboard/order/modal/capture.html
@@ -19,7 +19,7 @@
{% trans "Before this action:" context "Modal capture payment title" %}
<ul class="list">
<li class="list-item">{% trans "Order total:" context "Modal capture payment list title" %}
- {% gross payment.order.total html=True %}
+ {{ payment.order.total.gross|amount:'html' }}
</li>
<li class="list-item">{% trans "Captured amount:" context "Modal capture payment list title" %}
{{ captured|currencyfmt:currency }}
diff --git a/templates/dashboard/order/modal/refund.html b/templates/dashboard/order/modal/refund.html
index 2a4ab71555..965c9b95b8 100644
--- a/templates/dashboard/order/modal/refund.html
+++ b/templates/dashboard/order/modal/refund.html
@@ -20,7 +20,7 @@
{% trans "Before this action:" context "Modal refund payment title" %}
<ul class="list">
<li class="list-item">{% trans "Order total:" context "Modal refund payment list title" %}
- {% gross payment.order.total html=True %}
+ {{ payment.order.total.gross|amount:'html' }}
</li>
<li class="list-item">{% trans "Captured amount:" context "Modal refund payment list title" %}
{{ captured|currencyfmt:currency }}
diff --git a/templates/dashboard/order/pdf/invoice.html b/templates/dashboard/order/pdf/invoice.html
index 9d241ecb41..443e134fa4 100644
--- a/templates/dashboard/order/pdf/invoice.html
+++ b/templates/dashboard/order/pdf/invoice.html
@@ -1,6 +1,6 @@
{% load i18n static %}
{% load prices_i18n %}
-{% load discount_amount_for from prices %}
+{% load discount_as_negative from voucher %}
{% load render_bundle from webpack_loader %}
<html>
@@ -90,13 +90,13 @@
{{ item.product_sku }}
</td>
<td class="right-align">
- {% gross item.get_price_per_item html=True %}
+ {{ item.unit_price.gross|amount:'html' }}
</td>
<td class="right-align">
{{ item.quantity }}
</td>
<td class="right-align">
- {% gross item.get_total html=True %}
+ {{ item.get_total.gross|amount:'html' }}
</td>
</tr>
{% endfor %}
@@ -123,7 +123,7 @@
{% trans "Subtotal" context "Order subtotal price" %}
</td>
<td class="right-align">
- {% gross order.get_subtotal_without_voucher html=True %}
+ {{ order.get_subtotal.gross|amount:'html' }}
</td>
</tr>
<tr>
@@ -131,16 +131,16 @@
{% trans "Shipping total" context "Order total shipping price header" %}
</td>
<td class="right-align">
- {% gross order.shipping_price html=True %}
+ {{ order.shipping_price.gross|amount:'html' }}
</td>
</tr>
- {% if order.voucher %}
+ {% if order.discount_amount %}
<tr>
<td>
- {% trans "Voucher" context "Order voucher header" %} {{ order.voucher }}
+ {% trans "Voucher" context "Order voucher header" %} {{ order.discount_name }}
</td>
<td class="right-align">
- {% gross order.discount|discount_amount_for:order.total html=True %}
+ {% discount_as_negative order.discount_amount html=True %}
</td>
</tr>
{% endif %}
@@ -151,7 +151,7 @@
{% trans "Grand total" context "Order total price header" %}
</td>
<td class="right-align">
- {% gross order.total html=True %}
+ {{ order.total.gross|amount:'html' }}
</td>
</tr>
</tfoot>
diff --git a/templates/dashboard/order/pdf/packing_slip.html b/templates/dashboard/order/pdf/packing_slip.html
index 4074b49e29..299aa64196 100644
--- a/templates/dashboard/order/pdf/packing_slip.html
+++ b/templates/dashboard/order/pdf/packing_slip.html
@@ -1,4 +1,3 @@
-{% load discount_amount_for from prices %}
{% load i18n static %}
{% load prices_i18n %}
{% load shop %}
diff --git a/templates/dashboard/product/_stock_table.html b/templates/dashboard/product/_stock_table.html
index 65b1bf78f3..96b9450999 100644
--- a/templates/dashboard/product/_stock_table.html
+++ b/templates/dashboard/product/_stock_table.html
@@ -18,9 +18,9 @@
<td class="wide">{{ stock_item.location }}</td>
<td>{{ stock_item.quantity }}</td>
<td>{{ stock_item.quantity_allocated }}</td>
- <td class="right-align">{% if stock_item.cost_price %}{% gross stock_item.cost_price %}{% else %}-{% endif %}</td>
+ <td class="right-align">{% if stock_item.cost_price %}{{ stock_item.cost_price|amount }}{% else %}-{% endif %}</td>
<td class="right-align">
- {% margin_for_variant stock=stock_item as margin%}
+ {% margin_for_variant stock=stock_item as margin %}
{% if margin %}
{{ margin }}%
{% else %}
diff --git a/templates/dashboard/product/detail.html b/templates/dashboard/product/detail.html
index 0d4277af27..01d7107a5a 100644
--- a/templates/dashboard/product/detail.html
+++ b/templates/dashboard/product/detail.html
@@ -42,20 +42,16 @@
<p class="text-padding">{% trans "Sale price" context "Product field" %}</p>
</div>
<div class="col s7 m6">
- {% with sale_price.min_price as min_price %}
- {% with sale_price.max_price as max_price %}
- <p class="text-padding right-align">{% gross min_price %} - {% gross max_price %}</p>
- {% endwith %}
+ {% with sale_price as price_range %}
+ <p class="text-padding right-align">{{ price_range.start.gross|amount }} - {{ price_range.stop.gross|amount }}</p>
{% endwith %}
</div>
<div class="col s5 m6">
<p class="text-padding">{% trans "Purchase cost" context "Product field" %}</p>
</div>
<div class="col s7 m6">
- {% with purchase_cost.min_price as min_price %}
- {% with purchase_cost.max_price as max_price %}
- <p class="text-padding right-align">{% gross min_price %} - {% gross max_price %}</p>
- {% endwith %}
+ {% with purchase_cost as price_range %}
+ <p class="text-padding right-align">{{ price_range.start.gross|amount }} - {{ price_range.stop.gross|amount }}</p>
{% endwith %}
</div>
<div class="col s5 m6">
@@ -114,7 +110,7 @@
<td>{{ variant.sku }}</td>
<td>{{ variant }}</td>
<td class="wide">{% render_variant_availability_status variant %}</td>
- <td class="right-align">{% gross variant.get_price_per_item %}</td>
+ <td class="right-align">{{ variant.get_price_per_item.gross|amount }}</td>
<td class="right-align">
{% margins_for_variant variant=variant as margins %}
{% if margins|length > 1 %}
diff --git a/templates/dashboard/product/list.html b/templates/dashboard/product/list.html
index 772eee82d2..76164e5202 100644
--- a/templates/dashboard/product/list.html
+++ b/templates/dashboard/product/list.html
@@ -83,7 +83,7 @@
{{ product.name }}
</td>
<td>
- {% gross product.price html=True %}
+ {{ product.price|amount:'html' }}
</td>
</tr>
{% endfor %}
diff --git a/templates/dashboard/product/product_variant/detail.html b/templates/dashboard/product/product_variant/detail.html
index b18b316f8e..f51041f2c1 100644
--- a/templates/dashboard/product/product_variant/detail.html
+++ b/templates/dashboard/product/product_variant/detail.html
@@ -53,17 +53,19 @@
<p class="text-padding">{% trans "Sale price" context "Dashboard variant details view" %}</p>
</div>
<div class="col s7 m6">
- <p class="text-padding right-align">{% gross variant.get_price_per_item %}</p>
+ <p class="text-padding right-align">{{ variant.get_price_per_item.gross|amount }}</p>
</div>
<div class="col s5 m6">
<p class="text-padding">{% trans "Cost price range" context "Dashboard variant details view" %}</p>
</div>
<div class="col s7 m6">
<p class="text-padding right-align">
- {% if costs|length > 1 %}
- {% gross costs|first %} - {% gross costs|last %}
- {% elif costs|length == 1 %}
- {% gross costs|first %}
+ {% if costs %}
+ {% if costs.min != costs.max %}
+ {{ costs.min.gross|amount }} - {{ costs.max.gross|amount }}
+ {% else %}
+ {{ costs.min.gross|amount }}
+ {% endif %}
{% else %}
-
{% endif %}
diff --git a/templates/dashboard/search/results.html b/templates/dashboard/search/results.html
index 23be97d951..75fd54890a 100644
--- a/templates/dashboard/search/results.html
+++ b/templates/dashboard/search/results.html
@@ -35,7 +35,7 @@
</span>
<p class="list-item-price">
<small>
- {% gross product.price html=True %}
+ {{ product.price|amount:'html' }}
</small>
</p>
</a>
diff --git a/templates/dashboard/shipping/detail.html b/templates/dashboard/shipping/detail.html
index 2b319a05e0..b6f6bba7c5 100644
--- a/templates/dashboard/shipping/detail.html
+++ b/templates/dashboard/shipping/detail.html
@@ -94,7 +94,7 @@
{% for country in method_countries %}
<tr>
<td>{{ country.get_country_code_display }}</td>
- <td>{% gross country.price %}</td>
+ <td>{{ country.price|amount:'html' }}</td>
<td class="right-align">
<a href="{% url 'dashboard:shipping-method-country-edit' shipping_method_pk=shipping_method.pk country_pk=country.pk %}" class="btn-flat waves-effect">
{% trans 'Edit' context 'Attribute choice value edit action' %}
diff --git a/templates/dashboard/shipping/list.html b/templates/dashboard/shipping/list.html
index b8a09a8269..2676afd9a6 100644
--- a/templates/dashboard/shipping/list.html
+++ b/templates/dashboard/shipping/list.html
@@ -60,10 +60,10 @@
<td>
{% if not method.price_range %}
-
- {% elif method.price_range.min_price == method.price_range.max_price %}
- {% gross method.price_range.min_price html=True %}
+ {% elif method.price_range.start == method.price_range.stop %}
+ {{ method.price_range.start.gross|amount:'html' }}
{% else %}
- {% gross method.price_range.min_price html=True %}&ndash;{% gross method.price_range.max_price html=True %}
+ {{ method.price_range.start.gross|amount:'html' }}&ndash;{{ method.price_range.stop.gross|amount:'html' }}
{% endif %}
</td>
<td>
diff --git a/templates/order/_ordered_items_table.html b/templates/order/_ordered_items_table.html
index 0eb841ed3e..0642778cc9 100644
--- a/templates/order/_ordered_items_table.html
+++ b/templates/order/_ordered_items_table.html
@@ -1,7 +1,6 @@
{% load i18n %}
{% load i18n_address_tags %}
-{% load gross from prices_i18n %}
-{% load discount_amount_for from prices %}
+{% load amount from prices_i18n %}
{% load product_first_image from product_images %}
{% load discount_as_negative from voucher %}
{% load placeholder %}
@@ -66,7 +65,7 @@
<p class="float-right">x {{ line.quantity }}</p>
</div>
<div class="col-md-6 col-12">
- <p class="float-right">{% gross line.get_total html=True %}</p>
+ <p class="float-right">{{ line.get_total.gross|amount:'html' }}</p>
</div>
</div>
</div>
@@ -104,7 +103,7 @@
</p>
</div>
<div class="col-4">
- <p class="float-right">{% gross order.shipping_price html=True %}</p>
+ <p class="float-right">{{ order.shipping_price.gross|amount:'html' }}</p>
</div>
</div>
</div>
@@ -117,7 +116,9 @@
<p>{{ order.discount_name }}</p>
</div>
<div class="col-4">
- <p class="float-right">{% discount_as_negative order.discount %}</p>
+ <p class="float-right">
+ {% discount_as_negative order.discount_amount html=True %}
+ </p>
</div>
</div>
</div>
@@ -131,7 +132,7 @@
</div>
</div>
<div class="col-4">
- <p class="float-right">{% gross order.total html=True %}</p>
+ <p class="float-right">{{ order.total.gross|amount:'html' }}</p>
</div>
</div>
</div>
diff --git a/templates/order/payment.html b/templates/order/payment.html
index 137bf1f1ef..1b68fa4a70 100644
--- a/templates/order/payment.html
+++ b/templates/order/payment.html
@@ -1,8 +1,6 @@
{% extends "base.html" %}
{% load bootstrap_form from bootstrap4 %}
-{% load gross from prices_i18n %}
-{% load discount_amount_for from prices %}
{% load i18n %}
{% load staticfiles %}
diff --git a/templates/product/_items.html b/templates/product/_items.html
index e13d6b39d3..664dba49f2 100644
--- a/templates/product/_items.html
+++ b/templates/product/_items.html
@@ -21,7 +21,7 @@
{% if availability.available %}
{% price_range availability.price_range %}
{% if availability.discount %}
- {% if availability.price_range_undiscounted.min_price != availability.price_range.min_price %}
+ {% if availability.price_range_undiscounted.start != availability.price_range.start %}
<div class="product-list__sale">
<svg data-src="{% static "images/sale-bg.svg" %}" />
<span class="product-list__sale__text">
diff --git a/templates/product/_price_range.html b/templates/product/_price_range.html
index d79ac36e05..1fcda92ab8 100644
--- a/templates/product/_price_range.html
+++ b/templates/product/_price_range.html
@@ -1,8 +1,8 @@
{% load i18n %}
-{% load gross from prices_i18n %}
+{% load prices_i18n %}
<span>
<span>
- {% if price_range.min_price != price_range.max_price %}{% trans "from" context "product price range" %} {% endif %}{% gross price_range.min_price html=True %}
+ {% if price_range.start != price_range.stop %}{% trans "from" context "product price range" %} {% endif %}{{ price_range.start.gross|amount:'html' }}
</span>
</span>
diff --git a/templates/product/details.html b/templates/product/details.html
index acc088c1d9..d2946e3925 100644
--- a/templates/product/details.html
+++ b/templates/product/details.html
@@ -2,8 +2,8 @@
{% load bootstrap_field from bootstrap4 %}
{% load i18n %}
-{% load gross from prices_i18n %}
{% load markdown from markdown %}
+{% load prices_i18n %}
{% load price_range from price_ranges %}
{% load staticfiles %}
{% load get_thumbnail product_first_image from product_images %}
@@ -124,13 +124,13 @@
<h2 class="product__info__price">
<span>{% price_range availability.price_range %}</span>
{% if availability.discount %}
- <small class="product__info__price__undiscounted">{% gross availability.price_range_undiscounted.min_price html=True %}</small>
+ <small class="product__info__price__undiscounted">{{ availability.price_range_undiscounted.start.gross|amount:'html' }}</small>
{% endif %}
{% if availability.price_range_local_currency %}
<br>
<small class="text-info">
&asymp;
- {% gross availability.price_range_local_currency.min_price html=True %}
+ {{ availability.price_range_local_currency.start.gross|amount:'html' }}
</small>
{% endif %}
</h2>
diff --git a/templates/templated_email/source/order/confirm_order.email b/templates/templated_email/source/order/confirm_order.email
index ff979c6fa8..ded1bed49a 100644
--- a/templates/templated_email/source/order/confirm_order.email
+++ b/templates/templated_email/source/order/confirm_order.email
@@ -1,5 +1,5 @@
{% load i18n %}
-{% load gross from prices_i18n %}
+{% load prices_i18n %}
{% block subject %}
{% trans "Order details" context "Order confirmation e-mail subject" %}
@@ -12,12 +12,12 @@ Hi!
Thank you for your order. Below is the list of ordered products. To see your payment details please visit:
{{ url }}{% endblocktrans %}
{% for group in order.groups.all %}{% for line in group.lines.all %}
-{{ line.quantity }} x {{ line.product_name }}, {% gross line.get_total %}
+{{ line.quantity }} x {{ line.product_name }}, {{ line.get_total.gross|amount }}
{% endfor %}{% endfor %}
{% trans "Order summary" context "Order confirmation e-mail table header" %}:
-{% trans "Subtotal" context "Order confirmation e-mail table header" %}: {% gross order.get_subtotal_without_voucher %}
-{% trans "Shipping" context "Order confirmation e-mail table header" %}: {% gross order.shipping_price %}
-{% trans "Total" context "Order confirmation e-mail table header" %}: {% gross order.total %}
+{% trans "Subtotal" context "Order confirmation e-mail table header" %}: {{ order.get_subtotal.gross|amount }}
+{% trans "Shipping" context "Order confirmation e-mail table header" %}: {{ order.shipping_price.gross|amount }}
+{% trans "Total" context "Order confirmation e-mail table header" %}: {{ order.total.gross|amount }}
{% trans "Billing address" context "Order confirmation e-mail billing address" %}
{{ order.billing_address }}
diff --git a/templates/templated_email/source/order/partials/_order_lines.mjml b/templates/templated_email/source/order/partials/_order_lines.mjml
index 2061d342fd..93a71de535 100644
--- a/templates/templated_email/source/order/partials/_order_lines.mjml
+++ b/templates/templated_email/source/order/partials/_order_lines.mjml
@@ -1,7 +1,7 @@
<mj-section css-class="no-display">
<mj-column>
<mj-text>
- {% load gross from prices_i18n %}
+ {% load prices_i18n %}
</mj-text>
</mj-column>
</mj-section>
@@ -14,7 +14,7 @@
{% trans "Subtotal" context "E-mail order lines summary table" %}
</td>
<td style="text-align: right;">
- {% gross order.get_subtotal_without_voucher html=True %}
+ {{ order.get_subtotal.gross|amount:'html' }}
</td>
</tr>
<tr>
@@ -22,7 +22,7 @@
{% trans "Shipping" context "E-mail order lines summary table" %}
</td>
<td style="text-align: right;">
- {% gross order.shipping_price html=True %}
+ {{ order.shipping_price.gross|amount:'html' }}
</td>
</tr>
<tr>
@@ -30,7 +30,7 @@
<strong>{% trans "Total" context "E-mail order lines summary table" %}</strong>
</td>
<td style="text-align: right;">
- <strong>{% gross order.total html=True %}</strong>
+ <strong>{{ order.total.gross|amount:'html' }}</strong>
</td>
</tr>
</tfoot>
@@ -49,9 +49,9 @@
<td>{{ line.product_name }}</td>
<td style="text-align: right;">{{ line.quantity }}</td>
<td style="text-align: right;">
- {% gross line.get_price_per_item html=True %}
+ {{ line.unit_price.gross|amount:'html' }}
</td>
- <td style="text-align: right;">{% gross line.get_total %}</td>
+ <td style="text-align: right;">{{ line.get_total.gross|amount }}</td>
</tr>
{% endfor %}
{% endfor %}
diff --git a/tests/conftest.py b/tests/conftest.py
index 027a0c1797..a2293e8783 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -9,7 +9,7 @@ from django.core.files import File
from django.core.files.uploadedfile import SimpleUploadedFile
from django.utils.encoding import smart_text
from PIL import Image
-from prices import Price
+from prices import Money
from saleor.account.models import Address, User
from saleor.cart import utils
@@ -241,7 +241,7 @@ def product_in_stock(product_type, default_category):
attributes = {smart_text(product_attr.pk): smart_text(attr_value.pk)}
product = Product.objects.create(
- name='Test product', price=Decimal('10.00'),
+ name='Test product', price=Money('10.00', currency='USD'),
product_type=product_type, attributes=attributes,
category=default_category)
@@ -256,14 +256,14 @@ def product_in_stock(product_type, default_category):
warehouse_2 = StockLocation.objects.create(name='Warehouse 2')
warehouse_3 = StockLocation.objects.create(name='Warehouse 3')
Stock.objects.create(
- variant=variant, cost_price=1, quantity=5, quantity_allocated=5,
- location=warehouse_1)
+ variant=variant, cost_price=Money('1.00', currency='USD'),
+ quantity=5, quantity_allocated=5, location=warehouse_1)
Stock.objects.create(
- variant=variant, cost_price=100, quantity=5, quantity_allocated=5,
- location=warehouse_2)
+ variant=variant, cost_price=Money('100.00', currency='USD'),
+ quantity=5, quantity_allocated=5, location=warehouse_2)
Stock.objects.create(
- variant=variant, cost_price=10, quantity=5, quantity_allocated=0,
- location=warehouse_3)
+ variant=variant, cost_price=Money('10.00', currency='USD'),
+ quantity=5, quantity_allocated=0, location=warehouse_3)
return product
@@ -273,7 +273,7 @@ def product_without_shipping(default_category):
name='Type with no shipping', has_variants=False,
is_shipping_required=False)
product = Product.objects.create(
- name='Test product', price=Decimal('10.00'),
+ name='Test product', price=Money('10.00', currency='USD'),
product_type=product_type, category=default_category)
ProductVariant.objects.create(product=product, sku='SKU_B')
return product
@@ -286,17 +286,17 @@ def product_list(product_type, default_category):
attributes = {smart_text(product_attr.pk): smart_text(attr_value.pk)}
product_1 = Product.objects.create(
- name='Test product 1', price=Decimal('10.00'),
+ name='Test product 1', price=Money('10.00', currency='USD'),
product_type=product_type, attributes=attributes, is_published=True,
category=default_category)
product_2 = Product.objects.create(
- name='Test product 2', price=Decimal('20.00'),
+ name='Test product 2', price=Money('20.00', currency='USD'),
product_type=product_type, attributes=attributes, is_published=False,
category=default_category)
product_3 = Product.objects.create(
- name='Test product 3', price=Decimal('20.00'),
+ name='Test product 3', price=Money('20.00', currency='USD'),
product_type=product_type, attributes=attributes, is_published=True,
category=default_category)
@@ -307,7 +307,9 @@ def product_list(product_type, default_category):
def order_list(admin_user, billing_address):
data = {
'billing_address': billing_address, 'user': admin_user,
- 'user_email': admin_user.email, 'total': Price(123, currency='USD')}
+ 'user_email': admin_user.email,
+ 'total_net': Money(123, currency='USD'),
+ 'total_gross': Money(123, currency='USD')}
order = Order.objects.create(**data)
order1 = Order.objects.create(**data)
order2 = Order.objects.create(**data)
@@ -339,7 +341,7 @@ def product_with_image(product_in_stock, product_image):
@pytest.fixture
def unavailable_product(product_type, default_category):
product = Product.objects.create(
- name='Test product', price=Decimal('10.00'),
+ name='Test product', price=Money('10.00', currency='USD'),
product_type=product_type, is_published=False,
category=default_category)
return product
@@ -348,7 +350,7 @@ def unavailable_product(product_type, default_category):
@pytest.fixture
def product_with_images(product_type, default_category):
product = Product.objects.create(
- name='Test product', price=Decimal('10.00'),
+ name='Test product', price=Money('10.00', currency='USD'),
product_type=product_type, category=default_category)
file_mock_0 = MagicMock(spec=File, name='FileMock0')
file_mock_0.name = 'image0.jpg'
@@ -373,7 +375,7 @@ def voucher(db): # pylint: disable=W0613
def order_with_lines(order, product_type, default_category):
group = DeliveryGroup.objects.create(order=order)
product = Product.objects.create(
- name='Test product', price=Decimal('10.00'),
+ name='Test product', price=Money('10.00', currency='USD'),
product_type=product_type, category=default_category)
OrderLine.objects.create(
@@ -386,7 +388,7 @@ def order_with_lines(order, product_type, default_category):
unit_price_net=Decimal('10.00'),
unit_price_gross=Decimal('10.00'))
product = Product.objects.create(
- name='Test product 2', price=Decimal('20.00'),
+ name='Test product 2', price=Money('20.00', currency='USD'),
product_type=product_type, category=default_category)
OrderLine.objects.create(
@@ -399,7 +401,7 @@ def order_with_lines(order, product_type, default_category):
unit_price_net=Decimal('20.00'),
unit_price_gross=Decimal('20.00'))
product = Product.objects.create(
- name='Test product 3', price=Decimal('30.00'),
+ name='Test product 3', price=Money('30.00', currency='USD'),
product_type=product_type, category=default_category)
OrderLine.objects.create(
@@ -420,13 +422,13 @@ def order_with_lines(order, product_type, default_category):
def order_with_lines_and_stock(order, product_type, default_category):
group = DeliveryGroup.objects.create(order=order)
product = Product.objects.create(
- name='Test product', price=Decimal('10.00'),
+ name='Test product', price=Money('10.00', currency='USD'),
product_type=product_type, category=default_category)
variant = ProductVariant.objects.create(product=product, sku='SKU_A')
warehouse = StockLocation.objects.create(name='Warehouse 1')
stock = Stock.objects.create(
- variant=variant, cost_price=1, quantity=5, quantity_allocated=3,
- location=warehouse)
+ variant=variant, cost_price=Money(1, currency='USD'),
+ quantity=5, quantity_allocated=3, location=warehouse)
OrderLine.objects.create(
delivery_group=group,
product=product,
@@ -439,12 +441,12 @@ def order_with_lines_and_stock(order, product_type, default_category):
stock=stock,
stock_location=stock.location.name)
product = Product.objects.create(
- name='Test product 2', price=Decimal('20.00'),
+ name='Test product 2', price=Money('20.00', currency='USD'),
product_type=product_type, category=default_category)
variant = ProductVariant.objects.create(product=product, sku='SKU_B')
stock = Stock.objects.create(
- variant=variant, cost_price=2, quantity=2, quantity_allocated=2,
- location=warehouse)
+ variant=variant, cost_price=Money(2, currency='USD'),
+ quantity=2, quantity_allocated=2, location=warehouse)
OrderLine.objects.create(
delivery_group=group,
product=product,
@@ -467,8 +469,8 @@ def order_with_variant_from_different_stocks(order_with_lines_and_stock):
variant = ProductVariant.objects.get(sku=line.product_sku)
warehouse_2 = StockLocation.objects.create(name='Warehouse 2')
stock = Stock.objects.create(
- variant=variant, cost_price=1, quantity=5, quantity_allocated=2,
- location=warehouse_2)
+ variant=variant, cost_price=Money(1, currency='USD'),
+ quantity=5, quantity_allocated=2, location=warehouse_2)
OrderLine.objects.create(
delivery_group=line.delivery_group,
product=variant.product,
@@ -482,9 +484,8 @@ def order_with_variant_from_different_stocks(order_with_lines_and_stock):
stock_location=stock.location.name)
warehouse_2 = StockLocation.objects.create(name='Warehouse 3')
Stock.objects.create(
- variant=variant, cost_price=1, quantity=5, quantity_allocated=0,
- location=warehouse_2)
- recalculate_order(order_with_lines_and_stock)
+ variant=variant, cost_price=Money(1, currency='USD'),
+ quantity=5, quantity_allocated=0, location=warehouse_2)
return order_with_lines_and_stock
@@ -492,13 +493,13 @@ def order_with_variant_from_different_stocks(order_with_lines_and_stock):
def delivery_group(order, product_type, default_category):
group = DeliveryGroup.objects.create(order=order)
product = Product.objects.create(
- name='Test product', price=Decimal('10.00'),
+ name='Test product', price=Money('10.00', currency='USD'),
product_type=product_type, category=default_category)
variant = ProductVariant.objects.create(product=product, sku='SKU_A')
warehouse = StockLocation.objects.create(name='Warehouse 2')
stock = Stock.objects.create(
- variant=variant, cost_price=1, quantity=5, quantity_allocated=3,
- location=warehouse)
+ variant=variant, cost_price=Money(1, currency='USD'),
+ quantity=5, quantity_allocated=3, location=warehouse)
OrderLine.objects.create(
delivery_group=group,
product=product,
diff --git a/tests/dashboard/test_chips.py b/tests/dashboard/test_chips.py
index 38ff9314e9..b7e7ab287b 100644
--- a/tests/dashboard/test_chips.py
+++ b/tests/dashboard/test_chips.py
@@ -5,7 +5,7 @@ from saleor.dashboard.templatetags.chips import (
CHIPS_PATTERN, handle_default, handle_multiple_choice,
handle_multiple_model_choice, handle_nullboolean, handle_range,
handle_single_choice, handle_single_model_choice)
-from saleor.dashboard.widgets import PriceRangeWidget
+from saleor.dashboard.widgets import MoneyRangeWidget
from saleor.product.models import Category, Product
@@ -45,7 +45,7 @@ class ModelMultipleChoiceFieldFilterSet(django_filters.FilterSet):
class RangeFieldFilterSet(django_filters.FilterSet):
price = django_filters.RangeFilter(
- label='Price', name='price', widget=PriceRangeWidget)
+ label='Price', name='price', widget=MoneyRangeWidget)
def test_char_field_chip():
diff --git a/tests/dashboard/test_discount.py b/tests/dashboard/test_discount.py
new file mode 100644
index 0000000000..38a519bc3d
--- /dev/null
+++ b/tests/dashboard/test_discount.py
@@ -0,0 +1,44 @@
+from datetime import date
+from decimal import Decimal
+
+from django.urls import reverse
+from prices import Money
+
+from saleor.discount import DiscountValueType, VoucherType
+from saleor.discount.models import Sale, Voucher
+
+
+def test_sales_list(admin_client, sale):
+ url = reverse('dashboard:sale-list')
+ response = admin_client.get(url)
+ assert response.status_code == 200
+
+
+def test_vouchers_list(admin_client, voucher):
+ url = reverse('dashboard:voucher-list')
+ response = admin_client.get(url)
+ assert response.status_code == 200
+
+
+def test_voucher_shipping_add(admin_client):
+ assert len(Voucher.objects.all()) == 0
+ url = reverse('dashboard:voucher-add')
+ data = {
+ 'code': 'TESTVOUCHER', 'name': 'Test Voucher',
+ 'start_date': '2018-01-01', 'end_date': '2018-06-01',
+ 'type': VoucherType.SHIPPING, 'discount_value': '15.99',
+ 'discount_value_type': DiscountValueType.FIXED,
+ 'shipping-limit': '59.99'}
+ response = admin_client.post(url, data, follow=True)
+ assert response.status_code == 200
+ assert len(Voucher.objects.all()) == 1
+
+ voucher = Voucher.objects.all()[0]
+ assert voucher.type == VoucherType.SHIPPING
+ assert voucher.code == data['code']
+ assert voucher.name == data['name']
+ assert voucher.start_date == date(2018, 1, 1)
+ assert voucher.end_date == date(2018, 6, 1)
+ assert voucher.discount_value_type == DiscountValueType.FIXED
+ assert voucher.discount_value == Decimal('15.99')
+ assert voucher.limit == Money('59.99', currency='USD')
diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.py
index c0e5341f00..7ee2fd3a90 100644
--- a/tests/dashboard/test_order.py
+++ b/tests/dashboard/test_order.py
@@ -4,7 +4,9 @@ from unittest.mock import patch
import pytest
from django.urls import reverse
from django_fsm import TransitionNotAllowed
-from prices import Price
+from payments import FraudStatus, PaymentStatus
+from prices import Money, TaxedMoney
+
from tests.utils import get_redirect_location, get_url_path
from saleor.cart.models import Cart
@@ -19,6 +21,51 @@ from saleor.order.utils import (
from saleor.product.models import ProductVariant, Stock, StockLocation
+def test_view_capture_order_payment(admin_client, order_with_lines_and_stock):
+ order = order_with_lines_and_stock
+ payment = order.payments.create(
+ variant='default', status=PaymentStatus.PREAUTH,
+ fraud_status=FraudStatus.ACCEPT, currency='USD', total='100.0')
+
+ url = reverse(
+ 'dashboard:capture-payment', kwargs={
+ 'order_pk': order.pk,
+ 'payment_pk': payment.pk})
+ response = admin_client.get(url)
+ assert response.status_code == 200
+
+ response = admin_client.post(
+ url, {'csrfmiddlewaretoken': 'hello', 'amount': '20.00'})
+ assert response.status_code == 302
+ assert order.payments.last().get_captured_price() == TaxedMoney(
+ net=Money(20, 'USD'), gross=Money(20, 'USD'))
+
+
+def test_view_refund_order_payment(admin_client, order_with_lines_and_stock):
+ order = order_with_lines_and_stock
+ payment = order.payments.create(
+ variant='default', status=PaymentStatus.CONFIRMED,
+ fraud_status=FraudStatus.ACCEPT, currency='USD', total='100.0',
+ captured_amount='100.0')
+
+ url = reverse(
+ 'dashboard:refund-payment', kwargs={
+ 'order_pk': order.pk,
+ 'payment_pk': payment.pk})
+ response = admin_client.get(url)
+ assert response.status_code == 200
+
+ response = admin_client.post(
+ url, {'csrfmiddlewaretoken': 'hello', 'amount': '20.00'})
+ assert response.status_code == 302
+ assert order.payments.last().get_captured_price() == TaxedMoney(
+ net=Money(80, 'USD'), gross=Money(80, 'USD'))
+
+
@pytest.mark.integration
@pytest.mark.django_db
def test_view_cancel_order_line(admin_client, order_with_lines_and_stock):
@@ -631,7 +678,8 @@ def test_process_new_delivery_group_with_discount(
group.save()
line = group.lines.first()
- assert line.get_price_per_item() == Price(currency="USD", net=5)
+ assert line.unit_price == TaxedMoney(
+ net=Money('5', 'USD'), gross=Money('5', 'USD'))
def test_cant_process_cancelled_delivery_group(
diff --git a/tests/dashboard/test_product.py b/tests/dashboard/test_product.py
index 45f7d6baa7..0e122d99eb 100644
--- a/tests/dashboard/test_product.py
+++ b/tests/dashboard/test_product.py
@@ -48,7 +48,7 @@ def test_stock_record_update_works(admin_client, product_in_stock):
'stock_pk': stock.pk})
admin_client.post(url, {
'variant': stock.variant_id, 'location': stock.location.id,
- 'cost_price': stock.cost_price.net,
+ 'cost_price': stock.cost_price.amount,
'quantity': quantity + 5})
new_stock = variant.stock.get(pk=stock.pk)
assert new_stock.quantity == quantity + 5
@@ -143,7 +143,7 @@ def test_change_attributes_in_product_form(
new_color = color_value.pk
data = {
'name': product.name,
- 'price': product.price.gross,
+ 'price': product.price.amount,
'category': product.category.pk,
'description': 'description',
'attribute-author': new_author,
@@ -668,7 +668,7 @@ def test_assign_collection_to_product(product_in_stock):
collection = Collection.objects.create(name='test_collections')
data = {
'name': product.name,
- 'price': product.price.gross,
+ 'price': product.price.amount,
'category': product.category.pk,
'description': 'description',
'collections': [collection.pk]}
diff --git a/tests/dashboard/test_shipping.py b/tests/dashboard/test_shipping.py
index 9f4eab4dc6..2b76131486 100644
--- a/tests/dashboard/test_shipping.py
+++ b/tests/dashboard/test_shipping.py
@@ -1,4 +1,5 @@
from django.urls import reverse
+from prices import Money
from saleor.shipping.models import ShippingMethod, ShippingMethodCountry
@@ -79,7 +80,7 @@ def test_shipping_method_country_add_not_valid(admin_client, shipping_method):
def test_shipping_method_country_edit(admin_client, shipping_method):
assert len(ShippingMethodCountry.objects.all()) == 1
country = shipping_method.price_per_country.all()[0]
- assert country.price.gross == 10
+ assert country.price == Money(10, 'USD')
url = reverse('dashboard:shipping-method-country-edit',
kwargs={'shipping_method_pk': shipping_method.pk,
'country_pk': country.pk})
@@ -88,7 +89,9 @@ def test_shipping_method_country_edit(admin_client, shipping_method):
response = admin_client.post(url, data, follow=True)
assert response.status_code == 200
assert len(ShippingMethodCountry.objects.all()) == 1
- assert shipping_method.price_per_country.all()[0].price.gross == 50
+
+ shipping_price = shipping_method.price_per_country.all()[0].price
+ assert shipping_price == Money(50, 'USD')
def test_shipping_method_country_delete(admin_client, shipping_method):
diff --git a/tests/test_cart.py b/tests/test_cart.py
index ab555d73ef..08c945fcfc 100644
--- a/tests/test_cart.py
+++ b/tests/test_cart.py
@@ -9,7 +9,7 @@ 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 Price
+from prices import Money, TaxedMoney
from saleor.cart import CartStatus, forms, utils
from saleor.cart.context_processors import cart_counter
@@ -294,10 +294,9 @@ def test_adding_same_variant(cart, product_in_stock):
variant = product_in_stock.variants.get()
cart.add(variant, 1)
cart.add(variant, 2)
- price_total = 10 * 3
assert len(cart) == 1
assert cart.count() == {'total_quantity': 3}
- assert cart.get_total().gross == price_total
+ assert cart.get_total().gross == Money(30, 'USD')
def test_replacing_same_variant(cart, product_in_stock):
@@ -580,7 +579,7 @@ def test_cart_summary_page(client, product_in_stock, request_cart):
assert content['quantity'] == request_cart.quantity
cart_total = request_cart.get_total()
assert content['total'] == currencyfmt(
- cart_total.gross, cart_total.currency)
+ cart_total.gross.amount, cart_total.currency)
assert len(content['lines']) == 1
cart_line = content['lines'][0]
assert cart_line['variant'] == variant.name
@@ -599,7 +598,8 @@ def test_total_with_discount(client, sale, request_cart, product_in_stock):
variant = product_in_stock.variants.get()
request_cart.add(variant, 1)
line = request_cart.lines.first()
- assert line.get_total(discounts=sales) == Price(currency="USD", net=5)
+ assert line.get_total(discounts=sales) == TaxedMoney(
+ net=Money(5, 'USD'), gross=Money(5, 'USD'))
def test_product_group():
@@ -712,9 +712,10 @@ 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)
- assert cart_data['cart_total'] == Price(net=10, currency='USD')
- assert cart_data['total_with_shipping'].min_price == Price(
- net=20, currency='USD')
+ assert cart_data['cart_total'] == TaxedMoney(
+ net=Money(10, 'USD'), gross=Money(10, 'USD'))
+ assert cart_data['total_with_shipping'].start == TaxedMoney(
+ net=Money(20, 'USD'), gross=Money(20, 'USD'))
def test_get_cart_data_no_shipping(request_cart_with_item):
@@ -722,5 +723,6 @@ def test_get_cart_data_no_shipping(request_cart_with_item):
cart_data = utils.get_cart_data(
request_cart_with_item, shipment_option, 'USD', None)
cart_total = cart_data['cart_total']
- assert cart_total == Price(net=10, currency='USD')
- assert cart_data['total_with_shipping'].min_price == cart_total
+ assert cart_total == TaxedMoney(
+ net=Money(10, 'USD'), gross=Money(10, 'USD'))
+ assert cart_data['total_with_shipping'].start == cart_total
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index 6bd7a3365d..cddf86d7f9 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -3,7 +3,7 @@ from unittest.mock import MagicMock, Mock
import pytest
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
-from prices import Price
+from prices import Money, TaxedMoney
from saleor.account.models import Address
from saleor.checkout import views
@@ -49,38 +49,34 @@ def test_checkout_is_shipping_required():
def test_checkout_deliveries():
+ item_price = TaxedMoney(net=Money(10, 'USD'), gross=Money(10, 'USD'))
partition = Mock(
- get_total=Mock(
- return_value=Price(10, currency=settings.DEFAULT_CURRENCY)),
- get_price_per_item=Mock(
- return_value=Price(10, currency=settings.DEFAULT_CURRENCY)))
+ get_total=Mock(return_value=item_price),
+ get_price_per_item=Mock(return_value=item_price))
def f():
yield partition
partition.__iter__ = Mock(return_value=f())
- cart = Mock(partition=Mock(return_value=[partition]),
- currency=settings.DEFAULT_CURRENCY)
- checkout = Checkout(
- cart, AnonymousUser(), 'tracking_code')
+ cart = Mock(partition=Mock(return_value=[partition]), currency='USD')
+ checkout = Checkout(cart, AnonymousUser(), 'tracking_code')
deliveries = list(checkout.deliveries)
- assert deliveries[0][1] == Price(0, currency=settings.DEFAULT_CURRENCY)
+ assert deliveries[0][1] == TaxedMoney(
+ net=Money(0, 'USD'), gross=Money(0, 'USD'))
assert deliveries[0][2] == partition.get_total()
assert deliveries[0][0][0][0] == partition
def test_checkout_deliveries_with_shipping_method(monkeypatch):
- shipping_cost = 5
- items_cost = 5
+ shipping_cost = Money(3, currency=settings.DEFAULT_CURRENCY)
+ items_cost = Money(5, currency=settings.DEFAULT_CURRENCY)
+ cost_with_shipping = items_cost + shipping_cost
+ items_price = TaxedMoney(net=items_cost, gross=items_cost)
partition = Mock(
is_shipping_required=MagicMock(return_value=True),
- get_total=Mock(
- return_value=Price(
- items_cost, currency=settings.DEFAULT_CURRENCY)),
- get_price_per_item=Mock(
- return_value=Price(
- items_cost, currency=settings.DEFAULT_CURRENCY)))
+ get_total=Mock(return_value=items_price),
+ get_price_per_item=Mock(return_value=items_price))
def f():
yield partition
@@ -90,20 +86,17 @@ def test_checkout_deliveries_with_shipping_method(monkeypatch):
partition=Mock(return_value=[partition]),
currency=settings.DEFAULT_CURRENCY)
+ shipping_price = TaxedMoney(net=shipping_cost, gross=shipping_cost)
shipping_method_mock = Mock(
- get_total=Mock(
- return_value=Price(
- shipping_cost, currency=settings.DEFAULT_CURRENCY)))
+ get_total_price=Mock(return_value=shipping_price))
monkeypatch.setattr(Checkout, 'shipping_method', shipping_method_mock)
- checkout = Checkout(
- cart, AnonymousUser(), 'tracking_code')
-
+ checkout = Checkout(cart, AnonymousUser(), 'tracking_code')
deliveries = list(checkout.deliveries)
- assert deliveries[0][1] == Price(
- shipping_cost, currency=settings.DEFAULT_CURRENCY)
- assert deliveries[0][2] == Price(
- items_cost + shipping_cost, currency=settings.DEFAULT_CURRENCY)
+
+ assert deliveries[0][1] == shipping_price
+ assert deliveries[0][2] == TaxedMoney(
+ net=cost_with_shipping, gross=cost_with_shipping)
assert deliveries[0][0][0][0] == partition
@@ -239,7 +232,8 @@ def test_checkout_discount(request_cart, sale, product_in_stock):
variant = product_in_stock.variants.get()
request_cart.add(variant, 1)
checkout = Checkout(request_cart, AnonymousUser(), 'tracking_code')
- assert checkout.get_total() == Price(currency="USD", net=5)
+ assert checkout.get_total() == TaxedMoney(
+ net=Money(5, currency="USD"), gross=Money(5, currency="USD"))
def test_checkout_create_order_insufficient_stock(
diff --git a/tests/test_core.py b/tests/test_core.py
index 6d0bd36713..62c90df4ae 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -2,11 +2,12 @@ from unittest.mock import Mock
import pytest
from django.shortcuts import reverse
+from prices import Money
from saleor.account.models import Address, User
from saleor.core.utils import (
- Country, create_superuser, get_country_by_ip, get_currency_for_country,
- random_data)
+ Country, create_superuser, format_money, get_country_by_ip,
+ get_currency_for_country, random_data)
from saleor.discount.models import Sale, Voucher
from saleor.order.models import Order
from saleor.product.models import Product
@@ -24,6 +25,11 @@ type_schema = {
'is_shipping_required': True}}
+def test_format_money():
+ money = Money('123.99', 'USD')
+ assert format_money(money) == '$123.99'
+
+
@pytest.mark.parametrize('ip_data, expected_country', [
({'country': {'iso_code': 'PL'}}, Country('PL')),
({'country': {'iso_code': 'UNKNOWN'}}, None),
diff --git a/tests/test_discounts.py b/tests/test_discounts.py
index 0e702bbda4..60ca0c1512 100644
--- a/tests/test_discounts.py
+++ b/tests/test_discounts.py
@@ -4,7 +4,7 @@ from unittest.mock import Mock
import pytest
from freezegun import freeze_time
-from prices import FixedDiscount, FractionalDiscount, Price
+from prices import Money, TaxedMoney
from saleor.discount import (
DiscountValueType, VoucherApplyToProduct, VoucherType)
@@ -17,15 +17,15 @@ from saleor.product.models import Product, ProductVariant
@pytest.mark.parametrize('limit, value', [
- (Price(5, currency='USD'), Price(10, currency='USD')),
- (Price(10, currency='USD'), Price(10, currency='USD'))])
+ (Money(5, currency='USD'), Money(10, currency='USD')),
+ (Money(10, currency='USD'), Money(10, currency='USD'))])
def test_valid_voucher_limit(settings, limit, value):
voucher = Voucher(
code='unique', type=VoucherType.SHIPPING,
discount_value_type=DiscountValueType.FIXED,
- discount_value=Price(10, currency='USD'),
+ discount_value=Money(10, currency='USD'),
limit=limit)
- voucher.validate_limit(value)
+ voucher.validate_limit(TaxedMoney(net=value, gross=value))
@pytest.mark.integration
@@ -45,10 +45,7 @@ def test_variant_discounts(product_in_stock):
value=50)
high_discount.products.add(product_in_stock)
final_price = variant.get_price_per_item(discounts=Sale.objects.all())
- assert final_price.gross == 0
- applied_discount = final_price.history.right
- assert isinstance(applied_discount, FixedDiscount)
- assert applied_discount.amount.gross == 50
+ assert final_price.gross == Money(0, currency='USD')
@pytest.mark.integration
@@ -60,27 +57,25 @@ def test_percentage_discounts(product_in_stock):
value=50)
discount.products.add(product_in_stock)
final_price = variant.get_price_per_item(discounts=[discount])
- assert final_price.gross == 5
- applied_discount = final_price.history.right
- assert isinstance(applied_discount, FractionalDiscount)
- assert applied_discount.factor == Decimal('0.5')
+ assert final_price.gross == Money(5, 'USD')
@pytest.mark.parametrize(
'total, discount_value, discount_type, limit, expected_value', [
('100', 10, DiscountValueType.FIXED, None, 10),
('100.05', 10, DiscountValueType.PERCENTAGE, 100, 10)])
-def test_value_voucher_checkout_discount(settings, total, discount_value,
- discount_type, limit, expected_value):
+def test_value_voucher_checkout_discount(
+ settings, total, discount_value, discount_type, limit, expected_value):
voucher = Voucher(
code='unique', type=VoucherType.VALUE,
discount_value_type=discount_type,
discount_value=discount_value,
- limit=Price(limit, currency='USD') if limit is not None else None)
- checkout = Mock(get_subtotal=Mock(return_value=Price(total,
- currency='USD')))
+ limit=Money(limit, currency='USD') if limit is not None else None)
+ subtotal = TaxedMoney(
+ net=Money(total, currency='USD'), gross=Money(total, currency='USD'))
+ checkout = Mock(get_subtotal=Mock(return_value=subtotal))
discount = get_voucher_discount_for_checkout(voucher, checkout)
- assert discount.amount == Price(expected_value, currency='USD')
+ assert discount == Money(expected_value, currency='USD')
def test_value_voucher_checkout_discount_not_applicable(settings):
@@ -88,12 +83,13 @@ def test_value_voucher_checkout_discount_not_applicable(settings):
code='unique', type=VoucherType.VALUE,
discount_value_type=DiscountValueType.FIXED,
discount_value=10,
- limit=100)
- checkout = Mock(get_subtotal=Mock(
- return_value=Price(10, currency='USD')))
+ limit=Money(100, currency='USD'))
+ subtotal = TaxedMoney(
+ net=Money(10, currency='USD'), gross=Money(10, currency='USD'))
+ checkout = Mock(get_subtotal=Mock(return_value=subtotal))
with pytest.raises(NotApplicable) as e:
get_voucher_discount_for_checkout(voucher, checkout)
- assert e.value.limit == Price(100, currency='USD')
+ assert e.value.limit == Money(100, currency='USD')
@pytest.mark.parametrize(
@@ -105,11 +101,17 @@ def test_value_voucher_checkout_discount_not_applicable(settings):
def test_shipping_voucher_checkout_discount(
settings, shipping_cost, shipping_country_code, discount_value,
discount_type, apply_to, expected_value):
+ subtotal = TaxedMoney(
+ net=Money(100, currency='USD'), gross=Money(100, currency='USD'))
+ shipping_total = TaxedMoney(
+ net=Money(shipping_cost, currency='USD'),
+ gross=Money(shipping_cost, currency='USD'))
checkout = Mock(
- get_subtotal=Mock(return_value=Price(100, currency='USD')),
+ get_subtotal=Mock(return_value=subtotal),
is_shipping_required=True, shipping_method=Mock(
- price=Price(shipping_cost, currency='USD'),
- country_code=shipping_country_code))
+ price=Money(shipping_cost, currency='USD'),
+ country_code=shipping_country_code,
+ get_total_price=Mock(return_value=shipping_total)))
voucher = Voucher(
code='unique', type=VoucherType.SHIPPING,
discount_value_type=discount_type,
@@ -117,43 +119,45 @@ def test_shipping_voucher_checkout_discount(
apply_to=apply_to,
limit=None)
discount = get_voucher_discount_for_checkout(voucher, checkout)
- assert discount.amount == Price(expected_value, currency='USD')
+ assert discount == Money(expected_value, currency='USD')
@pytest.mark.parametrize(
'is_shipping_required, shipping_method, discount_value, discount_type, '
'apply_to, limit, subtotal, error_msg', [
(True, Mock(country_code='PL'), 10, DiscountValueType.FIXED,
- 'US', None, Price(10, currency='USD'),
+ 'US', None, Money(10, currency='USD'),
'This offer is only valid in United States of America.'),
(True, None, 10, DiscountValueType.FIXED,
- None, None, Price(10, currency='USD'),
+ None, None, Money(10, currency='USD'),
'Please select a shipping method first.'),
(False, None, 10, DiscountValueType.FIXED,
- None, None, Price(10, currency='USD'),
+ None, None, Money(10, currency='USD'),
'Your order does not require shipping.'),
- (True, Mock(price=Price(10, currency='USD')), 10,
- DiscountValueType.FIXED, None, 5, Price(2, currency='USD'),
+ (True, Mock(price=Money(10, currency='USD')), 10,
+ DiscountValueType.FIXED, None, 5, Money(2, currency='USD'),
'This offer is only valid for orders over $5.00.')])
def test_shipping_voucher_checkout_discount_not_applicable(
settings, is_shipping_required, shipping_method, discount_value,
discount_type, apply_to, limit, subtotal, error_msg):
- checkout = Mock(is_shipping_required=is_shipping_required,
- shipping_method=shipping_method,
- get_subtotal=Mock(return_value=subtotal))
+ subtotal_price = TaxedMoney(net=subtotal, gross=subtotal)
+ checkout = Mock(
+ is_shipping_required=is_shipping_required,
+ shipping_method=shipping_method,
+ get_subtotal=Mock(return_value=subtotal_price))
voucher = Voucher(
code='unique', type=VoucherType.SHIPPING,
discount_value_type=discount_type,
discount_value=discount_value,
- limit=Price(limit, currency='USD') if limit is not None else None,
+ limit=Money(limit, currency='USD') if limit is not None else None,
apply_to=apply_to)
with pytest.raises(NotApplicable) as e:
get_voucher_discount_for_checkout(voucher, checkout)
assert str(e.value) == error_msg
-def test_product_voucher_checkout_discount_not_applicable(settings,
- monkeypatch):
+def test_product_voucher_checkout_discount_not_applicable(
+ settings, monkeypatch):
monkeypatch.setattr(
'saleor.discount.utils.get_product_variants_and_prices',
lambda cart, product: [])
@@ -168,8 +172,8 @@ def test_product_voucher_checkout_discount_not_applicable(settings,
assert str(e.value) == 'This offer is only valid for selected items.'
-def test_category_voucher_checkout_discount_not_applicable(settings,
- monkeypatch):
+def test_category_voucher_checkout_discount_not_applicable(
+ settings, monkeypatch):
monkeypatch.setattr(
'saleor.discount.utils.get_category_variants_and_prices',
lambda cart, product: [])
@@ -271,13 +275,15 @@ def test_checkout_discount_form_active_queryset_after_some_time(voucher):
([10], 10, DiscountValueType.PERCENTAGE, None, 1),
([10, 10], 10, DiscountValueType.PERCENTAGE, None, 2)])
-def test_products_voucher_checkout_discount_not(settings, monkeypatch, prices,
- discount_value, discount_type,
- apply_to, expected_value):
+def test_products_voucher_checkout_discount_not(
+ settings, monkeypatch, prices, discount_value, discount_type, apply_to,
+ expected_value):
monkeypatch.setattr(
'saleor.discount.utils.get_product_variants_and_prices',
lambda cart, product: (
- (None, Price(p, currency='USD')) for p in prices))
+ (None, TaxedMoney(
+ net=Money(p, currency='USD'), gross=Money(p, currency='USD')))
+ for p in prices))
voucher = Voucher(
code='unique', type=VoucherType.PRODUCT,
discount_value_type=discount_type,
@@ -285,26 +291,27 @@ def test_products_voucher_checkout_discount_not(settings, monkeypatch, prices,
apply_to=apply_to)
checkout = Mock(cart=Mock())
discount = get_voucher_discount_for_checkout(voucher, checkout)
- assert discount.amount == Price(expected_value, currency='USD')
+ assert discount == Money(expected_value, 'USD')
@pytest.mark.django_db
def test_sale_applies_to_correct_products(product_type, default_category):
product = Product.objects.create(
- name='Test Product', price=10, description='', pk=10,
- product_type=product_type, category=default_category)
+ name='Test Product', price=Money(10, currency='USD'), description='',
+ pk=10, product_type=product_type, category=default_category)
variant = ProductVariant.objects.create(product=product, sku='firstvar')
product2 = Product.objects.create(
- name='Second product', price=15, description='',
+ name='Second product', price=Money(15, currency='USD'), description='',
product_type=product_type, category=default_category)
sec_variant = ProductVariant.objects.create(
product=product2, sku='secvar', pk=10)
sale = Sale.objects.create(
- name='Test sale', value=5, type=DiscountValueType.FIXED)
+ name='Test sale', value=3, type=DiscountValueType.FIXED)
sale.products.add(product)
assert product2 not in sale.products.all()
product_discount = get_product_discount_on_sale(sale, variant.product)
- assert product_discount.amount == Price(net=5, currency='USD')
+ discounted_price = product_discount(product.price)
+ assert discounted_price == Money(7, currency='USD')
with pytest.raises(NotApplicable):
get_product_discount_on_sale(sale, sec_variant.product)
diff --git a/tests/test_graphql.py b/tests/test_graphql.py
index 46036e8771..0086c8ad8d 100644
--- a/tests/test_graphql.py
+++ b/tests/test_graphql.py
@@ -121,9 +121,17 @@ def test_product_query(client, product_in_stock):
availability {
available,
priceRange {
- minPrice {
- gross
- net
+ start {
+ gross {
+ amount
+ currency
+ localized
+ }
+ net {
+ amount
+ currency
+ localized
+ }
currency
}
}
@@ -143,8 +151,8 @@ def test_product_query(client, product_in_stock):
product_data = product_edges_data[0]['node']
assert product_data['name'] == product.name
assert product_data['url'] == product.get_absolute_url()
- gross = product_data['availability']['priceRange']['minPrice']['gross']
- assert float(gross) == float(product.price.gross)
+ gross = product_data['availability']['priceRange']['start']['gross']
+ assert float(gross['amount']) == float(product.price.amount)
def test_filter_product_by_category(client, product_in_stock):
@@ -353,10 +361,9 @@ def test_real_query(client, product_in_stock):
id
name
price {
+ amount
currency
- gross
- grossLocalized
- net
+ localized
__typename
}
availability {
@@ -372,19 +379,31 @@ def test_real_query(client, product_in_stock):
fragment ProductPriceFragmentQuery on ProductAvailability {
available
discount {
- gross
+ gross {
+ amount
+ currency
+ __typename
+ }
__typename
}
priceRange {
- maxPrice {
- gross
- grossLocalized
+ stop {
+ gross {
+ amount
+ currency
+ localized
+ __typename
+ }
currency
__typename
}
- minPrice {
- gross
- grossLocalized
+ start {
+ gross {
+ amount
+ currency
+ localized
+ __typename
+ }
currency
__typename
}
diff --git a/tests/test_order.py b/tests/test_order.py
index 2a6287b78c..0ddf99754a 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -2,33 +2,36 @@ from decimal import Decimal
from unittest.mock import Mock, patch
from django.urls import reverse
-from prices import Price
+from prices import Money, TaxedMoney
from tests.utils import get_redirect_location
from saleor.order import OrderStatus, models
from saleor.order.emails import collect_data_for_email
from saleor.order.forms import OrderNoteForm
-from saleor.order.utils import add_variant_to_delivery_group
-
-
-def test_total_property():
- order = models.Order(total_net=20, total_tax=5)
- assert order.total.gross == 25
- assert order.total.tax == 5
- assert order.total.net == 20
-
-
-def test_total_property_empty_value():
- order = models.Order(total_net=None, total_tax=None)
- assert order.total is None
+from saleor.order.utils import add_variant_to_delivery_group, recalculate_order
def test_total_setter():
- price = Price(net=10, gross=20, currency='USD')
+ price = TaxedMoney(
+ net=Money(10, currency='USD'), gross=Money(15, currency='USD'))
order = models.Order()
order.total = price
- assert order.total_net.net == 10
- assert order.total_tax.net == 10
+ assert order.total_net == Money(10, currency='USD')
+ assert order.total.net == Money(10, currency='USD')
+ assert order.total_gross == Money(15, currency='USD')
+ assert order.total.gross == Money(15, currency='USD')
+ assert order.total.tax == Money(5, currency='USD')
+
+
+def test_order_get_subtotal(order_with_lines):
+ order_with_lines.discount_name = "Test discount"
+ order_with_lines.discount_amount = (
+ order_with_lines.total.gross * Decimal('0.5'))
+ recalculate_order(order_with_lines)
+
+ target_subtotal = order_with_lines.total - order_with_lines.shipping_price
+ target_subtotal += order_with_lines.discount_amount
+ assert order_with_lines.get_subtotal() == target_subtotal
def test_add_variant_to_delivery_group_adds_line_for_new_variant(
diff --git a/tests/test_payment.py b/tests/test_payment.py
index 591f39ad37..0307c87edb 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -1,4 +1,4 @@
-from prices import Price
+from prices import Money
from saleor.order.models import Payment
@@ -6,7 +6,7 @@ from saleor.order.models import Payment
def test_get_purchased_items(order_with_lines, settings, voucher):
payment = Payment.objects.create(order=order_with_lines, variant='paypal')
- discount = Price('10.0', currency=settings.DEFAULT_CURRENCY)
+ discount = Money('10.0', currency=settings.DEFAULT_CURRENCY)
assert len(payment.get_purchased_items()) == len(
order_with_lines.get_lines())
@@ -35,5 +35,5 @@ def test_get_purchased_items(order_with_lines, settings, voucher):
assert discounted.name == order_with_lines.discount_name
assert discounted.sku == 'DISCOUNT'
- assert discounted.price == -1 * order_with_lines.discount_amount.net
+ assert discounted.price == -1 * order_with_lines.discount_amount.amount
assert discounted.quantity == 1
diff --git a/tests/test_product.py b/tests/test_product.py
index 269e9c6e2b..a5c9ad3781 100644
--- a/tests/test_product.py
+++ b/tests/test_product.py
@@ -106,7 +106,7 @@ def test_availability(product_in_stock, monkeypatch, settings):
settings.DEFAULT_COUNTRY = 'PL'
settings.OPENEXCHANGERATES_API_KEY = 'fake-key'
availability = get_availability(product_in_stock, local_currency='PLN')
- assert availability.price_range_local_currency.min_price.currency == 'PLN'
+ assert availability.price_range_local_currency.start.currency == 'PLN'
assert availability.available