Skip to content

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

WIP

Pacu2461619ba9aa2
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index b3ad2e2e62..14250b077d 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -21,7 +21,7 @@ from ..core.utils.taxes import ZERO_MONEY, get_taxes_for_country
from ..discount import VoucherType
from ..discount.models import NotApplicable, Voucher
from ..discount.utils import (
- get_product_or_category_voucher_discount, get_shipping_voucher_discount,
+ get_products_voucher_discount, get_shipping_voucher_discount,
get_value_voucher_discount, increase_voucher_usage)
from ..order.models import Order
from ..shipping.models import ShippingMethodCountry
@@ -74,27 +74,38 @@ def remove_unavailable_variants(cart):
add_variant_to_cart(cart, line.variant, quantity, replace=True)
-def get_product_variants_and_prices(cart, product):
+def get_prices_of_discounted_products(lines, discounted_products):
"""Get variants and unit prices from cart lines matching the product."""
- lines = (line for line in cart if line.variant.product_id == product.id)
- for line in lines:
- for dummy_i in range(line.quantity):
- yield line.variant, line.variant.get_price()
+ # If there's no discounted_products,
+ # it means that all products are discounted
+ if not discounted_products:
+ return [line.get_total() for line in lines]
+ prices = [
+ line.get_total()
+ for line in lines
+ if line.variant.product in discounted_products]
+ return prices
-def get_category_variants_and_prices(cart, root_category):
+
+def get_prices_of_products_in_discounted_collections(
+ lines, discounted_collections):
"""Get variants and unit prices from cart lines matching the category.
Product is assumed to be in the category if it belongs to any of its
descendant subcategories.
"""
- matching_products = {
- line.variant.product for line in cart
- if line.variant.product.category.is_descendant_of(
- root_category, include_self=True)}
- for product in matching_products:
- for line in get_product_variants_and_prices(cart, product):
- yield line
+ # If there's no discounted collections,
+ # it means that all of them are discounted
+ if not discounted_collections:
+ return [line.get_total() for line in lines]
+
+ discounted_collections = set(discounted_collections)
+ prices = [
+ line.get_total() for line in lines
+ if line.variant and
+ set(line.variant.product.collections.all()) & discounted_collections]
+ return prices
def check_product_availability_and_warn(request, cart):
@@ -628,33 +639,31 @@ def _get_shipping_voucher_discount_for_cart(voucher, cart):
'Please select a shipping method first.')
raise NotApplicable(msg)
not_valid_for_country = (
- voucher.apply_to and shipping_method.country_code != voucher.apply_to)
+ voucher.countries and
+ shipping_method.country_code not in voucher.countries)
if not_valid_for_country:
msg = pgettext(
'Voucher not applicable',
- 'This offer is only valid in %(country)s.')
- raise NotApplicable(
- msg % {'country': voucher.get_apply_to_display()})
+ 'This offer is not valid in your country.')
+ raise NotApplicable(msg)
return get_shipping_voucher_discount(
voucher, cart.get_subtotal(), shipping_method.get_total_price())
-def _get_product_or_category_voucher_discount_for_cart(voucher, cart):
+def _get_products_voucher_discount(order_or_cart, voucher):
"""Calculate discount value for a voucher of product or category type."""
if voucher.type == VoucherType.PRODUCT:
- prices = [
- variant_price for _, variant_price in
- get_product_variants_and_prices(cart, voucher.product)]
+ prices = get_prices_of_discounted_products(
+ order_or_cart.lines.all(), voucher.products.all())
else:
- prices = [
- variant_price for _, variant_price in
- get_category_variants_and_prices(cart, voucher.category)]
+ prices = get_prices_of_products_in_discounted_collections(
+ order_or_cart.lines.all(), voucher.collections.all())
if not prices:
msg = pgettext(
'Voucher not applicable',
'This offer is only valid for selected items.')
raise NotApplicable(msg)
- return get_product_or_category_voucher_discount(voucher, prices)
+ return get_products_voucher_discount(voucher, prices)
def get_voucher_discount_for_cart(voucher, cart):
@@ -666,9 +675,10 @@ def get_voucher_discount_for_cart(voucher, cart):
return _get_value_voucher_discount_for_cart(voucher, cart)
if voucher.type == VoucherType.SHIPPING:
return _get_shipping_voucher_discount_for_cart(voucher, cart)
- if voucher.type in (VoucherType.PRODUCT, VoucherType.CATEGORY):
- return _get_product_or_category_voucher_discount_for_cart(
- voucher, cart)
+ if voucher.type == VoucherType.PRODUCT:
+ return _get_products_voucher_discount(cart, voucher)
+ if voucher.type == VoucherType.CATEGORY:
+ return _get_products_voucher_discount(cart, voucher)
raise NotImplementedError('Unknown discount type')
diff --git a/saleor/dashboard/discount/filters.py b/saleor/dashboard/discount/filters.py
index 2609747012..3029c94330 100644
--- a/saleor/dashboard/discount/filters.py
+++ b/saleor/dashboard/discount/filters.py
@@ -18,7 +18,7 @@ SORT_BY_FIELDS_LABELS_VOUCHER = {
'name': pgettext_lazy('Voucher list sorting option', 'name'),
'discount_value': pgettext_lazy(
'Voucher list sorting option', 'discount_value'),
- 'apply_to': pgettext_lazy('Voucher list sorting option', 'apply_to'),
+ 'countries': pgettext_lazy('Voucher list sorting option', 'countries'),
'start_date': pgettext_lazy('Voucher list sorting option', 'start_date'),
'end_date': pgettext_lazy('Voucher list sorting option', 'end_date'),
'used': pgettext_lazy('Voucher list sorting option', 'used'),
diff --git a/saleor/dashboard/discount/forms.py b/saleor/dashboard/discount/forms.py
index d23bcd73c9..5572ab7552 100644
--- a/saleor/dashboard/discount/forms.py
+++ b/saleor/dashboard/discount/forms.py
@@ -8,7 +8,7 @@ from django_prices.forms import MoneyField
from ...core.i18n import COUNTRY_CODE_CHOICES
from ...core.utils.taxes import ZERO_MONEY
-from ...discount import DiscountValueType, VoucherApplyToProduct
+from ...discount import DiscountValueType
from ...discount.models import Sale, Voucher
from ...product.models import Product
from ...shipping.models import ShippingMethodCountry
@@ -70,7 +70,7 @@ class VoucherForm(forms.ModelForm):
class Meta:
model = Voucher
- exclude = ['limit', 'apply_to', 'product', 'category', 'used']
+ exclude = ['limit', 'countries', 'products', 'collections', 'used']
labels = {
'type': pgettext_lazy(
'Discount type',
@@ -130,18 +130,18 @@ class ShippingVoucherForm(forms.ModelForm):
label=pgettext_lazy(
'Lowest value for order to be able to use the voucher',
'Only if order is over or equal to'))
- apply_to = forms.ChoiceField(
+ countries = forms.ChoiceField(
choices=country_choices,
required=False,
- label=pgettext_lazy('Voucher form', 'Apply to'))
+ label=pgettext_lazy(
+ 'Text above the dropdown of countries',
+ 'Countries that free shipping should apply to'))
class Meta:
model = Voucher
- fields = ['apply_to', 'limit']
+ fields = ['countries', 'limit']
def save(self, commit=True):
- self.instance.category = None
- self.instance.product = None
return super().save(commit)
@@ -160,7 +160,7 @@ class ValueVoucherForm(forms.ModelForm):
def save(self, commit=True):
self.instance.category = None
- self.instance.apply_to = None
+ self.instance.countries = []
self.instance.product = None
return super().save(commit)
@@ -168,19 +168,9 @@ class ValueVoucherForm(forms.ModelForm):
class CommonVoucherForm(forms.ModelForm):
use_required_attribute = False
- apply_to = forms.ChoiceField(
- choices=VoucherApplyToProduct.CHOICES, required=False,
- label=pgettext_lazy('Voucher form', 'Apply to'))
def save(self, commit=True):
self.instance.limit = None
- # Apply to one with percentage discount is more complicated case.
- # On which product we should apply it? On first, last or cheapest?
- # Percentage case is limited to the all value and the apply_to field
- # is not used in this case so we set it to None.
- if (self.instance.discount_value_type ==
- DiscountValueType.PERCENTAGE):
- self.instance.apply_to = None
return super().save(commit)
@@ -193,24 +183,19 @@ class ProductVoucherForm(CommonVoucherForm):
class Meta:
model = Voucher
- fields = ['product', 'apply_to']
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- if self.instance.product:
- self.fields['product'].set_initial(self.instance.product)
+ fields = ['products']
-class CategoryVoucherForm(CommonVoucherForm):
+class CollectionVoucherForm(CommonVoucherForm):
class Meta:
model = Voucher
- fields = ['category', 'apply_to']
+ fields = ['collections']
labels = {
- 'category': pgettext_lazy(
- 'Category',
- 'Category')}
+ 'collections': pgettext_lazy(
+ 'Collections',
+ 'Collections')}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- self.fields['category'].required = True
+ self.fields['collections'].required = True
diff --git a/saleor/dashboard/discount/views.py b/saleor/dashboard/discount/views.py
index aa01726d57..395e3f45f1 100644
--- a/saleor/dashboard/discount/views.py
+++ b/saleor/dashboard/discount/views.py
@@ -26,7 +26,7 @@ def get_voucher_type_forms(voucher, data):
data or None, instance=voucher, prefix=VoucherType.VALUE),
VoucherType.PRODUCT: forms.ProductVoucherForm(
data or None, instance=voucher, prefix=VoucherType.PRODUCT),
- VoucherType.CATEGORY: forms.CategoryVoucherForm(
+ VoucherType.CATEGORY: forms.CollectionVoucherForm(
data or None, instance=voucher, prefix=VoucherType.CATEGORY)}
@@ -90,7 +90,7 @@ def sale_delete(request, pk):
@staff_member_required
@permission_required('discount.manage_discounts')
def voucher_list(request):
- vouchers = (Voucher.objects.select_related('product', 'category')
+ vouchers = (Voucher.objects.prefetch_related('products', 'collections')
.order_by('name'))
voucher_filter = VoucherFilter(request.GET, queryset=vouchers)
vouchers = get_paginator_items(
diff --git a/saleor/dashboard/order/utils.py b/saleor/dashboard/order/utils.py
index 049aabcd60..b2ac1fa335 100644
--- a/saleor/dashboard/order/utils.py
+++ b/saleor/dashboard/order/utils.py
@@ -3,11 +3,14 @@ from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import get_template
from ...checkout import AddressType
+from ...checkout.utils import (
+ _get_products_voucher_discount, get_prices_of_discounted_products,
+ get_prices_of_products_in_discounted_collections)
from ...core.utils.taxes import ZERO_MONEY
from ...discount import VoucherType
from ...discount.models import NotApplicable
from ...discount.utils import (
- get_product_or_category_voucher_discount, get_shipping_voucher_discount,
+ get_products_voucher_discount, get_shipping_voucher_discount,
get_value_voucher_discount)
from ...product.utils import decrease_stock
@@ -74,82 +77,21 @@ def update_order_with_user_addresses(order):
order.save(update_fields=['billing_address', 'shipping_address'])
-def get_product_variants_and_prices(order, product):
- """Get variants and unit prices from order lines matching the product."""
- lines = (
- line for line in order
- if line.variant and line.variant.product == product)
- for line in lines:
- for dummy_i in range(line.quantity):
- variant = line.variant
- if variant:
- yield variant, variant.get_price()
-
-
-def get_category_variants_and_prices(order, root_category):
- """Get variants and unit prices from cart lines matching the category.
-
- Product is assumed to be in the category if it belongs to any of its
- descendant subcategories.
- """
- products = {line.variant.product for line in order if line.variant}
- matching_products = set()
- for product in products:
- if product.category.is_descendant_of(root_category, include_self=True):
- matching_products.add(product)
- for product in matching_products:
- for line in get_product_variants_and_prices(order, product):
- yield line
-
-
-def _get_value_voucher_discount_for_order(order):
- """Calculate discount value for a voucher of value type."""
- try:
- discount_amount = get_value_voucher_discount(
- order.voucher, order.get_subtotal())
- except NotApplicable:
- discount_amount = ZERO_MONEY
- return discount_amount
-
-
-def _get_shipping_voucher_discount_for_order(order):
- """Calculate discount value for a voucher of shipping type."""
- try:
- discount_amount = get_shipping_voucher_discount(
- order.voucher, order.get_subtotal(), order.shipping_price)
- except NotApplicable:
- discount_amount = ZERO_MONEY
- return discount_amount
-
-
-def _get_product_or_category_voucher_discount_for_order(order):
- """Calculate discount value for a voucher of product or category type."""
- if order.voucher.type == VoucherType.PRODUCT:
- prices = [
- variant_price for _, variant_price in
- get_product_variants_and_prices(order, order.voucher.product)]
- else:
- prices = [
- variant_price for _, variant_price in
- get_category_variants_and_prices(order, order.voucher.category)]
- if not prices:
- return ZERO_MONEY
- return get_product_or_category_voucher_discount(order.voucher, prices)
-
-
def get_voucher_discount_for_order(order):
"""Calculate discount value depending on voucher and discount types.
Raise NotApplicable if voucher of given type cannot be applied.
"""
if not order.voucher:
- return None
+ return ZERO_MONEY
if order.voucher.type == VoucherType.VALUE:
- return _get_value_voucher_discount_for_order(order)
+ return get_value_voucher_discount(
+ order.voucher, order.get_subtotal())
if order.voucher.type == VoucherType.SHIPPING:
- return _get_shipping_voucher_discount_for_order(order)
+ return get_shipping_voucher_discount(
+ order.voucher, order.get_subtotal(), order.shipping_price)
if order.voucher.type in (VoucherType.PRODUCT, VoucherType.CATEGORY):
- return _get_product_or_category_voucher_discount_for_order(order)
+ return _get_products_voucher_discount(order, order.voucher)
raise NotImplementedError('Unknown discount type')
@@ -169,6 +111,10 @@ def save_address_in_order(order, address, address_type):
order.save(update_fields=['billing_address', 'shipping_address'])
+def addresses_are_equal(address_1, address_2):
+ return address_1 and address_2 and address_1 == address_2
+
+
def remove_customer_from_order(order):
"""Remove related customer and user email from order.
@@ -181,16 +127,14 @@ def remove_customer_from_order(order):
order.save()
if customer:
- equal_billing_addresses = (
- order.billing_address and customer.default_billing_address and
- customer.default_billing_address == order.billing_address)
+ equal_billing_addresses = addresses_are_equal(
+ order.billing_address, customer.default_billing_address)
if equal_billing_addresses:
order.billing_address.delete()
order.billing_address = None
- equal_shipping_addresses = (
- order.shipping_address and customer.default_shipping_address and
- customer.default_shipping_address == order.shipping_address)
+ equal_shipping_addresses = addresses_are_equal(
+ order.shipping_address, customer.default_shipping_address)
if equal_shipping_addresses:
order.shipping_address.delete()
order.shipping_address = None
diff --git a/saleor/discount/__init__.py b/saleor/discount/__init__.py
index b2637ce1ee..4ca1489651 100644
--- a/saleor/discount/__init__.py
+++ b/saleor/discount/__init__.py
@@ -24,14 +24,3 @@ class VoucherType:
(CATEGORY, pgettext_lazy(
'Voucher: discount for', 'A category of products')),
(SHIPPING, pgettext_lazy('Voucher: discount for', 'Shipping'))]
-
-
-class VoucherApplyToProduct:
- ONE_PRODUCT = 'one'
- ALL_PRODUCTS = 'all'
-
- CHOICES = [
- (ONE_PRODUCT, pgettext_lazy(
- 'Voucher application', 'Apply to a single item')),
- (ALL_PRODUCTS, pgettext_lazy(
- 'Voucher application', 'Apply to all matching products'))]
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 48d4149af4..59391c7560 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -6,12 +6,12 @@ from django.conf import settings
from django.db import models
from django.db.models import F, Q
from django.utils.translation import pgettext, pgettext_lazy
-from django_countries import countries
+from django_countries.fields import CountryField
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
+from . import DiscountValueType, VoucherType
class NotApplicable(ValueError):
@@ -51,14 +51,12 @@ class Voucher(models.Model):
max_digits=12, decimal_places=settings.DEFAULT_DECIMAL_PLACES)
# not mandatory fields, usage depends on type
- product = models.ForeignKey(
- 'product.Product', blank=True, null=True, on_delete=models.CASCADE)
- category = models.ForeignKey(
- 'product.Category', blank=True, null=True, on_delete=models.CASCADE)
- apply_to = models.CharField(max_length=20, blank=True, null=True)
+ countries = CountryField(multiple=True, blank=True)
limit = MoneyField(
currency=settings.DEFAULT_CURRENCY, max_digits=12,
decimal_places=settings.DEFAULT_DECIMAL_PLACES, null=True, blank=True)
+ products = models.ManyToManyField('product.Product', blank=True)
+ collections = models.ManyToManyField('product.Collection', blank=True)
objects = VoucherQueryset.as_manager()
@@ -76,13 +74,16 @@ class Voucher(models.Model):
if self.type == VoucherType.PRODUCT:
return pgettext(
'Voucher type',
- '%(discount)s off %(product)s') % {
- 'discount': discount, 'product': self.product}
+ '%(discount)s off %(product_num)d products') % {
+ 'discount': discount,
+ 'product_num': len(self.products.all())}
+ # TODO its collections now
if self.type == VoucherType.CATEGORY:
return pgettext(
'Voucher type',
- '%(discount)s off %(category)s') % {
- 'discount': discount, 'category': self.category}
+ '%(discount)s off %(collections_num)d collections') % {
+ 'discount': discount,
+ 'collections_num': len(self.collections.all())}
return pgettext(
'Voucher type', '%(discount)s off') % {'discount': discount}
@@ -92,17 +93,6 @@ class Voucher(models.Model):
self.discount_value == Decimal(100) and
self.discount_value_type == DiscountValueType.PERCENTAGE)
- def get_apply_to_display(self):
- if self.type == VoucherType.SHIPPING and self.apply_to:
- return countries.name(self.apply_to)
- if self.type == VoucherType.SHIPPING:
- return pgettext('Voucher', 'Any country')
- if self.apply_to and self.type in {
- VoucherType.PRODUCT, VoucherType.CATEGORY}:
- choices = dict(VoucherApplyToProduct.CHOICES)
- return choices[self.apply_to]
- return None
-
def get_discount(self):
if self.discount_value_type == DiscountValueType.FIXED:
discount_amount = Money(
@@ -140,6 +130,8 @@ class Sale(models.Model):
products = models.ManyToManyField('product.Product', blank=True)
categories = models.ManyToManyField('product.Category', blank=True)
collections = models.ManyToManyField('product.Collection', blank=True)
+ start_date = models.DateField(default=date.today)
+ end_date = models.DateField(null=True, blank=True)
class Meta:
app_label = 'discount'
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 0c73df3f27..200e7ff17b 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -1,8 +1,7 @@
from django.db.models import F
from django.utils.translation import pgettext
-from . import VoucherApplyToProduct
-from ..core.utils.taxes import ZERO_MONEY, ZERO_TAXED_MONEY
+from ..core.utils.taxes import ZERO_TAXED_MONEY
from .models import NotApplicable
@@ -44,8 +43,7 @@ def get_product_discount_on_sale(sale, product):
return sale.get_discount()
raise NotApplicable(
pgettext(
- 'Voucher not applicable',
- 'Discount not applicable for this product'))
+ 'Voucher not applicable', 'Discount not applicable for this product'))
def get_product_discounts(product, discounts):
@@ -78,12 +76,7 @@ def get_shipping_voucher_discount(voucher, total_price, shipping_price):
return voucher.get_discount_amount_for(shipping_price)
-def get_product_or_category_voucher_discount(voucher, prices):
+def get_products_voucher_discount(voucher, prices):
"""Calculate discount value for a voucher of product or category type."""
- if voucher.apply_to == VoucherApplyToProduct.ALL_PRODUCTS:
- discounts = (
- voucher.get_discount_amount_for(price) for price in prices)
- total_amount = sum(discounts, ZERO_MONEY)
- return total_amount
product_total = sum(prices, ZERO_TAXED_MONEY)
return voucher.get_discount_amount_for(product_total)
diff --git a/saleor/graphql/discount/mutations.py b/saleor/graphql/discount/mutations.py
index d3ea04aaf2..594c105a46 100644
--- a/saleor/graphql/discount/mutations.py
+++ b/saleor/graphql/discount/mutations.py
@@ -3,18 +3,18 @@ import graphene
from ...discount import VoucherType, models
from ..core.mutations import ModelDeleteMutation, ModelMutation
from ..core.types.common import Decimal
-from .types import ApplyToEnum, DiscountValueTypeEnum, VoucherTypeEnum
+from .types import DiscountValueTypeEnum, VoucherTypeEnum
def validate_voucher(voucher_data):
voucher_type = voucher_data.get('type')
errors = []
if voucher_type == VoucherType.PRODUCT:
- if not voucher_data.get('product'):
- errors.append(('product', 'This field is required.'))
+ if not voucher_data.get('products'):
+ errors.append(('products', 'This field is required.'))
elif voucher_type == VoucherType.CATEGORY:
- if not voucher_data.get('category'):
- errors.append(('category', 'This field is required.'))
+ if not voucher_data.get('collections'):
+ errors.append(('collections', 'This field is required.'))
return errors
@@ -30,10 +30,15 @@ class VoucherInput(graphene.InputObjectType):
discount_value_type = DiscountValueTypeEnum(
description='Choices: fixed or percentage.')
discount_value = Decimal(description='Value of the voucher.')
- product = graphene.ID(description='Product related to the discount.')
- category = graphene.ID(description='Category related to the discount.')
- apply_to = ApplyToEnum(description='Single item or all matching products.')
+ products = graphene.List(
+ graphene.ID, description='Products discounted by the voucher.')
+ collections = graphene.List(
+ graphene.ID, description='Collections discounted by the voucher.')
limit = Decimal(description='Limit value of the discount.')
+ countries = graphene.List(
+ graphene.String,
+ description='Country codes that can be used with '
+ 'the shipping voucher')
class VoucherCreate(ModelMutation):
diff --git a/saleor/graphql/discount/resolvers.py b/saleor/graphql/discount/resolvers.py
index 7508e5037e..c099fe5384 100644
--- a/saleor/graphql/discount/resolvers.py
+++ b/saleor/graphql/discount/resolvers.py
@@ -2,8 +2,8 @@ from ...discount import models
from ..utils import filter_by_query_param
VOUCHER_SEARCH_FIELDS = (
- 'name', 'code', 'discount_value', 'product__name', 'category__name',
- 'limit', 'apply_to', 'discount_value_type')
+ 'name', 'code', 'discount_value', 'collections__name', 'products__name',
+ 'limit', 'countries', 'discount_value_type')
SALE_SEARCH_FIELDS = ('name', 'value', 'type')
diff --git a/saleor/graphql/discount/types.py b/saleor/graphql/discount/types.py
index 6274cce7f3..01e5041c07 100644
--- a/saleor/graphql/discount/types.py
+++ b/saleor/graphql/discount/types.py
@@ -2,7 +2,7 @@ import graphene
from graphene import relay
from ...discount import (
- DiscountValueType, VoucherApplyToProduct, VoucherType, models)
+ DiscountValueType, VoucherType, models)
from ..core.types.common import CountableDjangoObjectType
@@ -43,8 +43,3 @@ class VoucherTypeEnum(graphene.Enum):
class DiscountValueTypeEnum(graphene.Enum):
FIXED = DiscountValueType.FIXED
PERCENTAGE = DiscountValueType.PERCENTAGE
-
-
-class ApplyToEnum(graphene.Enum):
- ONE_PRODUCT = VoucherApplyToProduct.ONE_PRODUCT
- ALL_PRODUCTS = VoucherApplyToProduct.ALL_PRODUCTS
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 6c6e340128..f67252ed00 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -7,6 +7,7 @@ from ..checkout import AddressType
from ..core.utils.taxes import (
ZERO_MONEY, get_tax_rate_by_name, get_taxes_for_address)
from ..dashboard.order.utils import get_voucher_discount_for_order
+from ..discount.models import NotApplicable
from ..order import FulfillmentStatus, OrderStatus
from ..order.models import OrderLine
from ..product.utils import allocate_stock, deallocate_stock, increase_stock
@@ -41,8 +42,11 @@ def update_voucher_discount(func):
def decorator(*args, **kwargs):
if kwargs.pop('update_voucher_discount', True):
order = args[0]
- order.discount_amount = (
- get_voucher_discount_for_order(order) or ZERO_MONEY)
+ try:
+ discount_amount = get_voucher_discount_for_order(order)
+ except NotApplicable:
+ discount_amount = ZERO_MONEY
+ order.discount_amount = discount_amount
return func(*args, **kwargs)
return decorator
diff --git a/templates/dashboard/discount/voucher/list.html b/templates/dashboard/discount/voucher/list.html
index 014f9a9876..a5934a589f 100644
--- a/templates/dashboard/discount/voucher/list.html
+++ b/templates/dashboard/discount/voucher/list.html
@@ -46,10 +46,6 @@
{% trans "Discount" context "Voucher table header" as label %}
{% sorting_header 'discount_value' label is_wide=True %}
- <th>
- {% trans "Apply to" context "Voucher table header" %}
- </th>
-
{% trans "Start date" context "Voucher table header" as label %}
{% sorting_header 'start_date' label is_wide=True %}
@@ -72,9 +68,6 @@
<td class="right-align">
{{ voucher.discount_value }}&nbsp;<span class="currency">{{ voucher.get_discount_value_type_display }}</span>
</td>
- <td>
- {{ voucher.get_apply_to_display|default_if_none:"-" }}
- </td>
<td>
{{ voucher.start_date }}
</td>
diff --git a/tests/api/test_discount.py b/tests/api/test_discount.py
index fa8eee2c8b..7280d30184 100644
--- a/tests/api/test_discount.py
+++ b/tests/api/test_discount.py
@@ -6,9 +6,9 @@ from django.shortcuts import reverse
from tests.utils import get_graphql_content
from saleor.discount import (
- DiscountValueType, VoucherApplyToProduct, VoucherType)
+ DiscountValueType, VoucherType)
from saleor.graphql.discount.types import (
- ApplyToEnum, DiscountValueTypeEnum, VoucherTypeEnum)
+ DiscountValueTypeEnum, VoucherTypeEnum)
from .utils import assert_no_permission
@@ -56,7 +56,6 @@ def test_voucher_query(
startDate
discountValueType
discountValue
- applyTo
}
}
}
@@ -74,7 +73,6 @@ def test_voucher_query(
assert data['startDate'] == voucher.start_date.isoformat()
assert data['discountValueType'] == voucher.discount_value_type.upper()
assert data['discountValue'] == voucher.discount_value
- assert data['applyTo'] == voucher.apply_to
def test_sale_query(
@@ -105,10 +103,10 @@ def test_create_voucher(user_api_client, admin_api_client):
query = """
mutation voucherCreate(
$type: VoucherTypeEnum, $name: String, $code: String,
- $applyTo: ApplyToEnum, $discountValueType: DiscountValueTypeEnum,
+ $discountValueType: DiscountValueTypeEnum,
$discountValue: Decimal, $limit: Decimal) {
voucherCreate(input: {
- name: $name, type: $type, code: $code, applyTo: $applyTo,
+ name: $name, type: $type, code: $code,
discountValueType: $discountValueType, discountValue: $discountValue,
limit: $limit}) {
errors {
@@ -120,7 +118,6 @@ def test_create_voucher(user_api_client, admin_api_client):
limit {
amount
}
- applyTo
name
code
discountValueType
@@ -132,7 +129,6 @@ def test_create_voucher(user_api_client, admin_api_client):
'name': 'test voucher',
'type': VoucherTypeEnum.VALUE.name,
'code': 'testcode123',
- 'applyTo': ApplyToEnum.ALL_PRODUCTS.name,
'discountValueType': DiscountValueTypeEnum.FIXED.name,
'discountValue': '10.12',
'limit': '1.12'})
@@ -147,7 +143,6 @@ def test_create_voucher(user_api_client, admin_api_client):
data = content['data']['voucherCreate']['voucher']
assert data['type'] == VoucherType.VALUE.upper()
assert data['limit']['amount'] == float('1.12')
- assert data['applyTo'] == VoucherApplyToProduct.ALL_PRODUCTS
assert data['name'] == 'test voucher'
assert data['code'] == 'testcode123'
assert data['discountValueType'] == DiscountValueType.FIXED.upper()
@@ -324,35 +319,39 @@ def test_sale_delete_mutation(user_api_client, admin_api_client, sale):
with pytest.raises(sale._meta.model.DoesNotExist):
sale.refresh_from_db()
-
-def test_validate_voucher(voucher, admin_api_client, product):
- query = """
- mutation voucherUpdate(
- $product_id: ID, $id: ID!, $type: VoucherTypeEnum) {
- voucherUpdate(
- id: $id, input: {product: $product_id, type: $type}) {
- errors {
- field
- message
- }
- voucher {
- product {
- name
- }
- }
- }
- }
- """
-
- assert not voucher.product
- variables = json.dumps({
- 'type': VoucherTypeEnum.PRODUCT.name,
- 'id': graphene.Node.to_global_id('Voucher', voucher.id),
- 'product': graphene.Node.to_global_id('Product', product.id)})
-
- response = admin_api_client.post(
- reverse('api'), {'query': query, 'variables': variables})
- content = get_graphql_content(response)
- data = content['data']['voucherUpdate']['errors'][0]
- assert data['field'] == 'product'
- assert data['message'] == 'This field is required.'
+# FIXME
+# def test_validate_voucher(voucher, admin_api_client, product):
+# query = """
+# mutation voucherUpdate(
+# $products: [ProductInput], $id: ID!, $type: VoucherTypeEnum) {
+# voucherUpdate(
+# id: $id, input: {products: $products, type: $type}) {
+# errors {
+# field
+# message
+# }
+# voucher {
+# products {
+# edges {
+# node {
+# name
+# }
+# }
+# }
+# }
+# }
+# }
+# """
+
+# assert not voucher.products.all()
+# product_id = graphene.Node.to_global_id('Product', product.id)
+# variables = json.dumps({
+# 'type': VoucherTypeEnum.PRODUCT.name,
+# 'id': graphene.Node.to_global_id('Voucher', voucher.id),
+# 'products': [{'name': 1, 'productID': product_id}]})
+# response = admin_api_client.post(
+# reverse('api'), {'query': query, 'variables': variables})
+# content = get_graphql_content(response)
+# data = content['data']['voucherUpdate']['errors'][0]
+# assert data['field'] == 'products'
+# assert data['message'] == 'This field is required.'
diff --git a/tests/conftest.py b/tests/conftest.py
index a0fb3a0aa5..007ab31bbf 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -111,6 +111,14 @@ def cart(db): # pylint: disable=W0613
return Cart.objects.create()
+def cart_with_item(cart, product):
+ variant = product.variants.get()
+ add_variant_to_cart(cart, variant, 3)
+ cart.save()
+ return cart
+
+
@pytest.fixture
def cart_with_voucher(cart, product, voucher):
variant = product.variants.get()
diff --git a/tests/dashboard/test_discounts.py b/tests/dashboard/test_discounts.py
index 613f1cd2fe..34d6873264 100644
--- a/tests/dashboard/test_discounts.py
+++ b/tests/dashboard/test_discounts.py
@@ -9,7 +9,8 @@ from django.urls import reverse
from prices import Money, TaxedMoney
from saleor.dashboard.order.utils import get_voucher_discount_for_order
from saleor.discount import DiscountValueType, VoucherType
-from saleor.discount.models import Sale, Voucher
+from saleor.discount.models import Sale, Voucher, NotApplicable
+from saleor.product.models import Collection
def test_sales_list(admin_client, sale):
@@ -55,7 +56,8 @@ def test_view_sale_add(admin_client, default_category, collection):
'type': DiscountValueType.PERCENTAGE,
'value': 100,
'categories': [default_category.id],
- 'collections': [collection.id]}
+ 'collections': [collection.id],
+ 'start_date': '2018-01-01'}
response = admin_client.post(url, data)
@@ -67,34 +69,28 @@ def test_view_sale_add(admin_client, default_category, collection):
assert collection in sale.collections.all()
-def test_view_sale_add_requires_product_or_category(
- admin_client, default_category, product):
+def test_view_sale_add_requires_product_category_or_collection(
+ admin_client, default_category, product, collection):
+ initial_sales_count = Sale.objects.count()
url = reverse('dashboard:sale-add')
data = {
'name': 'Free products',
'type': DiscountValueType.PERCENTAGE,
- 'value': 100}
+ 'value': 100,
+ 'start_date': '2018-01-01'}
response = admin_client.post(url, data)
assert response.status_code == 200
- assert Sale.objects.count() == 0
-
- data_with_category = data.copy()
- data_with_category.update({'categories': [default_category.id]})
-
- response = admin_client.post(url, data_with_category)
-
- assert response.status_code == 302
- assert Sale.objects.count() == 1
-
- data_with_product = data.copy()
- data_with_product.update({'products': [product.id]})
-
- response = admin_client.post(url, data_with_product)
-
- assert response.status_code == 302
- assert Sale.objects.count() == 2
+ assert Sale.objects.count() == initial_sales_count
+ products_data = [
+ {'categories': [default_category.id]},
+ {'products': [product.id]}, {'collections': [collection.pk]}]
+ for count, proper_data in enumerate(products_data):
+ proper_data.update(data)
+ response = admin_client.post(url, proper_data)
+ assert response.status_code == 302
+ assert Sale.objects.count() == 1 + initial_sales_count + count
@pytest.mark.parametrize(
@@ -114,18 +110,6 @@ def test_value_voucher_order_discount(
assert discount == Money(expected_value, 'USD')
-def test_value_voucher_order_discount_not_applicable_returns_zero(settings):
- voucher = Voucher(
- code='unique', type=VoucherType.VALUE,
- discount_value_type=DiscountValueType.FIXED,
- discount_value=10,
- limit=Money(100, 'USD'))
- subtotal = TaxedMoney(net=Money(10, 'USD'), gross=Money(10, 'USD'))
- order = Mock(get_subtotal=Mock(return_value=subtotal), voucher=voucher)
- discount = get_voucher_discount_for_order(order)
- assert discount == Money(0, 'USD')
-
-
@pytest.mark.parametrize(
'shipping_cost, discount_value, discount_type, expected_value', [
(10, 50, DiscountValueType.PERCENTAGE, 5),
@@ -159,35 +143,41 @@ def test_shipping_voucher_checkout_discount_not_applicable_returns_zero():
get_subtotal=Mock(return_value=price),
shipping_price=price,
voucher=voucher)
- discount = get_voucher_discount_for_order(order)
- assert discount == Money(0, 'USD')
+ with pytest.raises(NotApplicable):
+ get_voucher_discount_for_order(order)
-def test_product_voucher_checkout_discount_not_applicable_returns_zero(
- monkeypatch):
- monkeypatch.setattr(
- 'saleor.dashboard.order.utils.get_product_variants_and_prices',
- lambda order, product: [])
+def test_product_voucher_checkout_discount_raises_not_applicable(
+ order_with_lines, product_with_images):
+ discounted_product = product_with_images
voucher = Voucher(
code='unique', type=VoucherType.PRODUCT,
discount_value_type=DiscountValueType.FIXED,
discount_value=10)
- order = Mock(voucher=voucher)
- discount = get_voucher_discount_for_order(order)
- assert discount == Money(0, 'USD')
-
-
-def test_category_voucher_checkout_discount_not_applicable(monkeypatch):
- monkeypatch.setattr(
- 'saleor.dashboard.order.utils.get_category_variants_and_prices',
- lambda order, product: [])
+ voucher.save()
+ voucher.products.add(discounted_product)
+ order_with_lines.voucher = voucher
+ order_with_lines.save()
+ # Offer is valid only for products listed in voucher
+ with pytest.raises(NotApplicable):
+ get_voucher_discount_for_order(order_with_lines)
+
+
+def test_category_voucher_checkout_discount_raises_not_applicable(
+ monkeypatch, order_with_lines):
+ discounted_collection = Collection.objects.create(
+ name='Discounted', slug='discou')
voucher = Voucher(
code='unique', type=VoucherType.CATEGORY,
discount_value_type=DiscountValueType.FIXED,
discount_value=10)
- order = Mock(voucher=voucher)
- discount = get_voucher_discount_for_order(order)
- assert discount == Money(0, 'USD')
+ voucher.save()
+ voucher.collections.add(discounted_collection)
+ order_with_lines.voucher = voucher
+ order_with_lines.save()
+ # Discount should be valid only for items in the discounted collections
+ with pytest.raises(NotApplicable):
+ get_voucher_discount_for_order(order_with_lines)
def test_ajax_voucher_list(admin_client, voucher):
diff --git a/tests/test_cart.py b/tests/test_cart.py
index 1e5d6e4417..73891e615e 100644
--- a/tests/test_cart.py
+++ b/tests/test_cart.py
@@ -287,13 +287,12 @@ def test_cart_counter(monkeypatch):
assert ret == {'cart_counter': 4}
-def test_get_product_variants_and_prices():
- variant = Mock(product_id=1, id=1, get_price=Mock(return_value=10))
- cart = MagicMock(spec=Cart)
- cart.__iter__ = Mock(
- return_value=iter([Mock(quantity=1, variant=variant)]))
- variants = list(utils.get_product_variants_and_prices(cart, variant))
- assert variants == [(variant, 10)]
+def test_get_prices_of_discounted_products(cart_with_item):
+ discounted_line = cart_with_item.lines.first()
+ discounted_product = discounted_line.variant.product
+ prices = utils.get_prices_of_discounted_products(
+ cart_with_item, [discounted_product])
+ assert prices == [discounted_line.get_total()]
def test_contains_unavailable_variants():
@@ -588,12 +587,14 @@ def test_cart_line_state(product, request_cart_with_item):
assert line.quantity == 2
-def test_get_category_variants_and_prices(
- default_category, product, request_cart_with_item):
- result = list(utils.get_category_variants_and_prices(
- request_cart_with_item, default_category))
- variant = product.variants.get()
- assert result[0][0] == variant
+def test_get_prices_of_products_in_discounted_collections(
+ collection, product, cart_with_item):
+ discounted_line = cart_with_item.lines.first()
+ assert discounted_line.variant.product == product
+ product.collections.add(collection)
+ result = utils.get_prices_of_products_in_discounted_collections(
+ cart_with_item, [collection])
+ assert result == [discounted_line.get_total()]
def test_update_view_must_be_ajax(customer_user, rf):
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index cddd3dd38a..a410b6cd1c 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -508,7 +508,7 @@ def test_note_in_created_order_empty_note(request_cart_with_item, address):
('100', 10, DiscountValueType.FIXED, None, 10),
('100.05', 10, DiscountValueType.PERCENTAGE, 100, 10)])
def test_get_discount_for_cart_value_voucher(
- settings, total, discount_value, discount_type, limit,
+ total, discount_value, discount_type, limit,
discount_amount):
voucher = Voucher(
code='unique',
@@ -522,7 +522,7 @@ def test_get_discount_for_cart_value_voucher(
assert discount == Money(discount_amount, 'USD')
-def test_get_discount_for_cart_value_voucher_not_applicable(settings):
+def test_get_discount_for_cart_value_voucher_not_applicable():
voucher = Voucher(
code='unique',
type=VoucherType.VALUE,
@@ -538,14 +538,14 @@ def test_get_discount_for_cart_value_voucher_not_applicable(settings):
@pytest.mark.parametrize(
'shipping_cost, shipping_country_code, discount_value, discount_type,'
- 'apply_to, expected_value', [
- (10, None, 50, DiscountValueType.PERCENTAGE, None, 5),
- (10, None, 20, DiscountValueType.FIXED, None, 10),
- (10, 'PL', 20, DiscountValueType.FIXED, '', 10),
- (5, 'PL', 5, DiscountValueType.FIXED, 'PL', 5)])
+ 'countries, expected_value', [
+ (10, None, 50, DiscountValueType.PERCENTAGE, [], 5),
+ (10, None, 20, DiscountValueType.FIXED, [], 10),
+ (10, 'PL', 20, DiscountValueType.FIXED, [], 10),
+ (5, 'PL', 5, DiscountValueType.FIXED, ['PL'], 5)])
def test_get_discount_for_cart_shipping_voucher(
- settings, shipping_cost, shipping_country_code, discount_value,
- discount_type, apply_to, expected_value):
+ shipping_cost, shipping_country_code, discount_value,
+ discount_type, countries, expected_value):
subtotal = TaxedMoney(net=Money(100, 'USD'), gross=Money(100, 'USD'))
shipping_total = TaxedMoney(
net=Money(shipping_cost, 'USD'), gross=Money(shipping_cost, 'USD'))
@@ -560,7 +560,7 @@ def test_get_discount_for_cart_shipping_voucher(
code='unique', type=VoucherType.SHIPPING,
discount_value_type=discount_type,
discount_value=discount_value,
- apply_to=apply_to,
+ countries=countries,
limit=None)
discount = get_voucher_discount_for_cart(voucher, cart)
assert discount == Money(expected_value, 'USD')
@@ -568,22 +568,22 @@ def test_get_discount_for_cart_shipping_voucher(
@pytest.mark.parametrize(
'is_shipping_required, shipping_method, discount_value, discount_type,'
- 'apply_to, limit, subtotal, error_msg', [
+ 'countries, limit, subtotal, error_msg', [
(True, Mock(country_code='PL'), 10, DiscountValueType.FIXED,
- 'US', None, Money(10, 'USD'),
- 'This offer is only valid in United States of America.'),
+ ['US'], None, Money(10, 'USD'),
+ 'This offer is not valid in your country.'),
(True, None, 10, DiscountValueType.FIXED,
- None, None, Money(10, 'USD'),
+ [], None, Money(10, 'USD'),
'Please select a shipping method first.'),
(False, None, 10, DiscountValueType.FIXED,
- None, None, Money(10, 'USD'),
+ [], None, Money(10, 'USD'),
'Your order does not require shipping.'),
(True, Mock(price=Money(10, 'USD')), 10,
- DiscountValueType.FIXED, None, 5, Money(2, 'USD'),
+ DiscountValueType.FIXED, [], 5, Money(2, 'USD'),
'This offer is only valid for orders over $5.00.')])
def test_get_discount_for_cart_shipping_voucher_not_applicable(
- settings, is_shipping_required, shipping_method, discount_value,
- discount_type, apply_to, limit, subtotal, error_msg):
+ is_shipping_required, shipping_method, discount_value,
+ discount_type, countries, limit, subtotal, error_msg):
subtotal_price = TaxedMoney(net=subtotal, gross=subtotal)
cart = Mock(
get_subtotal=Mock(return_value=subtotal_price),
@@ -594,21 +594,21 @@ def test_get_discount_for_cart_shipping_voucher_not_applicable(
discount_value_type=discount_type,
discount_value=discount_value,
limit=Money(limit, 'USD') if limit is not None else None,
- apply_to=apply_to)
+ countries=countries)
with pytest.raises(NotApplicable) as e:
get_voucher_discount_for_cart(voucher, cart)
assert str(e.value) == error_msg
-def test_get_discount_for_cart_product_voucher_not_applicable(
- settings, monkeypatch):
+def test_get_discount_for_cart_product_voucher_not_applicable(monkeypatch):
monkeypatch.setattr(
- 'saleor.checkout.utils.get_product_variants_and_prices',
+ 'saleor.checkout.utils.get_prices_of_discounted_products',
lambda cart, product: [])
voucher = Voucher(
code='unique', type=VoucherType.PRODUCT,
discount_value_type=DiscountValueType.FIXED,
discount_value=10)
+ voucher.save()
cart = Mock()
with pytest.raises(NotApplicable) as e:
@@ -616,15 +616,15 @@ def test_get_discount_for_cart_product_voucher_not_applicable(
assert str(e.value) == 'This offer is only valid for selected items.'
-def test_get_discount_for_cart_category_voucher_not_applicable(
- settings, monkeypatch):
+def test_get_discount_for_cart_category_voucher_not_applicable(monkeypatch):
monkeypatch.setattr(
- 'saleor.checkout.utils.get_category_variants_and_prices',
+ 'saleor.checkout.utils.get_prices_of_products_in_discounted_collections', # noqa
lambda cart, product: [])
voucher = Voucher(
code='unique', type=VoucherType.CATEGORY,
discount_value_type=DiscountValueType.FIXED,
discount_value=10)
+ voucher.save()
cart = Mock()
with pytest.raises(NotApplicable) as e:
diff --git a/tests/test_discounts.py b/tests/test_discounts.py
index 44c034a809..b01798d65c 100644
--- a/tests/test_discounts.py
+++ b/tests/test_discounts.py
@@ -6,11 +6,11 @@ from prices import Money, TaxedMoney
from saleor.checkout.utils import get_voucher_discount_for_cart
from saleor.discount import (
- DiscountValueType, VoucherApplyToProduct, VoucherType)
+ DiscountValueType, VoucherType)
from saleor.discount.models import NotApplicable, Sale, Voucher
from saleor.discount.utils import (
decrease_voucher_usage, get_product_discount_on_sale,
- get_product_or_category_voucher_discount, get_shipping_voucher_discount,
+ get_products_voucher_discount, get_shipping_voucher_discount,
get_value_voucher_discount, increase_voucher_usage)
from saleor.product.models import Product, ProductVariant
@@ -65,51 +65,38 @@ def test_voucher_queryset_active(voucher):
date=date.today() - timedelta(days=1))
assert len(active_vouchers) == 0
-
- 'prices, discount_value, discount_type, apply_to, expected_value', [
- (
- [10], 10, DiscountValueType.FIXED,
- VoucherApplyToProduct.ONE_PRODUCT, 10),
- (
- [5], 10, DiscountValueType.FIXED,
- VoucherApplyToProduct.ONE_PRODUCT, 5),
- (
- [5, 5], 10, DiscountValueType.FIXED,
- VoucherApplyToProduct.ONE_PRODUCT, 10),
- (
- [2, 3], 10, DiscountValueType.FIXED,
- VoucherApplyToProduct.ONE_PRODUCT, 5),
-
- (
- [10, 10], 5, DiscountValueType.FIXED,
- VoucherApplyToProduct.ALL_PRODUCTS, 10),
- (
- [5, 2], 5, DiscountValueType.FIXED,
- VoucherApplyToProduct.ALL_PRODUCTS, 7),
- (
- [10, 10, 10], 5, DiscountValueType.FIXED,
- VoucherApplyToProduct.ALL_PRODUCTS, 15),
-
- ([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):
- monkeypatch.setattr(
- 'saleor.checkout.utils.get_product_variants_and_prices',
- lambda cart, product: (
- (None, TaxedMoney(
- net=Money(price, 'USD'), gross=Money(price, 'USD')))
- for price in prices))
- voucher = Voucher(
- code='unique', type=VoucherType.PRODUCT,
- discount_value_type=discount_type,
- discount_value=discount_value,
- apply_to=apply_to)
- checkout = Mock(cart=Mock())
- discount = get_voucher_discount_for_cart(voucher, checkout)
- assert discount == Money(expected_value, 'USD')
+#FIXME What is this test?
+# @pytest.mark.parametrize(
+# 'prices, discount_value, discount_type, expected_value', [
+# (
+# [10], 10, DiscountValueType.FIXED, 10),
+# (
+# [5], 10, DiscountValueType.FIXED, 5),
+# (
+# [5, 5], 10, DiscountValueType.FIXED, 10),
+# (
+# [2, 3], 10, DiscountValueType.FIXED, 5),
+
+# (
+# [10, 10], 5, DiscountValueType.FIXED, 10),
+# (
+# [5, 2], 5, DiscountValueType.FIXED, 7),
+# (
+# [10, 10, 10], 5, DiscountValueType.FIXED, 15),
+
+# ([10], 10, DiscountValueType.PERCENTAGE, 1),
+# ([10, 10], 10, DiscountValueType.PERCENTAGE, 2)])
+# def test_products_voucher_checkout_discount_not(
+# settings, monkeypatch, prices, discount_value, discount_type,
+# expected_value, cart_with_item):
+# voucher = Voucher(
+# code='unique', type=VoucherType.PRODUCT,
+# discount_value_type=discount_type,
+# discount_value=discount_value)
+# voucher.save()
+# checkout = cart_with_item
+# discount = get_voucher_discount_for_cart(voucher, checkout)
+# assert discount == Money(expected_value, 'USD')
def test_sale_applies_to_correct_products(product_type, default_category):
@@ -166,6 +153,7 @@ def test_get_value_voucher_discount(
discount_value_type=discount_value_type,
discount_value=discount_value,
limit=Money(limit, 'USD') if limit is not None else None)
+ voucher.save()
total_price = TaxedMoney(
net=Money(total, 'USD'), gross=Money(total, 'USD'))
discount = get_value_voucher_discount(voucher, total_price)
@@ -186,6 +174,7 @@ def test_get_shipping_voucher_discount(
discount_value_type=discount_value_type,
discount_value=discount_value,
limit=Money(limit, 'USD') if limit is not None else None)
+ voucher.save()
total = TaxedMoney(
net=Money(total, 'USD'), gross=Money(total, 'USD'))
shipping_price = TaxedMoney(
@@ -195,25 +184,20 @@ def test_get_shipping_voucher_discount(
@pytest.mark.parametrize(
- 'prices, discount_value_type, discount_value, voucher_type, apply_to, expected_value', [ # noqa
- ([5, 10, 15], DiscountValueType.PERCENTAGE, 10, VoucherType.PRODUCT,
- VoucherApplyToProduct.ALL_PRODUCTS, 3),
- ([5, 10, 15], DiscountValueType.FIXED, 2, VoucherType.PRODUCT,
- VoucherApplyToProduct.ALL_PRODUCTS, 6),
- ([5, 10, 15], DiscountValueType.FIXED, 2, VoucherType.PRODUCT,
- VoucherApplyToProduct.ONE_PRODUCT, 2),
- ([5, 10, 15], DiscountValueType.FIXED, 2, VoucherType.CATEGORY,
- None, 2)])
-def test_get_product_or_category_voucher_discount_all_products(
- prices, discount_value_type, discount_value, voucher_type, apply_to,
+ 'prices, discount_value_type, discount_value, voucher_type, expected_value', [ # noqa
+ ([5, 10, 15], DiscountValueType.PERCENTAGE, 10, VoucherType.PRODUCT, 3),
+ ([5, 10, 15], DiscountValueType.FIXED, 2, VoucherType.PRODUCT, 2),
+ ([5, 10, 15], DiscountValueType.FIXED, 2, VoucherType.CATEGORY, 2)])
+def test_get_voucher_discount_all_products(
+ prices, discount_value_type, discount_value, voucher_type,
expected_value):
prices = [
TaxedMoney(net=Money(price, 'USD'), gross=Money(price, 'USD'))
for price in prices]
voucher = Voucher(
- code='unique', type=voucher_type, apply_to=apply_to,
+ code='unique', type=voucher_type,
discount_value_type=discount_value_type,
discount_value=discount_value)
-
- discount = get_product_or_category_voucher_discount(voucher, prices)
+ voucher.save()
+ discount = get_products_voucher_discount(voucher, prices)
assert discount == Money(expected_value, 'USD')