diff --git a/core/static/core/style.css b/core/static/core/style.css index 26394f67..2842c840 100644 --- a/core/static/core/style.css +++ b/core/static/core/style.css @@ -129,6 +129,12 @@ tbody>tr:hover { background: yellow; width: 100%; } +#basket { + width: 40%; + background: lightgrey; + float: right; + padding: 10px; +} /*-----------------------------USER PROFILE----------------------------*/ .user_profile { diff --git a/eboutic/__init__.py b/eboutic/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/eboutic/admin.py b/eboutic/admin.py new file mode 100644 index 00000000..1e56ae1c --- /dev/null +++ b/eboutic/admin.py @@ -0,0 +1,6 @@ +from django.contrib import admin + +from eboutic.models import * + +admin.site.register(Basket) +admin.site.register(Invoice) diff --git a/eboutic/migrations/0001_initial.py b/eboutic/migrations/0001_initial.py new file mode 100644 index 00000000..8aa7d844 --- /dev/null +++ b/eboutic/migrations/0001_initial.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models +from django.conf import settings +import accounting.models + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('counter', '0009_auto_20160721_1902'), + ] + + operations = [ + migrations.CreateModel( + name='Basket', + fields=[ + ('id', models.AutoField(auto_created=True, serialize=False, primary_key=True, verbose_name='ID')), + ('date', models.DateTimeField(auto_now=True, verbose_name='date')), + ('user', models.ForeignKey(verbose_name='user', related_name='baskets', to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.CreateModel( + name='BasketItem', + fields=[ + ('id', models.AutoField(auto_created=True, serialize=False, primary_key=True, verbose_name='ID')), + ('product_name', models.CharField(max_length=255, verbose_name='product name')), + ('product_unit_price', accounting.models.CurrencyField(max_digits=12, decimal_places=2, verbose_name='unit price')), + ('quantity', models.IntegerField(verbose_name='quantity')), + ('basket', models.ForeignKey(verbose_name='basket', related_name='items', to='eboutic.Basket')), + ], + options={ + 'abstract': False, + }, + ), + migrations.CreateModel( + name='Invoice', + fields=[ + ('id', models.AutoField(auto_created=True, serialize=False, primary_key=True, verbose_name='ID')), + ('date', models.DateTimeField(auto_now=True, verbose_name='date')), + ('payment_method', models.CharField(max_length=20, choices=[('CREDIT_CARD', 'Credit card'), ('SITH_ACCOUNT', 'Sith account')], verbose_name='payment method')), + ('products', models.ManyToManyField(related_name='invoices', to='counter.Product', blank=True, verbose_name='products')), + ('user', models.ForeignKey(verbose_name='user', related_name='invoices', to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.CreateModel( + name='InvoiceItem', + fields=[ + ('id', models.AutoField(auto_created=True, serialize=False, primary_key=True, verbose_name='ID')), + ('product_name', models.CharField(max_length=255, verbose_name='product name')), + ('product_unit_price', accounting.models.CurrencyField(max_digits=12, decimal_places=2, verbose_name='unit price')), + ('quantity', models.IntegerField(verbose_name='quantity')), + ('invoice', models.ForeignKey(verbose_name='invoice', related_name='items', to='eboutic.Invoice')), + ], + options={ + 'abstract': False, + }, + ), + migrations.CreateModel( + name='Eboutic', + fields=[ + ], + options={ + 'proxy': True, + }, + bases=('counter.counter',), + ), + ] diff --git a/eboutic/migrations/0002_auto_20160722_0100.py b/eboutic/migrations/0002_auto_20160722_0100.py new file mode 100644 index 00000000..31503bac --- /dev/null +++ b/eboutic/migrations/0002_auto_20160722_0100.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('eboutic', '0001_initial'), + ] + + operations = [ + migrations.RemoveField( + model_name='invoice', + name='products', + ), + migrations.AddField( + model_name='invoice', + name='validated', + field=models.BooleanField(default=False, verbose_name='validated'), + ), + ] diff --git a/eboutic/migrations/__init__.py b/eboutic/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/eboutic/models.py b/eboutic/models.py new file mode 100644 index 00000000..27a81bc6 --- /dev/null +++ b/eboutic/models.py @@ -0,0 +1,68 @@ +from django.db import models, DataError +from django.utils.translation import ugettext_lazy as _ + +from accounting.models import CurrencyField +from counter.models import Counter, Product +from core.models import User + +class Eboutic(Counter): + class Meta: + proxy = True + +class Basket(models.Model): + """ + Basket is built when the user validate its session basket and asks for payment + """ + user = models.ForeignKey(User, related_name='baskets', verbose_name=_('user'), blank=False) + date = models.DateTimeField(_('date'), auto_now=True) + + def get_total(self): + total = 0 + for i in self.items.all(): + total += i.quantity * i.product_unit_price + return total + +class Invoice(models.Model): + """ + Invoices are generated once the payment has been validated + """ + user = models.ForeignKey(User, related_name='invoices', verbose_name=_('user'), blank=False) + date = models.DateTimeField(_('date'), auto_now=True) + payment_method = models.CharField(choices=[('CREDIT_CARD', _('Credit card')), ('SITH_ACCOUNT', _('Sith account'))], + max_length=20, verbose_name=_('payment method')) + validated = models.BooleanField(_("validated"), default=False) + + + def get_total(self): + total = 0 + for i in self.items.all(): + total += i.quantity * i.product_unit_price + return total + + def validate(self, *args, **kwargs): + if self.validated: + raise DataError(_("Invoice already validated")) + if self.payment_method == "SITH_ACCOUNT": + self.user.customer.amount -= self.get_total() + self.user.customer.save() + self.validated = True + self.save() + + + +class AbstractBaseItem(models.Model): + product_name = models.CharField(_('product name'), max_length=255) + product_unit_price = CurrencyField(_('unit price')) + quantity = models.IntegerField(_('quantity')) + + class Meta: + abstract = True + + def __str__(self): + return "Item: %s (%s) x%d" % (self.product_name, self.product_unit_price, self.quantity) + +class BasketItem(AbstractBaseItem): + basket = models.ForeignKey(Basket, related_name='items', verbose_name=_('basket')) + +class InvoiceItem(AbstractBaseItem): + invoice = models.ForeignKey(Invoice, related_name='items', verbose_name=_('invoice')) diff --git a/eboutic/templates/eboutic/eboutic_main.jinja b/eboutic/templates/eboutic/eboutic_main.jinja new file mode 100644 index 00000000..ba1a767a --- /dev/null +++ b/eboutic/templates/eboutic/eboutic_main.jinja @@ -0,0 +1,49 @@ +{% extends "core/base.jinja" %} + +{% macro add_product(id, content) %} +
+ {% csrf_token %} + + +
+{% endmacro %} + +{% macro del_product(id, content) %} +
+ {% csrf_token %} + + +
+{% endmacro %} + +{% block content %} +

