Add basics of eboutic, still need to implement the ET API to get bank payment

This commit is contained in:
Skia 2016-07-22 01:19:50 +02:00
parent 525d7e6709
commit f04cf9d4d4
13 changed files with 436 additions and 0 deletions

View File

@ -129,6 +129,12 @@ tbody>tr:hover {
background: yellow;
width: 100%;
}
#basket {
width: 40%;
background: lightgrey;
float: right;
padding: 10px;
}
/*-----------------------------USER PROFILE----------------------------*/
.user_profile {

0
eboutic/__init__.py Normal file
View File

6
eboutic/admin.py Normal file
View File

@ -0,0 +1,6 @@
from django.contrib import admin
from eboutic.models import *
admin.site.register(Basket)
admin.site.register(Invoice)

View File

@ -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',),
),
]

View File

@ -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'),
),
]

View File

68
eboutic/models.py Normal file
View File

@ -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'))

View File

@ -0,0 +1,49 @@
{% extends "core/base.jinja" %}
{% macro add_product(id, content) %}
<form method="post" action="{{ url('eboutic:main') }}" class="inline" style="display:inline">
{% csrf_token %}
<input type="hidden" name="action" value="add_product">
<button type="submit" name="product_id" value="{{ id }}"> {{ content }} </button>
</form>
{% endmacro %}
{% macro del_product(id, content) %}
<form method="post" action="{{ url('eboutic:main') }}" class="inline" style="display:inline">
{% csrf_token %}
<input type="hidden" name="action" value="del_product">
<button type="submit" name="product_id" value="{{ id }}"> {{ content }} </button>
</form>
{% endmacro %}
{% block content %}
<h3>{% trans %}Eboutic{% endtrans %}</h3>
<div id="basket">
<p>{% trans %}Basket: {% endtrans %}</p>
<ul>
{% for id,infos in request.session['basket']|dictsort %}
{% set product = eboutic.products.filter(id=id).first() %}
{% set s = infos['qty'] * infos['price'] / 100 %}
<li>{{ del_product(id, '-') }} {{ infos['qty'] }} {{ add_product(id, '+') }} {{ product.name }}: {{ "%0.2f"|format(s) }} €</li>
{% endfor %}
</ul>
<p><strong>{% trans %}Total: {% endtrans %}{{ "%0.2f"|format(basket_total) }} €</strong></p>
<form method="post" action="{{ url('eboutic:command') }}">
{% csrf_token %}
<input type="hidden" name="action" value="ask_payment">
<input type="submit" value="{% trans %}Proceed to command{% endtrans %}" />
</form>
</div>
<div>
<p><strong>{% trans %}Products: {% endtrans %}</strong>
{% for p in eboutic.products.all() %}
{{ add_product(p.id, p.name) }}
{% endfor %}
</p>
</div>
{% endblock %}

View File

@ -0,0 +1,42 @@
{% extends "core/base.jinja" %}
{% block content %}
<h3>{% trans %}Eboutic{% endtrans %}</h3>
<div>
<p>{% trans %}Basket: {% endtrans %}</p>
<table>
<thead>
<tr>
<td>Article</td>
<td>Quantity</td>
<td>Unit price</td>
</tr>
</thead>
<tbody>
{% for item in basket.items.all() %}
<tr>
<td>{{ item.product_name }}</td>
<td>{{ item.quantity }}</td>
<td>{{ item.product_unit_price }} €</td>
</tr>
{% endfor %}
<tbody>
</table>
<form method="post" action="{{ url('eboutic:command') }}">
{% csrf_token %}
<input type="hidden" name="action" value="pay_with_credit_card">
<input type="submit" value="{% trans %}Pay with credit card{% endtrans %}" />
</form>
<form method="post" action="{{ url('eboutic:pay_with_sith') }}">
{% csrf_token %}
<input type="hidden" name="action" value="pay_with_sith_account">
<input type="submit" value="{% trans %}Pay with Sith account{% endtrans %}" />
</form>
</div>
{% endblock %}

View File

@ -0,0 +1,19 @@
{% extends "core/base.jinja" %}
{% block content %}
<h3>{% trans %}Eboutic{% endtrans %}</h3>
<div>
{% if not_enough %}
{% trans %}Payment failed{% endtrans %}
{% else %}
{% trans %}Payment successful{% endtrans %}
{% endif %}
</div>
{% endblock %}

3
eboutic/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

14
eboutic/urls.py Normal file
View File

@ -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'),
]

136
eboutic/views.py Normal file
View File

@ -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()