Skip to content

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

Add PricingInfo object that stores all pricing information

Artur Smętb11557ae0bc8
diff --git a/saleor/product/utils.py b/saleor/product/utils.py
index e46a6f4885..d4db4f6d9e 100644
--- a/saleor/product/utils.py
+++ b/saleor/product/utils.py
@@ -1,3 +1,6 @@
+from collections import namedtuple
+
+from django_prices_openexchangerates import exchange_currency
from .models import Product
@@ -23,3 +26,39 @@ def get_product_images(product):
Returns list of product images that will be placed in product gallery
"""
return list(product.images.all())
+
+
+PricingInfo = namedtuple(
+ 'PricingInfo', ('price_range', 'discount',
+ 'price_range_local_currency',
+ 'discount_local_currency'))
+
+
+def get_pricing_info(product, discounts=None, local_currency=None):
+ # In default currency
+ price_range = product.get_price_range(discounts=discounts)
+ uncdiscounted = product.get_price_range()
+ if uncdiscounted.min_price > price_range.min_price:
+ discount = uncdiscounted.min_price - price_range.min_price
+ else:
+ discount = None
+
+ # Local currency
+ if local_currency:
+ price_range_local = exchange_currency(
+ price_range, local_currency)
+ undiscounted_local = exchange_currency(
+ uncdiscounted, local_currency)
+ if undiscounted_local.min_price > price_range_local.min_price:
+ discount_local_currency = (
+ undiscounted_local.min_price - price_range_local.min_price)
+ else:
+ discount_local_currency = None
+ else:
+ price_range_local = None
+ discount_local_currency = None
+
+ return PricingInfo(price_range=price_range,
+ discount=discount,
+ price_range_local_currency=price_range_local,
+ discount_local_currency=discount_local_currency)
diff --git a/tests/test_product.py b/tests/test_product.py
index 0b00c0a794..c23e23c850 100644
--- a/tests/test_product.py
+++ b/tests/test_product.py
@@ -3,7 +3,7 @@ import datetime
from mock import Mock
from saleor.product import models
-
+from saleor.product.utils import get_pricing_info
def test_stock_selector(product_in_stock):
variant = product_in_stock.variants.get()
@@ -63,3 +63,14 @@ def test_product_page_with_openexchagerates(
response = client.get(product_in_stock.get_absolute_url())
context = response.context
assert context['local_price_range'].min_price.currency == 'PLN'
+
+
+def test_pricing_info(product_in_stock, monkeypatch):
+ pricing_info = get_pricing_info(product_in_stock)
+ assert pricing_info.price_range == product_in_stock.get_price_range()
+ assert pricing_info.price_range_local_currency is None
+ monkeypatch.setattr(
+ 'django_prices_openexchangerates.models.get_rates',
+ lambda c: {'PLN': Mock(rate=2)})
+ pricing_info = get_pricing_info(product_in_stock, local_currency='PLN')
+ assert pricing_info.price_range_local_currency.min_price.currency == 'PLN'