{% trans %}Eboutic{% endtrans %}

+ +
+

{% trans %}Basket: {% endtrans %}

+ +

{% trans %}Total: {% endtrans %}{{ "%0.2f"|format(basket_total) }} €

+
+ {% csrf_token %} + + +
+
+
+

{% trans %}Products: {% endtrans %} + {% for p in eboutic.products.all() %} + {{ add_product(p.id, p.name) }} + {% endfor %} +

+
+ +{% endblock %} + + + diff --git a/eboutic/templates/eboutic/eboutic_makecommand.jinja b/eboutic/templates/eboutic/eboutic_makecommand.jinja new file mode 100644 index 00000000..003c7642 --- /dev/null +++ b/eboutic/templates/eboutic/eboutic_makecommand.jinja @@ -0,0 +1,42 @@ +{% extends "core/base.jinja" %} + +{% block content %} +

{% trans %}Eboutic{% endtrans %}

+ +
+

{% trans %}Basket: {% endtrans %}

+ + + + + + + + + + {% for item in basket.items.all() %} + + + + + + {% endfor %} + +
ArticleQuantityUnit price
{{ item.product_name }}{{ item.quantity }}{{ item.product_unit_price }} €
+
+ {% csrf_token %} + + +
+
+ {% csrf_token %} + + +
+
+ +{% endblock %} + + + + diff --git a/eboutic/templates/eboutic/eboutic_payment_result.jinja b/eboutic/templates/eboutic/eboutic_payment_result.jinja new file mode 100644 index 00000000..f55849f0 --- /dev/null +++ b/eboutic/templates/eboutic/eboutic_payment_result.jinja @@ -0,0 +1,19 @@ +{% extends "core/base.jinja" %} + +{% block content %} +

{% trans %}Eboutic{% endtrans %}

