This repository has been archived on 2023-02-21. You can view files and clone it, but cannot push or open issues or pull requests.
lingo-obsolete/lingo/models.py

163 lines
5.7 KiB
Python

# lingo - basket and payment system
# Copyright (C) 2015 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import datetime
import json
import requests
import eopayment
from jsonfield import JSONField
from django import template
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from combo.data.models import CellBase
from combo.data.library import register_cell_class
from combo.utils import sign_url
SERVICES = [
(eopayment.DUMMY, _('Dummy (for tests)')),
(eopayment.SYSTEMPAY, 'systempay (Banque Populaire)'),
(eopayment.SIPS, 'SIPS'),
(eopayment.SPPLUS, _('SP+ (Caisse d\'epargne)')),
(eopayment.OGONE, _('Ingenico (formerly Ogone)')),
]
class Regie(models.Model):
label = models.CharField(verbose_name=_('Label'), max_length=64)
slug = models.SlugField(unique=True)
description = models.TextField(verbose_name=_('Description'))
service = models.CharField(verbose_name=_('Payment Service'),
max_length=64, choices=SERVICES)
service_options = JSONField(blank=True,
verbose_name=_('Payment Service Options'))
class Meta:
verbose_name = _('Regie')
def natural_key(self):
return (self.slug,)
def __unicode__(self):
return self.label
def as_api_dict(self):
return {'slug': self.slug,
'label': self.label,
'description': self.description}
class BasketItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
regie = models.ForeignKey(Regie)
subject = models.CharField(verbose_name=_('Subject'), max_length=64)
source_url = models.URLField(_('Source URL'))
details = models.TextField(verbose_name=_('Details'), blank=True)
amount = models.DecimalField(verbose_name=_('Amount'),
decimal_places=2, max_digits=8)
creation_date = models.DateTimeField(auto_now_add=True)
cancellation_date = models.DateTimeField(null=True)
payment_date = models.DateTimeField(null=True)
notification_date = models.DateTimeField(null=True)
def notify(self):
# TODO: sign with real values
url = self.source_url + 'jump/trigger/paid?email=trigger@localhost&orig=combo'
url = sign_url(url, key='xxx')
message = {'result': 'ok'}
r = requests.post(url, data=json.dumps(message), timeout=3)
self.notification_date = timezone.now()
self.save()
class Transaction(models.Model):
items = models.ManyToManyField(BasketItem, blank=True)
start_date = models.DateTimeField(auto_now_add=True)
end_date = models.DateTimeField(null=True)
bank_data = JSONField(blank=True)
order_id = models.CharField(max_length=200)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
status = models.IntegerField(null=True)
def is_paid(self):
return self.status == eopayment.PAID
def get_status_label(self):
return {
0: _('Running'),
eopayment.PAID: _('Paid'),
eopayment.CANCELLED: _('Cancelled'),
}.get(self.status) or _('Unknown')
@register_cell_class
class LingoBasketCell(CellBase):
class Meta:
verbose_name = _('Basket')
@classmethod
def is_enabled(cls):
return Regie.objects.count() > 0
def is_relevant(self, context):
if not (getattr(context['request'], 'user', None) and context['request'].user.is_authenticated()):
return False
items = BasketItem.objects.filter(
user=context['request'].user, payment_date__isnull=True
).exclude(cancellation_date__isnull=False)
return len(items) > 0
def render(self, context):
basket_template = template.loader.get_template('lingo/combo/basket.html')
context['items'] = BasketItem.objects.filter(
user=context['request'].user, payment_date__isnull=True
).exclude(cancellation_date__isnull=False)
context['total'] = sum([x.amount for x in context['items']])
return basket_template.render(context)
@register_cell_class
class LingoRecentTransactionsCell(CellBase):
class Meta:
verbose_name = _('Recent Transactions')
@classmethod
def is_enabled(cls):
return Regie.objects.count() > 0
def is_relevant(self, context):
if not (getattr(context['request'], 'user', None) and context['request'].user.is_authenticated()):
return False
transactions = Transaction.objects.filter(
user=context['request'].user,
start_date__gte=timezone.now()-datetime.timedelta(days=7))
return len(transactions) > 0
def render(self, context):
recent_transactions_template = template.loader.get_template(
'lingo/combo/recent_transactions.html')
context['transactions'] = Transaction.objects.filter(
user=context['request'].user,
start_date__gte=timezone.now()-datetime.timedelta(days=7)
).order_by('-start_date')
return recent_transactions_template.render(context)