Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Simpler discounts with proper logic flow
Patryk Zawadzkidfe5822e8db8
diff --git a/discount/__init__.py b/discount/__init__.pydeleted file mode 100755index 4f582d12a3..0000000000--- a/discount/__init__.py+++ /dev/null@@ -1,57 +0,0 @@-from prices import PriceModifier---class Discount(PriceModifier):-- def can_apply(self, item, **kwargs):- raise NotImplementedError()-- def apply_to_item(self, item, **kwargs):- raise NotImplementedError()---class ItemDiscount(Discount):-- item = None-- def can_apply(self, item, **kwargs):- return hasattr(item, 'get_price')-- def apply_to_item(self, item, **kwargs):- self.item = item- # We have to add set_price method to Item Class- item.price += self---class ItemSetDiscount(Discount):-- item_set = None-- def can_apply(self, item, **kwargs):- return hasattr(item, 'get_total')-- def apply_to_item(self, item_set, **kwargs):- self.item = item_set- for item in item_set:- # We definitely have to add set_price method to Item Class- item.product.price += self---class DiscountManager(list):-- def apply(self, item, **kwargs):- for discount in self.filter(item, **kwargs):- discount.apply_to_item(item)-- def filter(self, item, **kwargs):- return [discount for discount in self- if discount.can_apply(item, **kwargs)]---def get_discounts(request):- if hasattr(request, 'discounts'):- return request.discounts- from .models import SelectedProduct- selected_products = SelectedProduct.objects.all()- request.discounts = DiscountManager(selected_products)- return request.discountsdiff --git a/discount/admin.py b/discount/admin.pydeleted file mode 100644index 1606584681..0000000000--- a/discount/admin.py+++ /dev/null@@ -1,5 +0,0 @@-from .models import SelectedProduct-from django.contrib import admin---admin.site.register(SelectedProduct)diff --git a/discount/migrations/__init__.py b/discount/migrations/__init__.pydeleted file mode 100644index e69de29bb2..0000000000diff --git a/discount/models.py b/discount/models.pydeleted file mode 100755index ca963f5827..0000000000--- a/discount/models.py+++ /dev/null@@ -1,40 +0,0 @@-from . import ItemDiscount-from django.conf import settings-from django.db import models-from django.utils.translation import pgettext_lazy-from django_prices.models import PriceField-from prices import Price-from product.models import Product, Category-import operator---class SelectedProduct(models.Model, ItemDiscount):-- name = models.CharField(max_length=255)- products = models.ManyToManyField(Product, blank=True)- categories = models.ManyToManyField(Category, blank=True)- discount = PriceField(pgettext_lazy(u'Discount field', u'discount value'),- currency=settings.SATCHLESS_DEFAULT_CURRENCY,- max_digits=12, decimal_places=4)-- def apply(self, price):- return Price(price.gross - self.discount.gross,- currency=price.currency,- previous=price,- modifier=self,- operation=operator.__sub__)-- def can_apply(self, item, **kwargs):- if not super(SelectedProduct, self).can_apply(item, **kwargs):- return False- if (self.products.filter(pk=item.pk).exists() or- self.categories.filter(products=self).exists()):- return True- return False-- def __unicode__(self):- return self.name-- def __repr__(self):- return 'SelectedProducts(name=%r, discount=%r)' % (str(self.discount),- self.name)diff --git a/discount/tests.py b/discount/tests.pydeleted file mode 100755index b14681b5d2..0000000000--- a/discount/tests.py+++ /dev/null@@ -1,76 +0,0 @@-from . import ItemDiscount, DiscountManager, ItemSetDiscount-from cart import Cart-from decimal import Decimal-from django.test import TestCase-from mock import MagicMock, patch-from prices import Price, inspect_price-from product.models import Product-import operator---class ProductDiscount(ItemDiscount):-- value = Decimal(5)- name = 'Product discount'-- def apply(self, price):- return Price(price.gross - self.value,- currency=price.currency,- previous=price,- modifier=self,- operation=operator.__sub__)-- def __repr__(self):- return 'ProductDiscount(%r, name=%r)' % (str(self.value), self.name)---class CartDiscount(ItemSetDiscount):-- precent = Decimal('0.5')- name = 'Cart discount'-- def apply(self, price):- return Price(price.gross - (price.gross * self.precent),- currency=price.currency,- previous=price,- modifier=self,- operation=operator.__sub__)-- def __repr__(self):- return 'CartDiscount(%r%%, name=%r)' % (int(self.precent * 100),- self.name)---class TestDiscountManager(TestCase):-- def setUp(self):- self.product = Product(name='test', price=Price(10, currency='USD'),- sku='1', category_id=1)- self.cart = Cart()- self.cart.add(self.product, 2)-- def test_discount_manager_with_one_item_discaunt(self):- discount = ProductDiscount()- discounts = DiscountManager([discount])- discounts.apply(self.product)- self.assertEqual(self.product.price, Price(5, currency='USD'))-- def test_discount_manager_with_many_item_discaunts(self):- discount = ProductDiscount()- discounts = DiscountManager([discount])- discounts.append(discount)- discounts.apply(self.product)- self.assertEqual(self.product.price, Price(0, currency='USD'))-- def test_discount_manager_with_one_item_set_discaunt(self):- discount = CartDiscount()- discounts = DiscountManager([discount])- discounts.apply(self.cart)- self.assertEqual(self.cart[0].product.price, Price(5, currency='USD'))-- def test_discount_manager_with_different_discaunts(self):- discount_cart = CartDiscount()- discount_product = ProductDiscount()- discounts = DiscountManager([discount_cart, discount_product])- discounts.apply(self.cart)- self.assertEqual(self.cart[0].product.price, Price(5, currency='USD'))diff --git a/discount/views.py b/discount/views.pydeleted file mode 100755index 60f00ef0ef..0000000000--- a/discount/views.py+++ /dev/null@@ -1 +0,0 @@-# Create your views here.diff --git a/product/admin.py b/product/admin.pyindex 8ba97141a2..ff0797d1d0 100644--- a/product/admin.py+++ b/product/admin.py@@ -1,7 +1,8 @@from django.contrib import admin-from .models import DigitalShip, Ship, Category+from . import modelsfrom mptt.admin import MPTTModelAdmin-admin.site.register(DigitalShip)-admin.site.register(Ship)-admin.site.register(Category, MPTTModelAdmin)+admin.site.register(models.DigitalShip)+admin.site.register(models.Ship)+admin.site.register(models.Category, MPTTModelAdmin)+admin.site.register(models.FixedProductDiscount)diff --git a/discount/migrations/0001_initial.py b/product/migrations/0008_auto__add_fixedproductdiscount.pysimilarity index 57%rename from discount/migrations/0001_initial.pyrename to product/migrations/0008_auto__add_fixedproductdiscount.pyindex 6bc97b0b20..17e28f1298 100644--- a/discount/migrations/0001_initial.py+++ b/product/migrations/0008_auto__add_fixedproductdiscount.py@@ -8,53 +8,32 @@ from django.db import modelsclass Migration(SchemaMigration):def forwards(self, orm):- # Adding model 'SelectedProduct'- db.create_table(u'discount_selectedproduct', (+ # Adding model 'FixedProductDiscount'+ db.create_table(u'product_fixedproductdiscount', ((u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),('name', self.gf('django.db.models.fields.CharField')(max_length=255)),('discount', self.gf('django_prices.models.PriceField')(currency='USD', max_digits=12, decimal_places=4)),))- db.send_create_signal(u'discount', ['SelectedProduct'])+ db.send_create_signal(u'product', ['FixedProductDiscount'])- # Adding M2M table for field products on 'SelectedProduct'- m2m_table_name = db.shorten_name(u'discount_selectedproduct_products')- db.create_table(m2m_table_name, (+ # Adding M2M table for field products on 'FixedProductDiscount'+ db.create_table(u'product_fixedproductdiscount_products', (('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),- ('selectedproduct', models.ForeignKey(orm[u'discount.selectedproduct'], null=False)),+ ('fixedproductdiscount', models.ForeignKey(orm[u'product.fixedproductdiscount'], null=False)),('product', models.ForeignKey(orm[u'product.product'], null=False))))- db.create_unique(m2m_table_name, ['selectedproduct_id', 'product_id'])-- # Adding M2M table for field categories on 'SelectedProduct'- m2m_table_name = db.shorten_name(u'discount_selectedproduct_categories')- db.create_table(m2m_table_name, (- ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),- ('selectedproduct', models.ForeignKey(orm[u'discount.selectedproduct'], null=False)),- ('category', models.ForeignKey(orm[u'product.category'], null=False))- ))- db.create_unique(m2m_table_name, ['selectedproduct_id', 'category_id'])+ db.create_unique(u'product_fixedproductdiscount_products', ['fixedproductdiscount_id', 'product_id'])def backwards(self, orm):- # Deleting model 'SelectedProduct'- db.delete_table(u'discount_selectedproduct')-- # Removing M2M table for field products on 'SelectedProduct'- db.delete_table(db.shorten_name(u'discount_selectedproduct_products'))+ # Deleting model 'FixedProductDiscount'+ db.delete_table(u'product_fixedproductdiscount')- # Removing M2M table for field categories on 'SelectedProduct'- db.delete_table(db.shorten_name(u'discount_selectedproduct_categories'))+ # Removing M2M table for field products on 'FixedProductDiscount'+ db.delete_table('product_fixedproductdiscount_products')models = {- u'discount.selectedproduct': {- 'Meta': {'object_name': 'SelectedProduct'},- 'categories': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['product.Category']", 'symmetrical': 'False', 'blank': 'True'}),- 'discount': ('django_prices.models.PriceField', [], {'currency': "'USD'", 'max_digits': '12', 'decimal_places': '4'}),- u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),- 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),- 'products': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['product.Product']", 'symmetrical': 'False', 'blank': 'True'})- },u'product.category': {'Meta': {'object_name': 'Category'},'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),@@ -67,6 +46,18 @@ class Migration(SchemaMigration):'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}),'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})},+ u'product.digitalship': {+ 'Meta': {'object_name': 'DigitalShip', '_ormbases': [u'product.Product']},+ u'product_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['product.Product']", 'unique': 'True', 'primary_key': 'True'}),+ 'url': ('django.db.models.fields.URLField', [], {'max_length': '200'})+ },+ u'product.fixedproductdiscount': {+ 'Meta': {'object_name': 'FixedProductDiscount'},+ 'discount': ('django_prices.models.PriceField', [], {'currency': "'USD'", 'max_digits': '12', 'decimal_places': '4'}),+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),+ 'products': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['product.Product']", 'symmetrical': 'False', 'blank': 'True'})+ },u'product.product': {'Meta': {'object_name': 'Product'},'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'products'", 'to': u"orm['product.Category']"}),@@ -74,7 +65,16 @@ class Migration(SchemaMigration):'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),'price': ('django_prices.models.PriceField', [], {'currency': "'USD'", 'max_digits': '12', 'decimal_places': '4'}),'sku': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'})+ },+ u'product.ship': {+ 'Meta': {'object_name': 'Ship', '_ormbases': [u'product.Product']},+ 'depth': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'blank': 'True'}),+ 'length': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'blank': 'True'}),+ u'product_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['product.Product']", 'unique': 'True', 'primary_key': 'True'}),+ 'stock': ('django.db.models.fields.DecimalField', [], {'default': "'1'", 'max_digits': '10', 'decimal_places': '4'}),+ 'weight': ('django.db.models.fields.PositiveIntegerField', [], {}),+ 'width': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'blank': 'True'})}}- complete_apps = ['discount']\ No newline at end of file+ complete_apps = ['product']\ No newline at end of filediff --git a/product/models.py b/product/models.pyindex 43abe0723f..88d70811e0 100644--- a/product/models.py+++ b/product/models.py@@ -1,4 +1,6 @@from decimal import Decimal+import re+from django.conf import settingsfrom django.core.urlresolvers import reversefrom django.db import models@@ -8,9 +10,12 @@ from django.utils.safestring import mark_safefrom django.utils.translation import pgettext_lazyfrom django_prices.models import PriceFieldfrom mptt.models import MPTTModel+from prices import FixedDiscountfrom satchless.item import Itemfrom unidecode import unidecode-import re+++class NotApplicable(ValueError): passclass SubtypedQuerySet(QuerySet):@@ -125,8 +130,12 @@ class Product(Subtyped, Item):(),{'slug': self.get_slug(), 'product_id': self.id})- def get_price_per_item(self, **kwargs):- return self.price+ def get_price_per_item(self, discounted=True, **kwargs):+ price = self.price+ if discounted:+ for modifier in get_product_discounts(self, **kwargs):+ price += modifier+ return pricedef get_slug(self):value = unidecode(self.name)@@ -135,6 +144,43 @@ class Product(Subtyped, Item):return mark_safe(re.sub(r'[-\s]+', '-', value))+class ProductDiscountManager(models.Manager):++ def for_product(self, product):+ # Add a caching layer here to reduce the number of queries+ return self.get_queryset().filter(products=product)+++class FixedProductDiscount(models.Model):++ name = models.CharField(max_length=255)+ products = models.ManyToManyField(Product, blank=True)+ discount = PriceField(pgettext_lazy(u'Discount field', u'discount value'),+ currency=settings.SATCHLESS_DEFAULT_CURRENCY,+ max_digits=12, decimal_places=4)++ objects = ProductDiscountManager()++ def modifier_for_product(self, product, **kwargs):+ if not self.products.filter(pk=product.pk).exists():+ raise NotApplicable('Discount not applicable for this product')+ return FixedDiscount(self.discount, name=self.name)++ def __unicode__(self):+ return self.name++ def __repr__(self):+ return 'SelectedProduct(name=%r, discount=%r)' % (str(self.discount),+ self.name)++def get_product_discounts(product, **kwargs):+ for discount in FixedProductDiscount.objects.for_product(product):+ try:+ yield discount.modifier_for_product(product, **kwargs)+ except NotApplicable:+ pass++class StockedProduct(models.Model):stock = models.DecimalField(pgettext_lazy(u'Product item field', u'stock'),diff --git a/product/views.py b/product/views.pyindex 09096f9700..51cf72d5ae 100644--- a/product/views.py+++ b/product/views.py@@ -1,10 +1,10 @@-from .forms import ProductForm-from .models import Product, Category-from discount import get_discountsfrom django.http import HttpResponsePermanentRedirectfrom django.shortcuts import get_object_or_404from django.template.response import TemplateResponse+from .forms import ProductForm+from .models import Product, Category+def product_details(request, slug, product_id):product = get_object_or_404(Product, id=product_id)@@ -14,8 +14,6 @@ def product_details(request, slug, product_id):data=request.POST or None)if form.is_valid():form.save()- discounts = get_discounts(request)- discounts.apply(product)return TemplateResponse(request, 'product/details.html', {'product': product,'form': formdiff --git a/saleor/settings.py b/saleor/settings.pyindex 370d16f5b9..c6a1fb2054 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -105,7 +105,6 @@ INSTALLED_APPS = ['userprofile','registration','payment',- 'discount',]LOGGING = {diff --git a/setup.py b/setup.pyindex d32bd35b49..3e0f28a0cc 100755--- a/setup.py+++ b/setup.py@@ -29,12 +29,13 @@ setup(install_requires=['Django>=1.5','django-mptt>=0.5',+ 'django-payments>=0.3,<0.4a0','django-prices>=0.2,<0.3a0',+ 'prices>=0.4.2,<0.5a0','satchless>=1.0,<1.1a0','South>=0.7.6',- 'unidecode','requests>=1.2.0',- 'django-payments>=0.3,<0.4a0'],+ 'unidecode'],extras_require={'lint': ['pylint==0.26.0', 'django-lint==dev']},dependency_links=[