Skip to content

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

Replace Category Voucher with Collection

Pacu24289d67bc915
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 79c044124f..57108f7932 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -74,18 +74,22 @@ def remove_unavailable_variants(cart):
add_variant_to_cart(cart, line.variant, quantity, replace=True)
+def get_variant_prices_from_lines(lines):
+ return [
+ line.variant.get_price()
+ for line in lines
+ for item in range(line.quantity)]
+
+
def get_prices_of_discounted_products(lines, discounted_products):
"""Get variants and unit prices from cart lines matching the product."""
# 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
+ if discounted_products:
+ lines = (
+ line for line in lines
+ if line.variant.product in discounted_products)
+ return get_variant_prices_from_lines(lines)
def get_prices_of_products_in_discounted_collections(
@@ -97,15 +101,32 @@ def get_prices_of_products_in_discounted_collections(
"""
# 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]
+ if discounted_collections:
+ discounted_collections = set(discounted_collections)
+ lines = (
+ line for line in lines
+ if line.variant and
+ set(line.variant.product.collections.all()).intersection(
+ discounted_collections))
+ return get_variant_prices_from_lines(lines)
+
+
+def get_prices_of_products_in_discounted_categories(
+ lines, discounted_categories):
+ """Get variants and unit prices from cart lines matching the category.
- 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
+ Product is assumed to be in the category if it belongs to any of its
+ descendant subcategories.
+ """
+ # If there's no discounted collections,
+ # it means that all of them are discounted
+ if discounted_categories:
+ discounted_categories = set(discounted_categories)
+ lines = (
+ line for line in lines
+ if line.variant and
+ line.variant.product.category in discounted_categories)
+ return get_variant_prices_from_lines(lines)
def check_product_availability_and_warn(request, cart):
@@ -650,9 +671,12 @@ def _get_products_voucher_discount(order_or_cart, voucher):
if voucher.type == VoucherType.PRODUCT:
prices = get_prices_of_discounted_products(
order_or_cart.lines.all(), voucher.products.all())
- else:
+ elif voucher.type == VoucherType.COLLECTION:
prices = get_prices_of_products_in_discounted_collections(
order_or_cart.lines.all(), voucher.collections.all())
+ elif voucher.type == VoucherType.CATEGORY:
+ prices = get_prices_of_products_in_discounted_categories(
+ order_or_cart.lines.all(), voucher.categories.all())
if not prices:
msg = pgettext(
'Voucher not applicable',
@@ -670,7 +694,8 @@ def get_voucher_discount_for_cart(voucher, cart):
return get_value_voucher_discount(voucher, cart.get_subtotal())
if voucher.type == VoucherType.SHIPPING:
return _get_shipping_voucher_discount_for_cart(voucher, cart)
- if voucher.type in (VoucherType.PRODUCT, VoucherType.CATEGORY):
+ if voucher.type in (
+ VoucherType.PRODUCT, VoucherType.COLLECTION, VoucherType.CATEGORY):
return _get_products_voucher_discount(cart, voucher)
raise NotImplementedError('Unknown discount type')
diff --git a/saleor/core/middleware.py b/saleor/core/middleware.py
index 02d5c2d588..e97cf35f5b 100644
--- a/saleor/core/middleware.py
+++ b/saleor/core/middleware.py
@@ -1,4 +1,5 @@
import logging
+from datetime import date
from django.conf import settings
from django.contrib.sites.models import Site
@@ -33,7 +34,7 @@ def google_analytics(get_response):
def discounts(get_response):
"""Assign active discounts to `request.discounts`."""
def middleware(request):
- discounts = Sale.objects.prefetch_related(
+ discounts = Sale.objects.active(date.today()).prefetch_related(
'products', 'categories', 'collections')
request.discounts = discounts
return get_response(request)
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index c16bca832b..0b28e0a3bc 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -2,6 +2,7 @@ import itertools
import os
import random
import unicodedata
+from datetime import date
from decimal import Decimal
from django.conf import settings
@@ -491,7 +492,7 @@ def create_users(how_many=10):
def create_orders(how_many=10):
taxes = get_taxes_for_country(Country(settings.DEFAULT_COUNTRY))
- discounts = Sale.objects.prefetch_related(
+ discounts = Sale.objects.active(date.today()).prefetch_related(
'products', 'categories', 'collections')
for dummy in range(how_many):
order = create_fake_order(discounts, taxes)
diff --git a/saleor/dashboard/discount/filters.py b/saleor/dashboard/discount/filters.py
index 177b2091c3..3df52ee731 100644
--- a/saleor/dashboard/discount/filters.py
+++ b/saleor/dashboard/discount/filters.py
@@ -12,7 +12,9 @@ from ..widgets import DateRangeWidget
SORT_BY_FIELDS_SALE = {
'name': pgettext_lazy('Sale list sorting option', 'name'),
- 'value': pgettext_lazy('Sale list sorting option', 'value')}
+ 'value': pgettext_lazy('Sale list sorting option', 'value'),
+ 'start_date': pgettext_lazy('Sale list sorting option', 'start_date'),
+ 'end_date': pgettext_lazy('Sale list sorting option', 'end_date')}
SORT_BY_FIELDS_LABELS_VOUCHER = {
'name': pgettext_lazy('Voucher list sorting option', 'name'),
@@ -30,6 +32,18 @@ DISCOUNT_TYPE_CHOICES = (
('percentage', pgettext_lazy('Sale type filter choice', '%')))
+def filter_by_date_range(queryset, name, value):
+ q = Q()
+ if value.start:
+ q = Q(start_date__gte=value.start)
+ if value.stop:
+ if value.start:
+ q |= Q(end_date__lte=value.stop)
+ else:
+ q = Q(end_date__lte=value.stop)
+ return queryset.filter(q)
+
+
class SaleFilter(SortedFilterSet):
name = CharFilter(
label=pgettext_lazy('Sale list filter label', 'Name'),
@@ -45,6 +59,10 @@ class SaleFilter(SortedFilterSet):
widget=forms.Select)
value = RangeFilter(
label=pgettext_lazy('Sale list filter label', 'Value'))
+ date = DateFromToRangeFilter(
+ label=pgettext_lazy(
+ 'Sale list sorting filter label', 'Period of validity'),
+ name='created', widget=DateRangeWidget, method=filter_by_date_range)
sort_by = OrderingFilter(
label=pgettext_lazy('Sale list filter label', 'Sort by'),
fields=SORT_BY_FIELDS_SALE.keys(),
@@ -78,8 +96,8 @@ class VoucherFilter(SortedFilterSet):
label=pgettext_lazy('Sale list filter label', 'Discount_value'))
date = DateFromToRangeFilter(
label=pgettext_lazy(
- 'Order list sorting filter label', 'Period of validity'),
- name='created', widget=DateRangeWidget, method='filter_by_date_range')
+ 'Voucher list sorting filter label', 'Period of validity'),
+ name='created', widget=DateRangeWidget, method=filter_by_date_range)
min_amount_spent = RangeFilter(
label=pgettext_lazy(
'Voucher list sorting filter', 'Minimum amount spent'),
@@ -93,17 +111,6 @@ class VoucherFilter(SortedFilterSet):
model = Voucher
fields = []
- def filter_by_date_range(self, queryset, name, value):
- q = Q()
- if value.start:
- q = Q(start_date__gte=value.start)
- if value.stop:
- if value.start:
- q |= Q(end_date__lte=value.stop)
- else:
- q = Q(end_date__lte=value.stop)
- return queryset.filter(q)
-
def get_summary_message(self):
counter = self.qs.count()
return npgettext(
diff --git a/saleor/dashboard/discount/forms.py b/saleor/dashboard/discount/forms.py
index 7273007b8a..e75382b70b 100644
--- a/saleor/dashboard/discount/forms.py
+++ b/saleor/dashboard/discount/forms.py
@@ -5,12 +5,13 @@ from django.conf import settings
from django.urls import reverse_lazy
from django.utils.translation import pgettext_lazy
from django_prices.forms import MoneyField
+from mptt.forms import TreeNodeMultipleChoiceField
from ...core.i18n import COUNTRY_CODE_CHOICES
from ...core.utils.taxes import ZERO_MONEY
from ...discount import DiscountValueType
from ...discount.models import Sale, Voucher
-from ...product.models import Product
+from ...product.models import Category, Product
from ...shipping.models import ShippingMethodCountry
from ..forms import AjaxSelect2MultipleChoiceField
@@ -32,6 +33,12 @@ class SaleForm(forms.ModelForm):
'type': pgettext_lazy(
'Discount type',
'Fixed or percentage'),
+ 'start_date': pgettext_lazy(
+ 'Sale date restrictions',
+ 'Start date'),
+ 'end_date': pgettext_lazy(
+ 'Sale date restrictions',
+ 'End date'),
'value': pgettext_lazy(
'Percentage or fixed amount value',
'Value'),
@@ -70,7 +77,9 @@ class VoucherForm(forms.ModelForm):
class Meta:
model = Voucher
- exclude = ['min_amount_spent', 'countries', 'products', 'collections', 'used']
+ exclude = [
+ 'min_amount_spent', 'countries', 'products', 'collections',
+ 'categories', 'used']
labels = {
'type': pgettext_lazy(
'Discount type',
@@ -129,13 +138,13 @@ class ShippingVoucherForm(forms.ModelForm):
currency=settings.DEFAULT_CURRENCY,
label=pgettext_lazy(
'Lowest value for order to be able to use the voucher',
- 'Only if order is over or equal to'))
- countries = forms.ChoiceField(
+ 'Apply only if the purchase value is greater than or equal to'))
+ countries = forms.MultipleChoiceField(
choices=country_choices,
required=False,
label=pgettext_lazy(
'Text above the dropdown of countries',
- 'Countries that free shipping should apply to'))
+ 'Limit countries that voucher should apply to'))
class Meta:
model = Voucher
@@ -152,7 +161,7 @@ class ValueVoucherForm(forms.ModelForm):
currency=settings.DEFAULT_CURRENCY,
label=pgettext_lazy(
'Lowest value for order to be able to use the voucher',
- 'Only apply if purchase value is greater than or equal to'))
+ 'Apply only if the purchase value is greater than or equal to'))
class Meta:
model = Voucher
@@ -170,7 +179,12 @@ class CommonVoucherForm(forms.ModelForm):
use_required_attribute = False
def save(self, commit=True):
- self.instance.min_amount_spent = None
+ 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 whole order.
+ if self.instance.discount_value_type == DiscountValueType.PERCENTAGE:
+ self.instance.apply_once_per_order = True
return super().save(commit)
@@ -183,19 +197,29 @@ class ProductVoucherForm(CommonVoucherForm):
class Meta:
model = Voucher
- fields = ['products']
+ fields = ['products', 'apply_once_per_order']
class CollectionVoucherForm(CommonVoucherForm):
class Meta:
model = Voucher
- fields = ['collections']
+ fields = ['collections', 'apply_once_per_order']
labels = {
'collections': pgettext_lazy(
- 'Collections',
- 'Collections')}
+ 'Collections', 'Collections')}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['collections'].required = True
+
+
+class CategoryVoucherForm(CommonVoucherForm):
+ categories = TreeNodeMultipleChoiceField(
+ queryset=Category.objects.all(),
+ required=True,
+ label=pgettext_lazy('Categories', 'Categories'))
+
+ class Meta:
+ model = Voucher
+ fields = ['categories', 'apply_once_per_order']
diff --git a/saleor/dashboard/discount/views.py b/saleor/dashboard/discount/views.py
index 395e3f45f1..3e2bcadde5 100644
--- a/saleor/dashboard/discount/views.py
+++ b/saleor/dashboard/discount/views.py
@@ -26,7 +26,9 @@ 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.CollectionVoucherForm(
+ VoucherType.COLLECTION: forms.CollectionVoucherForm(
+ data or None, instance=voucher, prefix=VoucherType.COLLECTION),
+ VoucherType.CATEGORY: forms.CategoryVoucherForm(
data or None, instance=voucher, prefix=VoucherType.CATEGORY)}
diff --git a/saleor/dashboard/order/utils.py b/saleor/dashboard/order/utils.py
index b2ac1fa335..3d376e7055 100644
--- a/saleor/dashboard/order/utils.py
+++ b/saleor/dashboard/order/utils.py
@@ -4,14 +4,13 @@ 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_products_voucher_discount,
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_products_voucher_discount, get_shipping_voucher_discount,
- get_value_voucher_discount)
+ get_shipping_voucher_discount, get_value_voucher_discount)
from ...product.utils import decrease_stock
INVOICE_TEMPLATE = 'dashboard/order/pdf/invoice.html'
@@ -90,7 +89,8 @@ def get_voucher_discount_for_order(order):
if order.voucher.type == VoucherType.SHIPPING:
return get_shipping_voucher_discount(
order.voucher, order.get_subtotal(), order.shipping_price)
- if order.voucher.type in (VoucherType.PRODUCT, VoucherType.CATEGORY):
+ if order.voucher.type in (
+ VoucherType.PRODUCT, VoucherType.COLLECTION, VoucherType.CATEGORY):
return _get_products_voucher_discount(order, order.voucher)
raise NotImplementedError('Unknown discount type')
diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.py
index e094965cf0..a05a03cdc4 100644
--- a/saleor/dashboard/product/views.py
+++ b/saleor/dashboard/product/views.py
@@ -1,3 +1,5 @@
+from datetime import date
+
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import permission_required
@@ -303,7 +305,7 @@ def variant_details(request, product_pk, variant_pk):
images = variant.images.all()
margin = get_margin_for_variant(variant)
- discounted_price = variant.get_price(discounts=Sale.objects.all()).gross
+ discounted_price = variant.get_price(discounts=Sale.objects.active(date.today())).gross
ctx = {
'images': images, 'product': product, 'variant': variant,
'margin': margin, 'discounted_price': discounted_price}
diff --git a/saleor/data_feeds/google_merchant.py b/saleor/data_feeds/google_merchant.py
index 52965ae43a..7f7fa9e223 100644
--- a/saleor/data_feeds/google_merchant.py
+++ b/saleor/data_feeds/google_merchant.py
@@ -1,5 +1,6 @@
import csv
import gzip
+from datetime import date
from django.conf import settings
from django.contrib.sites.models import Site
@@ -195,7 +196,7 @@ def write_feed(file_obj):
writer = csv.DictWriter(file_obj, ATTRIBUTES, dialect=csv.excel_tab)
writer.writeheader()
categories = Category.objects.all()
- discounts = Sale.objects.all().prefetch_related('products',
+ discounts = Sale.objects.active(date.today()).prefetch_related('products',
'categories')
attributes_dict = {a.slug: a.pk for a in ProductAttribute.objects.all()}
attribute_values_dict = {smart_text(a.pk): smart_text(a) for a
diff --git a/saleor/discount/__init__.py b/saleor/discount/__init__.py
index 4ca1489651..5219d88a8c 100644
--- a/saleor/discount/__init__.py
+++ b/saleor/discount/__init__.py
@@ -14,13 +14,16 @@ class DiscountValueType:
class VoucherType:
PRODUCT = 'product'
+ COLLECTION = 'collection'
CATEGORY = 'category'
SHIPPING = 'shipping'
VALUE = 'value'
CHOICES = [
- (VALUE, pgettext_lazy('Voucher: discount for', 'All purchases')),
- (PRODUCT, pgettext_lazy('Voucher: discount for', 'One product')),
+ (VALUE, pgettext_lazy('Voucher: discount for', 'All products')),
+ (PRODUCT, pgettext_lazy('Voucher: discount for', 'Specific products')),
+ (COLLECTION, pgettext_lazy(
+ 'Voucher: discount for', 'Specific collections of products')),
(CATEGORY, pgettext_lazy(
- 'Voucher: discount for', 'A category of products')),
+ 'Voucher: discount for', 'Specific categories of products')),
(SHIPPING, pgettext_lazy('Voucher: discount for', 'Shipping'))]
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 6d12452834..d05abc38e4 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -44,13 +44,15 @@ class Voucher(models.Model):
used = models.PositiveIntegerField(default=0, editable=False)
start_date = models.DateField(default=date.today)
end_date = models.DateField(null=True, blank=True)
-
+ # this field indicates if discount should be applied per order or
+ # individually to every item
+ apply_once_per_order = models.BooleanField(default=False)
discount_value_type = models.CharField(
max_length=10, choices=DiscountValueType.CHOICES,
default=DiscountValueType.FIXED)
discount_value = models.DecimalField(
max_digits=12, decimal_places=settings.DEFAULT_DECIMAL_PLACES)
-
+ apply_once_per_customer = models.BooleanField(default=False)
# not mandatory fields, usage depends on type
countries = CountryField(multiple=True, blank=True)
min_amount_spent = MoneyField(
@@ -58,6 +60,7 @@ class Voucher(models.Model):
decimal_places=settings.DEFAULT_DECIMAL_PLACES, null=True, blank=True)
products = models.ManyToManyField('product.Product', blank=True)
collections = models.ManyToManyField('product.Collection', blank=True)
+ categories = models.ManyToManyField('product.Category', blank=True)
objects = VoucherQueryset.as_manager()
@@ -73,18 +76,29 @@ class Voucher(models.Model):
'Voucher type',
'%(discount)s off shipping') % {'discount': discount}
if self.type == VoucherType.PRODUCT:
- return pgettext(
- 'Voucher type',
- '%(discount)s off %(product_num)d products') % {
- 'discount': discount,
- 'product_num': len(self.products.all())}
- # TODO its collections now
+ products = len(self.products.all())
+ if products:
+ return pgettext(
+ 'Voucher type',
+ '%(discount)s off %(product_num)d products') % {
+ 'discount': discount,
+ 'product_num': products}
+ if self.type == VoucherType.COLLECTION:
+ collections = len(self.collections.all())
+ if collections:
+ return pgettext(
+ 'Voucher type',
+ '%(discount)s off %(collections_num)d collections') % {
+ 'discount': discount,
+ 'collections_num': collections}
if self.type == VoucherType.CATEGORY:
- return pgettext(
- 'Voucher type',
- '%(discount)s off %(collections_num)d collections') % {
- 'discount': discount,
- 'collections_num': len(self.collections.all())}
+ categories = len(self.categories.all())
+ if categories:
+ return pgettext(
+ 'Voucher type',
+ '%(discount)s off %(categories_num)d categories') % {
+ 'discount': discount,
+ 'categories_num': categories}
return pgettext(
'Voucher type', '%(discount)s off') % {'discount': discount}
@@ -122,6 +136,12 @@ class Voucher(models.Model):
min_amount_spent=min_amount_spent)
+class SaleQueryset(models.QuerySet):
+ def active(self, date):
+ return self.filter(
+ end_date__gte=date, start_date__lte=date)
+
+
class Sale(models.Model):
name = models.CharField(max_length=255)
type = models.CharField(
@@ -136,6 +156,8 @@ class Sale(models.Model):
start_date = models.DateField(default=date.today)
end_date = models.DateField(null=True, blank=True)
+ objects = SaleQueryset.as_manager()
+
class Meta:
app_label = 'discount'
permissions = ((
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 6818bab059..9bd5482dc9 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -1,7 +1,7 @@
from django.db.models import F
from django.utils.translation import pgettext
-from ..core.utils.taxes import ZERO_TAXED_MONEY
+from ..core.utils.taxes import ZERO_TAXED_MONEY, ZERO_MONEY
from .models import NotApplicable
@@ -78,5 +78,10 @@ def get_shipping_voucher_discount(voucher, total_price, shipping_price):
def get_products_voucher_discount(voucher, prices):
"""Calculate discount value for a voucher of product or category type."""
- product_total = sum(prices, ZERO_TAXED_MONEY)
- return voucher.get_discount_amount_for(product_total)
+ if voucher.apply_once_per_order:
+ product_total = sum(prices, ZERO_TAXED_MONEY)
+ return voucher.get_discount_amount_for(product_total)
+ discounts = (
+ voucher.get_discount_amount_for(price) for price in prices)
+ total_amount = sum(discounts, ZERO_MONEY)
+ return total_amount
diff --git a/saleor/graphql/discount/mutations.py b/saleor/graphql/discount/mutations.py
index ea8900601b..a19603fffc 100644
--- a/saleor/graphql/discount/mutations.py
+++ b/saleor/graphql/discount/mutations.py
@@ -12,9 +12,12 @@ def validate_voucher(voucher_data):
if voucher_type == VoucherType.PRODUCT:
if not voucher_data.get('products'):
errors.append(('products', 'This field is required.'))
- elif voucher_type == VoucherType.CATEGORY:
+ elif voucher_type == VoucherType.COLLECTION:
if not voucher_data.get('collections'):
errors.append(('collections', 'This field is required.'))
+ elif voucher_type == VoucherType.CATEGORY:
+ if not voucher_data.get('categories'):
+ errors.append(('categories', 'This field is required.'))
return errors
@@ -34,6 +37,8 @@ class VoucherInput(graphene.InputObjectType):
graphene.ID, description='Products discounted by the voucher.')
collections = graphene.List(
graphene.ID, description='Collections discounted by the voucher.')
+ categories = graphene.List(
+ graphene.ID, description='Categories discounted by the voucher.')
min_amount_spent = Decimal(
description='Min purchase amount required to apply the voucher.')
countries = graphene.List(
@@ -102,6 +107,10 @@ class SaleInput(graphene.InputObjectType):
graphene.ID, description='Categories related to the discount.')
collections = graphene.List(
graphene.ID, description='Collections related to the discount.')
+ start_date = graphene.types.datetime.DateTime(
+ description='Start date of the sale in ISO 8601 format.')
+ end_date = graphene.types.datetime.DateTime(
+ description='End date of the sale in ISO 8601 format.')
class SaleCreate(ModelMutation):
diff --git a/saleor/graphql/discount/resolvers.py b/saleor/graphql/discount/resolvers.py
index 467d850cb9..d587f30200 100644
--- a/saleor/graphql/discount/resolvers.py
+++ b/saleor/graphql/discount/resolvers.py
@@ -1,9 +1,12 @@
+from datetime import date
+
from ...discount import models
from ..utils import filter_by_query_param
VOUCHER_SEARCH_FIELDS = (
- 'name', 'code', 'discount_value', 'collections__name', 'products__name',
- 'min_amount_spent', 'countries', 'discount_value_type')
+ 'name', 'code', 'discount_value', 'categories__name', 'collections__name',
+ 'products__name', 'min_amount_spent', 'countries', 'discount_value_type',
+ 'apply_one_per_order', 'apply_once_per_customer')
SALE_SEARCH_FIELDS = ('name', 'value', 'type')
diff --git a/saleor/graphql/discount/types.py b/saleor/graphql/discount/types.py
index 8acd1a42c4..6720fb1380 100644
--- a/saleor/graphql/discount/types.py
+++ b/saleor/graphql/discount/types.py
@@ -29,12 +29,15 @@ class Sale(CountableDjangoObjectType):
filter_fields = {
'name': ['icontains'],
'type': ['icontains'],
- 'value': ['gte', 'lte']}
+ 'value': ['gte', 'lte'],
+ 'start_date': ['exact'],
+ 'end_date': ['exact']}
model = models.Sale
class VoucherTypeEnum(graphene.Enum):
PRODUCT = VoucherType.PRODUCT
+ COLLECTION = VoucherType.COLLECTION
CATEGORY = VoucherType.CATEGORY
SHIPPING = VoucherType.SHIPPING
VALUE = VoucherType.VALUE
diff --git a/templates/dashboard/discount/sale/form.html b/templates/dashboard/discount/sale/form.html
index c936f18d2c..8f399ff234 100644
--- a/templates/dashboard/discount/sale/form.html
+++ b/templates/dashboard/discount/sale/form.html
@@ -89,6 +89,16 @@
{{ form.type|materializecss:"input-field s12" }}
</div>
</div>
+ <div class="row">
+ <div class="col s12 m6">
+ <div class="row">
+ {{ form.start_date|materializecss }}
+ </div>
+ </div>
+ <div class="col s12 m6">
+ {{ form.end_date|materializecss:"input-field s12" }}
+ </div>
+ </div>
<div class="row">
{{ form.products|materializecss }}
</div>
diff --git a/templates/dashboard/discount/sale/list.html b/templates/dashboard/discount/sale/list.html
index d8d2daceaf..c47399df63 100644
--- a/templates/dashboard/discount/sale/list.html
+++ b/templates/dashboard/discount/sale/list.html
@@ -42,6 +42,12 @@
{% trans "Name" context "Sale (discount) table header" as label %}
{% sorting_header 'name' label is_wide=True %}
+ {% trans "Start date" context "Sale (discount) table header" as label %}
+ {% sorting_header 'start_date' label is_wide=True %}
+
+ {% trans "End date" context "Sale (discount) table header" as label %}
+ {% sorting_header 'end_date' label is_wide=True %}
+
{% trans "Discount" context "Sale (discount) table header" as label %}
{% sorting_header 'value' label is_wide=True %}
</tr>
@@ -52,6 +58,12 @@
<td>
{{ sale }}
</td>
+ <td>
+ {{ sale.start_date }}
+ </td>
+ <td>
+ {{ sale.end_date|default_if_none:"-" }}
+ </td>
<td>
{{ sale.value }}{{ sale.get_type_display }}
</td>
diff --git a/tests/api/test_discount.py b/tests/api/test_discount.py
index 5b428945d6..9c75ac6056 100644
--- a/tests/api/test_discount.py
+++ b/tests/api/test_discount.py
@@ -85,6 +85,7 @@ def test_sale_query(
type
name
value
+ startDate
}
}
}
@@ -97,6 +98,7 @@ def test_sale_query(
assert data['type'] == sale.type.upper()
assert data['name'] == sale.name
assert data['value'] == sale.value
+ assert data['startDate'] == sale.start_date.isoformat()
def test_create_voucher(user_api_client, admin_api_client):
@@ -319,39 +321,26 @@ def test_sale_delete_mutation(user_api_client, admin_api_client, sale):
with pytest.raises(sale._meta.model.DoesNotExist):
sale.refresh_from_db()
-# 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.'
+
+def test_validate_voucher(voucher, admin_api_client, product):
+ query = """
+ mutation voucherUpdate(
+ $id: ID!, $type: VoucherTypeEnum) {
+ voucherUpdate(
+ id: $id, input: {type: $type}) {
+ errors {
+ field
+ message
+ }
+ }
+ }
+ """
+ variables = json.dumps({
+ 'type': VoucherTypeEnum.PRODUCT.name,
+ 'id': graphene.Node.to_global_id('Voucher', voucher.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/dashboard/test_discounts.py b/tests/dashboard/test_discounts.py
index b23eebbeee..a2d2f4f26e 100644
--- a/tests/dashboard/test_discounts.py
+++ b/tests/dashboard/test_discounts.py
@@ -164,11 +164,11 @@ def test_product_voucher_checkout_discount_raises_not_applicable(
def test_category_voucher_checkout_discount_raises_not_applicable(
- monkeypatch, order_with_lines):
+ order_with_lines):
discounted_collection = Collection.objects.create(
name='Discounted', slug='discou')
voucher = Voucher(
- code='unique', type=VoucherType.CATEGORY,
+ code='unique', type=VoucherType.COLLECTION,
discount_value_type=DiscountValueType.FIXED,
discount_value=10)
voucher.save()
diff --git a/tests/dashboard/test_taxes.py b/tests/dashboard/test_taxes.py
index 0661e838c1..7e05a7ee83 100644
--- a/tests/dashboard/test_taxes.py
+++ b/tests/dashboard/test_taxes.py
@@ -123,7 +123,7 @@ def test_get_country_name_by_code():
assert country_name == 'Poland'
-def test_apply_tax_to_price_include_tax(site_settings, taxes):
+def test_apply_tax_to_price_do_not_include_tax(site_settings, taxes):
site_settings.include_taxes_in_prices = False
site_settings.save()
@@ -140,7 +140,7 @@ def test_apply_tax_to_price_include_tax(site_settings, taxes):
net=Money(100, 'USD'), gross=Money(108, 'USD'))
-def test_apply_tax_to_price_include_tax_fallback_to_standard_rate(
+def test_apply_tax_to_price_do_not_include_tax_fallback_to_standard_rate(
site_settings, taxes):
site_settings.include_taxes_in_prices = False
site_settings.save()
diff --git a/tests/test_cart.py b/tests/test_cart.py
index 73891e615e..45afc1fa7b 100644
--- a/tests/test_cart.py
+++ b/tests/test_cart.py
@@ -292,7 +292,10 @@ def test_get_prices_of_discounted_products(cart_with_item):
discounted_product = discounted_line.variant.product
prices = utils.get_prices_of_discounted_products(
cart_with_item, [discounted_product])
- assert prices == [discounted_line.get_total()]
+ excepted_value = [
+ discounted_line.variant.get_price()
+ for item in range(discounted_line.quantity)]
+ assert list(prices) == excepted_value
def test_contains_unavailable_variants():
@@ -432,23 +435,23 @@ def test_view_empty_cart(client, request_cart):
assert response.status_code == 200
-def test_view_cart_without_taxes(client, sale, request_cart_with_item):
+def test_view_cart_without_taxes(client, request_cart_with_item):
response = client.get(reverse('cart:index'))
response_cart_line = response.context[0]['cart_lines'][0]
cart_line = request_cart_with_item.lines.first()
assert not response_cart_line['get_total'].tax.amount
- assert not response_cart_line['get_total'] == cart_line.get_total()
+ assert response_cart_line['get_total'] == cart_line.get_total()
assert response.status_code == 200
def test_view_cart_with_taxes(
- settings, client, sale, request_cart_with_item, vatlayer):
+ settings, client, request_cart_with_item, vatlayer):
settings.DEFAULT_COUNTRY = 'PL'
response = client.get(reverse('cart:index'))
response_cart_line = response.context[0]['cart_lines'][0]
cart_line = request_cart_with_item.lines.first()
assert response_cart_line['get_total'].tax.amount
- assert not response_cart_line['get_total'] == cart_line.get_total(
+ assert response_cart_line['get_total'] == cart_line.get_total(
taxes=vatlayer)
assert response.status_code == 200
@@ -594,7 +597,9 @@ def test_get_prices_of_products_in_discounted_collections(
product.collections.add(collection)
result = utils.get_prices_of_products_in_discounted_collections(
cart_with_item, [collection])
- assert result == [discounted_line.get_total()]
+ assert list(result) == [
+ discounted_line.variant.get_price()
+ for item in range(discounted_line.quantity)]
def test_update_view_must_be_ajax(customer_user, rf):
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index d1f4e77458..0a3b5ceae3 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -616,12 +616,13 @@ def test_get_discount_for_cart_product_voucher_not_applicable(monkeypatch):
assert str(e.value) == 'This offer is only valid for selected items.'
-def test_get_discount_for_cart_category_voucher_not_applicable(monkeypatch):
+# FIXME
+def test_get_discount_for_cart_collection_voucher_not_applicable(monkeypatch):
monkeypatch.setattr(
'saleor.checkout.utils.get_prices_of_products_in_discounted_collections', # noqa
lambda cart, product: [])
voucher = Voucher(
- code='unique', type=VoucherType.CATEGORY,
+ code='unique', type=VoucherType.COLLECTION,
discount_value_type=DiscountValueType.FIXED,
discount_value=10)
voucher.save()
diff --git a/tests/test_discounts.py b/tests/test_discounts.py
index 4554b4fda6..28e01ff4f5 100644
--- a/tests/test_discounts.py
+++ b/tests/test_discounts.py
@@ -1,5 +1,4 @@
from datetime import date, timedelta
-from unittest.mock import Mock
import pytest
from prices import Money, TaxedMoney
@@ -71,50 +70,54 @@ def test_voucher_queryset_active(voucher):
date=date.today() - timedelta(days=1))
assert len(active_vouchers) == 0
-# 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')
+
+ 'prices, discount_value, discount_type, '
+ 'apply_once_per_order, expected_value', [
+ (
+ [10], 10, DiscountValueType.FIXED, True, 10),
+ (
+ [5], 10, DiscountValueType.FIXED, True, 5),
+ (
+ [5, 5], 10, DiscountValueType.FIXED, True, 10),
+ (
+ [2, 3], 10, DiscountValueType.FIXED, True, 5),
+
+ (
+ [10, 10], 5, DiscountValueType.FIXED, False, 10),
+ (
+ [5, 2], 5, DiscountValueType.FIXED, False, 7),
+ (
+ [10, 10, 10], 5, DiscountValueType.FIXED, False, 15)])
+def test_products_voucher_checkout_discount_not(
+ settings, monkeypatch, prices, discount_value, discount_type,
+ expected_value, apply_once_per_order, cart_with_item):
+ monkeypatch.setattr(
+ 'saleor.checkout.utils.get_prices_of_discounted_products',
+ lambda lines, discounted_products: (
+ 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_once_per_order=apply_once_per_order)
+ 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):
product = Product.objects.create(
name='Test Product', price=Money(10, 'USD'), description='',
- pk=10, product_type=product_type, category=default_category)
+ pk=111, product_type=product_type, category=default_category)
variant = ProductVariant.objects.create(product=product, sku='firstvar')
product2 = Product.objects.create(
name='Second product', price=Money(15, 'USD'), description='',
product_type=product_type, category=default_category)
sec_variant = ProductVariant.objects.create(
- product=product2, sku='secvar', pk=10)
+ product=product2, sku='secvar', pk=111)
sale = Sale.objects.create(
name='Test sale', value=3, type=DiscountValueType.FIXED)
sale.products.add(product)
@@ -192,10 +195,10 @@ def test_get_shipping_voucher_discount(
@pytest.mark.parametrize(
- 'prices, discount_value_type, discount_value, voucher_type, ''expected_value', [ # noqa
+ '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)])
+ ([5, 10, 15], DiscountValueType.FIXED, 2, VoucherType.COLLECTION, 2)])
def test_get_voucher_discount_all_products(
prices, discount_value_type, discount_value, voucher_type,
expected_value):
@@ -205,7 +208,7 @@ def test_get_voucher_discount_all_products(
voucher = Voucher(
code='unique', type=voucher_type,
discount_value_type=discount_value_type,
- discount_value=discount_value)
+ discount_value=discount_value, apply_once_per_order=True)
voucher.save()
discount = get_products_voucher_discount(voucher, prices)
assert discount == Money(expected_value, 'USD')