Skip to content

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

Create discount app

Michał Ociepkafbbf644871d1
diff --git a/saleor/discount/__init__.py b/saleor/discount/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/discount/migrations/0001_initial.py b/saleor/discount/migrations/0001_initial.py
new file mode 100644
index 0000000000..9fc0db58c1
--- /dev/null
+++ b/saleor/discount/migrations/0001_initial.py
@@ -0,0 +1,28 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9.1 on 2016-01-29 14:26
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ ('product', '0010_auto_20160129_0826'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='Sale',
+ fields=[
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('name', models.CharField(max_length=255)),
+ ('type', models.CharField(choices=[('fixed', 'Fixed amount'), ('percentage', 'Percentage discount')], default='fixed', max_length=10)),
+ ('value', models.DecimalField(decimal_places=2, default=0, max_digits=12)),
+ ('categories', models.ManyToManyField(blank=True, to='product.Category')),
+ ('products', models.ManyToManyField(blank=True, to='product.Product')),
+ ],
+ ),
+ ]
diff --git a/saleor/discount/migrations/__init__.py b/saleor/discount/migrations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
new file mode 100644
index 0000000000..b5096ec771
--- /dev/null
+++ b/saleor/discount/models.py
@@ -0,0 +1,79 @@
+from __future__ import unicode_literals
+
+from django.conf import settings
+from django.db import models
+from django.utils.translation import pgettext_lazy
+from django.utils.encoding import python_2_unicode_compatible
+from prices import FixedDiscount, percentage_discount, Price
+
+
+class NotApplicable(ValueError):
+ pass
+
+
+@python_2_unicode_compatible
+class Sale(models.Model):
+ FIXED = 'fixed'
+ PERCENTAGE = 'percentage'
+
+ DISCOUNT_TYPE_CHOICES = (
+ (FIXED, pgettext_lazy('discount type', 'Fixed amount')),
+ (PERCENTAGE, pgettext_lazy('discount_type', 'Percentage discount')))
+
+ name = models.CharField(max_length=255)
+ type = models.CharField(max_length=10, choices=DISCOUNT_TYPE_CHOICES,
+ default=FIXED)
+ value = models.DecimalField(max_digits=12, decimal_places=2, default=0)
+ products = models.ManyToManyField('product.Product', blank=True)
+ categories = models.ManyToManyField('product.Category', blank=True)
+
+ class Meta:
+ app_label = 'discount'
+
+ def __repr__(self):
+ return 'Sale(name=%r, value=%r, type=%s)' % (
+ str(self.name), self.value, self.get_type_display())
+
+ def __str__(self):
+ return self.name
+
+ def get_discount(self):
+ if self.type == self.FIXED:
+ discount_price = Price(net=self.value,
+ currency=settings.DEFAULT_CURRENCY)
+ return FixedDiscount(amount=discount_price, name=self.name)
+ elif self.type == self.PERCENTAGE:
+ return percentage_discount(value=self.value, name=self.name)
+ raise NotImplementedError('Unknown discount type')
+
+ def _product_has_category_discount(self, product, discounted_categories):
+ for category in product.categories.all():
+ for discounted_category in discounted_categories:
+ if category.is_descendant_of(discounted_category,
+ include_self=True):
+ return True
+ return False
+
+ def modifier_for_variant(self, variant):
+ check_price = variant.get_price_per_item()
+ discounted_products = [p.pk for p in self.products.all()]
+ discounted_categories = list(self.categories.all())
+ if discounted_products and variant.pk not in discounted_products:
+ raise NotApplicable('Discount not applicable for this product')
+ if (discounted_categories and not
+ self._product_has_category_discount(
+ variant.product, discounted_categories)):
+ raise NotApplicable('Discount too high for this product')
+ discount = self.get_discount()
+ after_discount = discount.apply(check_price)
+ if after_discount.gross <= 0:
+ raise NotApplicable('Discount too high for this product')
+ return discount
+
+
+def get_variant_discounts(variant, discounts, **kwargs):
+ for discount in discounts:
+ try:
+ yield discount.modifier_for_variant(variant, **kwargs)
+ except NotApplicable:
+ pass
diff --git a/saleor/discount/test_discounts.py b/saleor/discount/test_discounts.py
new file mode 100644
index 0000000000..1fbd15257f
--- /dev/null
+++ b/saleor/discount/test_discounts.py
@@ -0,0 +1,61 @@
+from decimal import Decimal
+from prices import FixedDiscount, FractionalDiscount
+
+import pytest
+from ..product.models import ProductVariant, Product
+from .models import Sale
+
+
+def product():
+ return Product.objects.create(
+ name='test product',
+ description='test description',
+ price=10,
+ weight=1)
+
+
+def product_variant(product):
+ return ProductVariant.objects.create(
+ product=product,
+ sku='TESTSKU',
+ name='variant')
+
+
[email protected]_db(transaction=True)
+def test_variant_discounts(product_variant):
+ product = product_variant.product
+ low_discount = Sale.objects.create(
+ type=Sale.FIXED,
+ value=5)
+ low_discount.products.add(product)
+ discount = Sale.objects.create(
+ type=Sale.FIXED,
+ value=8)
+ discount.products.add(product)
+ high_discount = Sale.objects.create(
+ type=Sale.FIXED,
+ value=50)
+ high_discount.products.add(product)
+ final_price = product_variant.get_price_per_item(
+ discounts=Sale.objects.all())
+ assert final_price.gross == 2
+ applied_discount = final_price.history.right
+ assert isinstance(applied_discount, FixedDiscount)
+ assert applied_discount.amount.gross == 8
+
+
[email protected]_db(transaction=True)
+def test_percentage_discounts(product_variant):
+ discount = Sale.objects.create(
+ type=Sale.PERCENTAGE,
+ value=50)
+ discount.products.add(product_variant.product)
+ final_price = product_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')