+ +
+ {% if not_enough %} + {% trans %}Payment failed{% endtrans %} + {% else %} + {% trans %}Payment successful{% endtrans %} + {% endif %} +
+ +{% endblock %} + + + + + diff --git a/eboutic/tests.py b/eboutic/tests.py new file mode 100644 index 00000000..7ce503c2 --- /dev/null +++ b/eboutic/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/eboutic/urls.py b/eboutic/urls.py new file mode 100644 index 00000000..56ff8975 --- /dev/null +++ b/eboutic/urls.py @@ -0,0 +1,14 @@ +from django.conf.urls import url, include + +from eboutic.views import * + +urlpatterns = [ + # Subscription views + url(r'^$', EbouticMain.as_view(), name='main'), + url(r'^command$', EbouticCommand.as_view(), name='command'), + url(r'^pay$', EbouticPayWithSith.as_view(), name='pay_with_sith'), + url(r'^et_autoanswer$', EtransactionAutoAnswer.as_view(), name='etransation_autoanswer'), +] + + + diff --git a/eboutic/views.py b/eboutic/views.py new file mode 100644 index 00000000..19040999 --- /dev/null +++ b/eboutic/views.py @@ -0,0 +1,136 @@ +from django.shortcuts import render + +from django.core.urlresolvers import reverse_lazy +from eboutic.models import Eboutic +from django.views.generic import TemplateView, View +from django.http import HttpResponse, HttpResponseRedirect +from django.shortcuts import render +from django.db import transaction, DataError +from django.utils.translation import ugettext as _ + +from counter.models import Product, Customer +from eboutic.models import Basket, Invoice, Eboutic, BasketItem, InvoiceItem + +# Create your views here. +class EbouticMain(TemplateView): + template_name = 'eboutic/eboutic_main.jinja' + + def sum_basket(request): + total = 0 + for pid,infos in request.session['basket'].items(): + total += infos['price'] * infos['qty'] + return total / 100 + + def get(self, request, *args, **kwargs): + if 'basket' not in request.session.keys(): # Init the basket session entry + request.session['basket'] = {} + request.session['basket_total'] = 0 + return super(EbouticMain, self).get(request, *args, **kwargs) + + def post(self, request, *args, **kwargs): + if 'basket' not in request.session.keys(): # Init the basket session entry + request.session['basket'] = {} + request.session['basket_total'] = 0 + if 'add_product' in request.POST['action']: + self.add_product(request) + elif 'del_product' in request.POST['action']: + self.del_product(request) + elif 'pay' in request.POST['action']: + self.ask_payment(request) + return self.render_to_response(self.get_context_data(**kwargs)) + + def get_price(self, pid): + return Product.objects.filter(pk=pid).first().selling_price + + def add_product(self, request, q = 1, p=None): + """ Add a product to the basket """ + pid = p or request.POST['product_id'] + pid = str(pid) + price = self.get_price(pid) + total = EbouticMain.sum_basket(request) + if pid in request.session['basket']: + request.session['basket'][pid]['qty'] += q + else: + request.session['basket'][pid] = {'qty': q, 'price': int(price*100)} + request.session.modified = True + return True + + def del_product(self, request): + """ Delete a product from the basket """ + pid = str(request.POST['product_id']) + if pid in request.session['basket']: + request.session['basket'][pid]['qty'] -= 1 + if request.session['basket'][pid]['qty'] <= 0: + del request.session['basket'][pid] + else: + request.session['basket'][pid] = 0 + request.session.modified = True + + def get_context_data(self, **kwargs): + kwargs = super(EbouticMain, self).get_context_data(**kwargs) + kwargs['basket_total'] = EbouticMain.sum_basket(self.request) + kwargs['eboutic'] = Eboutic.objects.filter(type="EBOUTIC").first() + return kwargs + +class EbouticCommand(TemplateView): + template_name = 'eboutic/eboutic_makecommand.jinja' + + def post(self, request, *args, **kwargs): + if 'basket' not in request.session.keys(): + return HttpResponseRedirect(reverse_lazy('eboutic:main', args=self.args, kwargs=kwargs)) + if 'ask_payment' in request.POST['action']: + if self.ask_payment(request): + kwargs['basket'] = self.basket + return self.render_to_response(self.get_context_data(**kwargs)) + + def ask_payment(self, request): + b = None + if 'basket_id' in request.session.keys(): + b = Basket.objects.filter(id=request.session['basket_id']).first() + if b is None: + b = Basket() + b.user = request.user + b.save() + request.session['basket_id'] = b.id + request.session.modified = True + b.items.all().delete() + for pid,infos in request.session['basket'].items(): + BasketItem(basket=b, product_name=Product.objects.filter(id=int(pid)).first().name, + quantity=infos['qty'], product_unit_price=infos['price']/100).save() + self.basket = b + return True + +class EbouticPayWithSith(TemplateView): + template_name = 'eboutic/eboutic_payment_result.jinja' + + def post(self, request, *args, **kwargs): + try: + with transaction.atomic(): + if 'basket_id' not in request.session.keys() or not request.user.is_authenticated(): + return HttpResponseRedirect(reverse_lazy('eboutic:main', args=self.args, kwargs=kwargs)) + b = Basket.objects.filter(id=request.session['basket_id']).first() + c = Customer.objects.filter(user__id=request.user.id).first() + if b is None or c is None: + return HttpResponseRedirect(reverse_lazy('eboutic:main', args=self.args, kwargs=kwargs)) + kwargs['not_enough'] = True + if c.amount < b.get_total(): + raise DataError(_("You have not enough money to buy the basket")) + else: + i = Invoice() + i.user = b.user + i.payment_method = "SITH_ACCOUNT" + i.save() + for it in b.items.all(): + InvoiceItem(invoice=i, product_name=it.product_name, + product_unit_price=it.product_unit_price, quantity=it.quantity).save() + i.validate() + kwargs['not_enough'] = False + request.session.pop('basket_id', None) + request.session.pop('basket', None) + except DataError as e: + kwargs['not_enough'] = True + return self.render_to_response(self.get_context_data(**kwargs)) + +class EtransactionAutoAnswer(View): + def get(self, request, *args, **kwargs): # TODO implement CA's API + return HttpResponse()