Skip to content

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

Add Cart and CartItem models and admin

Michal Ociepkab070d8c7be54
diff --git a/cart/admin.py b/cart/admin.py
new file mode 100644
index 0000000000..68e0494659
--- /dev/null
+++ b/cart/admin.py
@@ -0,0 +1,12 @@
+from django.contrib import admin
+from .models import Cart, CartItem
+
+class CartInlineAdmin(admin.TabularInline):
+
+ model = CartItem
+
+class CartAdmin(admin.ModelAdmin):
+
+ inlines = [CartInlineAdmin]
+
+admin.site.register(Cart, CartAdmin)
diff --git a/cart/migrations/0001_initial.py b/cart/migrations/0001_initial.py
new file mode 100644
index 0000000000..905eb46e41
--- /dev/null
+++ b/cart/migrations/0001_initial.py
@@ -0,0 +1,116 @@
+# -*- coding: utf-8 -*-
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+
+class Migration(SchemaMigration):
+
+ def forwards(self, orm):
+ # Adding model 'Cart'
+ db.create_table(u'cart_cart', (
+ (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+ ('owner', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='+', null=True, to=orm['auth.User'])),
+ ('token', self.gf('django.db.models.fields.CharField')(default='', max_length=36, blank=True)),
+ ))
+ db.send_create_signal(u'cart', ['Cart'])
+
+ # Adding model 'CartItem'
+ db.create_table(u'cart_cartitem', (
+ (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+ ('cart', self.gf('django.db.models.fields.related.ForeignKey')(related_name='items', to=orm['cart.Cart'])),
+ ('product', self.gf('django.db.models.fields.related.ForeignKey')(related_name='+', to=orm['product.Product'])),
+ ('quantity', self.gf('django.db.models.fields.DecimalField')(default='1', max_digits=10, decimal_places=4)),
+ ))
+ db.send_create_signal(u'cart', ['CartItem'])
+
+ # Adding unique constraint on 'CartItem', fields ['cart', 'product']
+ db.create_unique(u'cart_cartitem', ['cart_id', 'product_id'])
+
+
+ def backwards(self, orm):
+ # Removing unique constraint on 'CartItem', fields ['cart', 'product']
+ db.delete_unique(u'cart_cartitem', ['cart_id', 'product_id'])
+
+ # Deleting model 'Cart'
+ db.delete_table(u'cart_cart')
+
+ # Deleting model 'CartItem'
+ db.delete_table(u'cart_cartitem')
+
+
+ models = {
+ u'auth.group': {
+ 'Meta': {'object_name': 'Group'},
+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+ 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+ },
+ u'auth.permission': {
+ 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
+ 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+ },
+ u'auth.user': {
+ 'Meta': {'object_name': 'User'},
+ 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+ 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+ 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+ 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+ 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+ 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+ 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+ 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+ 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+ 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+ 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
+ },
+ u'cart.cart': {
+ 'Meta': {'object_name': 'Cart'},
+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'+'", 'null': 'True', 'to': u"orm['auth.User']"}),
+ 'token': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '36', 'blank': 'True'})
+ },
+ u'cart.cartitem': {
+ 'Meta': {'unique_together': "(('cart', 'product'),)", 'object_name': 'CartItem'},
+ 'cart': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'items'", 'to': u"orm['cart.Cart']"}),
+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': u"orm['product.Product']"}),
+ 'quantity': ('django.db.models.fields.DecimalField', [], {'default': "'1'", 'max_digits': '10', 'decimal_places': '4'})
+ },
+ u'contenttypes.contenttype': {
+ 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+ 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+ },
+ u'product.category': {
+ 'Meta': {'object_name': 'Category'},
+ 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+ 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+ 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': u"orm['product.Category']"}),
+ 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+ 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}),
+ 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
+ },
+ u'product.product': {
+ 'Meta': {'object_name': 'Product'},
+ 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['product.Category']"}),
+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+ 'price': ('django_prices.models.PriceField', [], {'currency': "'USD'", 'max_digits': '12', 'decimal_places': '4'}),
+ 'stock': ('django.db.models.fields.DecimalField', [], {'default': "'1'", 'max_digits': '10', 'decimal_places': '4'}),
+ 'subtype_attr': ('django.db.models.fields.CharField', [], {'max_length': '500'})
+ }
+ }
+
+ complete_apps = ['cart']
\ No newline at end of file
diff --git a/cart/migrations/__init__.py b/cart/migrations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/cart/models.py b/cart/models.py
index 71a8362390..2e61d6cfbe 100755
--- a/cart/models.py
+++ b/cart/models.py
@@ -1,3 +1,119 @@
+# coding: utf-8
+from product.models import Product
+from decimal import Decimal
+from django.contrib.auth.models import User
from django.db import models
+from django.utils.translation import pgettext as _p, ugettext as _
+from satchless.item import ItemSet, ItemLine
+from django.conf import settings
+from uuid import uuid4
+from satchless.cart import InvalidQuantityException
-# Create your models here.
+
+class Cart(models.Model, ItemSet):
+
+ owner = models.ForeignKey(User, null=True, blank=True, related_name='+',
+ verbose_name=_p('Cart field','owner'))
+ token = models.CharField(_p('Cart field','token'), max_length=36,
+ blank=True, default='')
+
+ def __iter__(self):
+ for i in self.get_all_items():
+ yield i
+
+ def save(self, *args, **kwargs):
+ if not self.token:
+ for i in xrange(100):
+ token = str(uuid4())
+ if not type(self).objects.filter(token=token).exists():
+ self.token = token
+ break
+ return super(Cart, self).save(*args, **kwargs)
+
+ def check_quantity(self, product, quantity, replace=False):
+ '''
+ Method checks quantity. Return valid quantity or raise
+ InvalidQuantityException.
+ '''
+ if not replace:
+ try:
+ cart_item = self.get_item(product=product)
+ except CartItem.DoesNotExist:
+ pass
+ else:
+ quantity += cart_item.quantity
+
+ if quantity < 0:
+ quantity = Decimal(0)
+
+ if quantity > product.stock:
+ raise InvalidQuantityException(_(u'To many'),
+ product.stock - quantity)
+
+ return quantity
+
+ def add_item(self, product, quantity, replace=False):
+ try:
+ quantity = self.check_quantity(product, quantity, replace=replace)
+ except InvalidQuantityException:
+ quantity = product.stock
+
+ cart_item = self.get_item(product=product)
+
+ if not quantity and cart_item:
+ cart_item.delete()
+ elif quantity and cart_item:
+ cart_item.quantity = quantity
+ cart_item.save(update_fields=['quantity'])
+ elif quantity and not cart_item:
+ cart_item = self.items.create(product=product, quantity=quantity)
+
+ return cart_item
+
+ def replace_item(self, product, quantity):
+ return self.add_item(product, quantity, replace=True)
+
+ def get_default_currency(self, **kwargs):
+ return settings.SATCHLESS_DEFAULT_CURRENCY
+
+ def get_item(self, product, create_instance=False):
+ return self.items.get(product=product)
+
+ def get_all_items(self):
+ return list(self.items.all())
+
+ def get_quantity(self, product):
+ try:
+ return self.get_item(product=product).quantity
+ except CartItem.ObjectDoesNotExist:
+ return Decimal('0')
+
+ def is_empty(self):
+ return not self.items.exists()
+
+
+class CartItem(models.Model, ItemLine):
+
+ cart = models.ForeignKey(Cart, related_name='items', editable=False,
+ verbose_name=_p('Cart item field','cart'))
+ product = models.ForeignKey(Product, related_name='+', editable=False,
+ verbose_name=_p('Cart item field','product'))
+ quantity = models.DecimalField(_p('Cart item field','quantity'),
+ max_digits=10, decimal_places=4,
+ default=Decimal(1))
+
+ class Meta:
+ unique_together = ('cart', 'product')
+
+ def __unicode__(self):
+ return u'%s × %.10g' % (self.product, self.quantity)
+
+ def get_price_per_item(self, **kwargs):
+ return self.product.get_price(**kwargs)
+
+ def get_quantity(self, **kwargs):
+ return self.quantity
+
+ def save(self, *args, **kwargs):
+ assert self.quantity > 0
+ return super(CartItem, self).save(*args, **kwargs)