2016-05-28 19:25:19 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2015-02-08 15:01:34 +01:00
|
|
|
# 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/>.
|
|
|
|
|
2015-03-06 12:04:41 +01:00
|
|
|
import datetime
|
2020-04-03 20:08:44 +02:00
|
|
|
from decimal import Decimal
|
2015-03-06 12:04:41 +01:00
|
|
|
import json
|
2016-01-10 15:54:39 +01:00
|
|
|
import logging
|
2020-01-24 10:20:24 +01:00
|
|
|
import re
|
2016-01-19 11:42:20 +01:00
|
|
|
|
2018-05-25 09:40:29 +02:00
|
|
|
from dateutil import parser
|
2015-02-08 15:01:34 +01:00
|
|
|
import eopayment
|
|
|
|
from jsonfield import JSONField
|
2020-06-12 10:35:26 +02:00
|
|
|
from requests import RequestException
|
2015-02-08 15:01:34 +01:00
|
|
|
|
2015-02-08 16:39:02 +01:00
|
|
|
from django import template
|
2015-02-08 15:34:49 +01:00
|
|
|
from django.conf import settings
|
2015-02-08 11:32:29 +01:00
|
|
|
from django.db import models
|
2015-09-04 11:39:20 +02:00
|
|
|
from django.forms import models as model_forms, Select
|
2015-02-08 15:01:34 +01:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2020-01-11 18:00:46 +01:00
|
|
|
from django.utils import timezone, dateparse, six
|
2018-03-07 19:20:31 +01:00
|
|
|
from django.core.mail import EmailMultiAlternatives
|
2020-04-01 16:18:28 +02:00
|
|
|
from django.urls import reverse
|
2020-04-08 10:02:09 +02:00
|
|
|
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied, ValidationError
|
2020-06-03 11:27:09 +02:00
|
|
|
from django.utils.encoding import force_bytes, python_2_unicode_compatible
|
2018-05-14 13:47:26 +02:00
|
|
|
from django.utils.formats import localize
|
2016-01-19 11:42:20 +01:00
|
|
|
from django.utils.http import urlencode
|
2018-07-25 14:28:05 +02:00
|
|
|
from django.utils.six.moves.urllib import parse as urlparse
|
2020-04-03 20:08:44 +02:00
|
|
|
from django.utils.timezone import make_aware, utc
|
2015-02-08 15:01:34 +01:00
|
|
|
|
2017-11-14 18:48:44 +01:00
|
|
|
from django.contrib.auth.models import User
|
2018-03-07 19:20:31 +01:00
|
|
|
from django.template.loader import render_to_string
|
2017-11-14 18:48:44 +01:00
|
|
|
|
2017-05-02 17:36:46 +02:00
|
|
|
from combo.data.fields import RichTextField
|
2015-02-08 16:39:02 +01:00
|
|
|
from combo.data.models import CellBase
|
|
|
|
from combo.data.library import register_cell_class
|
2016-10-21 14:06:51 +02:00
|
|
|
from combo.utils import NothingInCacheException, aes_hex_encrypt, requests
|
2017-11-14 18:48:44 +01:00
|
|
|
from combo.apps.notifications.models import Notification
|
2015-02-08 16:39:02 +01:00
|
|
|
|
2017-11-14 18:48:44 +01:00
|
|
|
try:
|
|
|
|
from mellon.models import UserSAMLIdentifier
|
|
|
|
except ImportError:
|
|
|
|
UserSAMLIdentifier = None
|
|
|
|
|
|
|
|
|
2016-02-16 18:30:39 +01:00
|
|
|
EXPIRED = 9999
|
|
|
|
|
2015-02-08 15:01:34 +01:00
|
|
|
|
|
|
|
SERVICES = [
|
|
|
|
(eopayment.DUMMY, _('Dummy (for tests)')),
|
|
|
|
(eopayment.SYSTEMPAY, 'systempay (Banque Populaire)'),
|
2020-01-17 11:20:52 +01:00
|
|
|
(eopayment.SIPS, 'SIPS (Atos, France)'),
|
2016-02-09 11:15:43 +01:00
|
|
|
(eopayment.SIPS2, _('SIPS (Atos, other countries)')),
|
2020-01-17 15:41:58 +01:00
|
|
|
(eopayment.SPPLUS, _('SP+ (Caisse d\'epargne)')),
|
2015-03-05 17:22:59 +01:00
|
|
|
(eopayment.OGONE, _('Ingenico (formerly Ogone)')),
|
2020-01-17 11:20:52 +01:00
|
|
|
(eopayment.PAYBOX, 'Paybox'),
|
|
|
|
(eopayment.PAYZEN, 'PayZen'),
|
|
|
|
(eopayment.TIPI, 'PayFiP/TIPI Régie'),
|
|
|
|
(eopayment.PAYFIP_WS, 'PayFiP Régie Web-Service'),
|
2020-03-05 10:15:43 +01:00
|
|
|
(eopayment.KEYWARE, 'Keyware'),
|
|
|
|
(eopayment.MOLLIE, 'Mollie'),
|
2015-02-08 15:01:34 +01:00
|
|
|
]
|
|
|
|
|
2015-09-04 11:39:20 +02:00
|
|
|
def build_remote_item(data, regie):
|
|
|
|
return RemoteItem(id=data.get('id'), regie=regie,
|
|
|
|
creation_date=data['created'],
|
2015-09-30 16:09:18 +02:00
|
|
|
payment_limit_date=data['pay_limit_date'],
|
2016-10-20 10:04:59 +02:00
|
|
|
display_id=data.get('display_id'),
|
2015-09-04 11:39:20 +02:00
|
|
|
total_amount=data.get('total_amount'),
|
|
|
|
amount=data.get('amount'),
|
2020-02-25 14:05:28 +01:00
|
|
|
amount_paid=data.get('amount_paid'),
|
2015-09-03 16:03:44 +02:00
|
|
|
subject=data.get('label'),
|
2015-09-23 10:49:01 +02:00
|
|
|
has_pdf=data.get('has_pdf'),
|
2016-03-29 10:58:21 +02:00
|
|
|
online_payment=data.get('online_payment'),
|
2016-03-30 18:10:17 +02:00
|
|
|
paid=data.get('paid'),
|
|
|
|
payment_date=data.get('payment_date'),
|
2020-06-04 14:28:47 +02:00
|
|
|
no_online_payment_reason=data.get('no_online_payment_reason'),
|
|
|
|
reference_id=data.get('reference_id'))
|
2015-09-04 11:39:20 +02:00
|
|
|
|
|
|
|
|
2019-05-09 16:57:23 +02:00
|
|
|
@python_2_unicode_compatible
|
|
|
|
class PaymentBackend(models.Model):
|
|
|
|
label = models.CharField(verbose_name=_('Label'), max_length=64)
|
|
|
|
slug = models.SlugField(
|
|
|
|
unique=True, verbose_name=_('Identifier'),
|
|
|
|
help_text=_('The identifier is used in webservice calls.'))
|
|
|
|
service = models.CharField(
|
|
|
|
verbose_name=_('Payment Service'), max_length=64, choices=SERVICES)
|
2020-05-18 18:31:03 +02:00
|
|
|
service_options = JSONField(blank=True, verbose_name=_('Payment Service Options'))
|
2019-05-09 16:57:23 +02:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.label
|
|
|
|
|
2019-05-14 16:38:32 +02:00
|
|
|
def get_payment(self):
|
2020-04-08 09:59:48 +02:00
|
|
|
options = self.service_options or {}
|
|
|
|
if isinstance(options, six.string_types):
|
2020-01-11 18:00:46 +01:00
|
|
|
# backward compatibility when used againt postgresql < 9.4 and
|
|
|
|
# service_options is received as a string.
|
|
|
|
try:
|
2020-04-08 09:59:48 +02:00
|
|
|
options = json.loads(options)
|
2020-01-11 18:00:46 +01:00
|
|
|
except ValueError:
|
|
|
|
pass
|
2020-04-08 09:59:48 +02:00
|
|
|
if not isinstance(options, dict):
|
|
|
|
options = {}
|
|
|
|
return eopayment.Payment(self.service, options)
|
2019-05-14 16:38:32 +02:00
|
|
|
|
2019-05-09 16:57:23 +02:00
|
|
|
|
2020-06-12 10:35:26 +02:00
|
|
|
class RegieException(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2018-07-25 14:28:05 +02:00
|
|
|
@python_2_unicode_compatible
|
2015-02-08 15:01:34 +01:00
|
|
|
class Regie(models.Model):
|
|
|
|
label = models.CharField(verbose_name=_('Label'), max_length=64)
|
2017-04-09 17:26:08 +02:00
|
|
|
slug = models.SlugField(unique=True, verbose_name=_('Identifier'),
|
|
|
|
help_text=_('The identifier is used in webservice calls.'))
|
2015-02-08 15:01:34 +01:00
|
|
|
description = models.TextField(verbose_name=_('Description'))
|
2016-09-27 17:06:17 +02:00
|
|
|
is_default = models.BooleanField(verbose_name=_('Default Regie'), default=False)
|
2015-09-04 11:39:20 +02:00
|
|
|
webservice_url = models.URLField(_('Webservice URL to retrieve remote items'),
|
|
|
|
blank=True)
|
2017-05-28 12:47:24 +02:00
|
|
|
extra_fees_ws_url = models.URLField(_('Webservice URL to compute extra fees'),
|
|
|
|
blank=True)
|
2015-10-05 18:03:52 +02:00
|
|
|
payment_min_amount = models.DecimalField(_('Minimal payment amount'),
|
|
|
|
max_digits=7, decimal_places=2, default=0)
|
2015-09-04 11:39:20 +02:00
|
|
|
|
2016-05-27 08:41:41 +02:00
|
|
|
text_on_success = models.TextField(
|
|
|
|
verbose_name=_('Custom text displayed on success'),
|
|
|
|
blank=True, null=True)
|
2019-05-17 18:10:43 +02:00
|
|
|
payment_backend = models.ForeignKey(
|
|
|
|
PaymentBackend, on_delete=models.CASCADE, verbose_name=_('Payment backend'))
|
2019-05-14 16:38:32 +02:00
|
|
|
transaction_options = JSONField(blank=True, verbose_name=_('Transaction Options'))
|
2016-05-27 08:41:41 +02:00
|
|
|
|
2015-09-04 11:39:20 +02:00
|
|
|
def is_remote(self):
|
|
|
|
return self.webservice_url != ''
|
2015-02-08 15:01:34 +01:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
verbose_name = _('Regie')
|
2016-11-11 14:01:56 +01:00
|
|
|
ordering = ('-is_default', 'label',)
|
2015-02-08 15:01:34 +01:00
|
|
|
|
2016-03-19 19:10:58 +01:00
|
|
|
def save(self, *args, **kwargs):
|
|
|
|
if self.webservice_url and self.webservice_url.endswith('/'):
|
|
|
|
self.webservice_url = self.webservice_url.strip('/')
|
2016-09-27 17:06:17 +02:00
|
|
|
if self.is_default:
|
|
|
|
qs = self.__class__.objects.filter(is_default=True)
|
|
|
|
if self.pk:
|
|
|
|
qs = qs.exclude(pk=self.pk)
|
|
|
|
qs.update(is_default=False)
|
2020-02-11 21:26:12 +01:00
|
|
|
elif not self.__class__.objects.filter(is_default=True).exists():
|
2016-09-27 17:06:17 +02:00
|
|
|
self.is_default = True
|
2016-03-19 19:10:58 +01:00
|
|
|
super(Regie, self).save(*args, **kwargs)
|
|
|
|
|
2015-02-08 15:01:34 +01:00
|
|
|
def natural_key(self):
|
|
|
|
return (self.slug,)
|
2015-02-08 11:32:29 +01:00
|
|
|
|
2018-07-25 14:28:05 +02:00
|
|
|
def __str__(self):
|
2015-02-08 15:01:34 +01:00
|
|
|
return self.label
|
2015-02-08 15:14:58 +01:00
|
|
|
|
2016-05-27 08:41:41 +02:00
|
|
|
def get_text_on_success(self):
|
|
|
|
if self.text_on_success:
|
|
|
|
return self.text_on_success
|
|
|
|
return _('Your payment has been succesfully registered.')
|
|
|
|
|
2016-10-21 14:06:20 +02:00
|
|
|
def get_invoices(self, user, history=False):
|
2015-09-04 11:39:20 +02:00
|
|
|
if not self.is_remote():
|
2018-03-30 17:11:58 +02:00
|
|
|
return []
|
2016-10-21 14:06:20 +02:00
|
|
|
if user:
|
|
|
|
url = self.webservice_url + '/invoices/'
|
|
|
|
if history:
|
|
|
|
url += 'history/'
|
2020-06-12 10:35:26 +02:00
|
|
|
|
|
|
|
regie_exc_msg = _('Regie "%(label)s" is unavailable, please retry later.') % {
|
|
|
|
'label': self.label,
|
|
|
|
}
|
|
|
|
|
|
|
|
try:
|
|
|
|
response = requests.get(url, user=user, remote_service='auto', cache_duration=0)
|
|
|
|
response.raise_for_status()
|
|
|
|
except RequestException as e:
|
|
|
|
raise RegieException(regie_exc_msg) from e
|
|
|
|
try:
|
|
|
|
items = response.json()
|
|
|
|
except ValueError as e:
|
|
|
|
raise RegieException(regie_exc_msg) from e
|
2016-10-21 14:06:20 +02:00
|
|
|
if items.get('data'):
|
|
|
|
return [build_remote_item(item, self) for item in items.get('data')]
|
|
|
|
return []
|
2015-09-22 14:07:40 +02:00
|
|
|
return []
|
2015-09-04 11:39:20 +02:00
|
|
|
|
2017-04-11 15:52:27 +02:00
|
|
|
def get_invoice(self, user, invoice_id, log_errors=True):
|
2016-10-21 14:06:20 +02:00
|
|
|
if not self.is_remote():
|
|
|
|
return self.basketitem_set.get(pk=invoice_id)
|
|
|
|
url = self.webservice_url + '/invoice/%s/' % invoice_id
|
2017-07-28 01:50:07 +02:00
|
|
|
response = requests.get(url, user=user, remote_service='auto', cache_duration=0, log_errors=log_errors)
|
2016-10-20 10:04:59 +02:00
|
|
|
if response.status_code == 404:
|
|
|
|
raise ObjectDoesNotExist()
|
|
|
|
response.raise_for_status()
|
|
|
|
if response.json().get('data') is None:
|
|
|
|
raise ObjectDoesNotExist()
|
|
|
|
return build_remote_item(response.json().get('data'), self)
|
2016-10-21 14:06:20 +02:00
|
|
|
|
|
|
|
def get_invoice_pdf(self, user, invoice_id):
|
2015-09-03 16:03:44 +02:00
|
|
|
"""
|
|
|
|
downloads item's file
|
|
|
|
"""
|
2016-10-21 14:06:20 +02:00
|
|
|
if self.is_remote() and user:
|
|
|
|
url = self.webservice_url + '/invoice/%s/pdf/' % invoice_id
|
2017-07-28 01:50:07 +02:00
|
|
|
return requests.get(url, user=user, remote_service='auto', cache_duration=0)
|
2016-10-21 14:06:20 +02:00
|
|
|
raise PermissionDenied
|
|
|
|
|
|
|
|
def pay_invoice(self, invoice_id, transaction_id, transaction_date):
|
2020-04-03 20:08:44 +02:00
|
|
|
assert timezone.is_aware(transaction_date), 'transaction_date must be an aware date'
|
|
|
|
|
2016-10-21 14:06:20 +02:00
|
|
|
url = self.webservice_url + '/invoice/%s/pay/' % invoice_id
|
2020-04-03 20:08:44 +02:00
|
|
|
transaction_date = transaction_date.astimezone(utc)
|
|
|
|
data = {
|
|
|
|
'transaction_id': transaction_id,
|
|
|
|
'transaction_date': transaction_date.strftime('%Y-%m-%dT%H:%M:%S')
|
|
|
|
}
|
2015-12-09 16:19:44 +01:00
|
|
|
headers = {'content-type': 'application/json'}
|
2016-10-21 14:06:20 +02:00
|
|
|
return requests.post(url, remote_service='auto',
|
2015-12-09 16:19:44 +01:00
|
|
|
data=json.dumps(data), headers=headers).json()
|
2015-09-17 16:20:38 +02:00
|
|
|
|
2015-02-08 15:14:58 +01:00
|
|
|
def as_api_dict(self):
|
2016-11-11 14:02:42 +01:00
|
|
|
return {'id': self.slug,
|
|
|
|
'text': self.label,
|
2015-02-08 15:14:58 +01:00
|
|
|
'description': self.description}
|
2015-02-08 15:34:49 +01:00
|
|
|
|
2017-05-28 12:47:24 +02:00
|
|
|
def compute_extra_fees(self, user):
|
|
|
|
if not self.extra_fees_ws_url:
|
|
|
|
return
|
|
|
|
post_data = {'data': []}
|
2017-10-11 17:20:56 +02:00
|
|
|
basketitems = BasketItem.get_items_to_be_paid(user).filter(regie=self)
|
2017-05-28 12:47:24 +02:00
|
|
|
for basketitem in basketitems.filter(extra_fee=False):
|
|
|
|
basketitem_data = {
|
|
|
|
'subject': basketitem.subject,
|
|
|
|
'source_url': basketitem.source_url,
|
|
|
|
'details': basketitem.details,
|
2017-05-31 09:47:15 +02:00
|
|
|
'amount': str(basketitem.amount),
|
2017-05-28 12:47:24 +02:00
|
|
|
'request_data': basketitem.request_data
|
|
|
|
}
|
|
|
|
post_data['data'].append(basketitem_data)
|
|
|
|
if not post_data['data']:
|
|
|
|
basketitems.filter(extra_fee=True).delete()
|
|
|
|
return
|
2017-05-31 09:47:15 +02:00
|
|
|
response = requests.post(
|
|
|
|
self.extra_fees_ws_url,
|
|
|
|
remote_service='auto',
|
|
|
|
data=json.dumps(post_data),
|
|
|
|
headers={'content-type': 'application/json'})
|
2017-05-28 12:47:24 +02:00
|
|
|
if response.status_code != 200 or response.json().get('err'):
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
logger.error('failed to compute extra fees (user: %r)', user)
|
|
|
|
return
|
|
|
|
basketitems.filter(extra_fee=True).delete()
|
|
|
|
for extra_fee in response.json().get('data'):
|
|
|
|
BasketItem(user=user, regie=self,
|
|
|
|
subject=extra_fee.get('subject'),
|
|
|
|
amount=extra_fee.get('amount'),
|
|
|
|
extra_fee=True,
|
|
|
|
user_cancellable=False).save()
|
|
|
|
|
2017-11-14 18:48:44 +01:00
|
|
|
def get_remote_pending_invoices(self):
|
2017-11-14 18:48:44 +01:00
|
|
|
if not self.is_remote() or UserSAMLIdentifier is None:
|
2017-11-14 18:48:44 +01:00
|
|
|
return {}
|
|
|
|
url = self.webservice_url + '/users/with-pending-invoices/'
|
|
|
|
response = requests.get(url, remote_service='auto', cache_duration=0,
|
2018-03-22 10:48:07 +01:00
|
|
|
log_errors=False, without_user=True)
|
2017-11-14 18:48:44 +01:00
|
|
|
if not response.ok:
|
|
|
|
return {}
|
|
|
|
return response.json()['data']
|
|
|
|
|
|
|
|
def get_notification_namespace(self):
|
|
|
|
return 'invoice-%s' % self.slug
|
|
|
|
|
|
|
|
def get_notification_id(self, invoice):
|
2018-04-03 11:33:37 +02:00
|
|
|
return '%s:%s' % (self.get_notification_namespace(), invoice.id)
|
2017-11-14 18:48:44 +01:00
|
|
|
|
|
|
|
def get_notification_reminder_id(self, invoice):
|
2018-04-03 11:33:37 +02:00
|
|
|
return '%s:reminder-%s' % (self.get_notification_namespace(), invoice.id)
|
2017-11-14 18:48:44 +01:00
|
|
|
|
|
|
|
def notify_invoice(self, user, invoice):
|
2018-04-03 11:33:37 +02:00
|
|
|
today = timezone.now().date()
|
2017-11-14 18:48:44 +01:00
|
|
|
remind_delta = timezone.timedelta(days=settings.LINGO_NEW_INVOICES_REMIND_DELTA)
|
|
|
|
active_items_cell = ActiveItems.objects.first()
|
|
|
|
if active_items_cell:
|
|
|
|
items_page_url = active_items_cell.page.get_online_url()
|
|
|
|
else:
|
|
|
|
items_page_url = ''
|
|
|
|
notification_id = self.get_notification_id(invoice)
|
|
|
|
notification_reminder_id = self.get_notification_reminder_id(invoice)
|
2018-04-03 11:33:37 +02:00
|
|
|
if invoice.payment_limit_date < today:
|
2017-11-14 18:48:44 +01:00
|
|
|
# invoice is out of date
|
2018-05-14 19:33:05 +02:00
|
|
|
Notification.objects.find(user, notification_id).forget()
|
|
|
|
Notification.objects.find(user, notification_reminder_id).forget()
|
2017-11-14 18:48:44 +01:00
|
|
|
else:
|
|
|
|
# invoice can be paid
|
2018-04-03 11:33:37 +02:00
|
|
|
if invoice.payment_limit_date >= today + remind_delta:
|
|
|
|
message = _('Invoice %s to pay') % invoice.subject
|
2017-11-14 18:48:44 +01:00
|
|
|
else:
|
2018-04-03 11:33:37 +02:00
|
|
|
message = _('Reminder: invoice %s to pay') % invoice.subject
|
2017-11-14 18:48:44 +01:00
|
|
|
notification_id = notification_reminder_id
|
2018-03-07 19:20:31 +01:00
|
|
|
if not Notification.objects.find(user, notification_id).exists():
|
|
|
|
self.notify_remote_invoice_by_email(user, invoice)
|
2020-01-31 10:55:19 +01:00
|
|
|
payment_limit_date = datetime.datetime(
|
|
|
|
invoice.payment_limit_date.year,
|
|
|
|
invoice.payment_limit_date.month,
|
|
|
|
invoice.payment_limit_date.day)
|
2017-11-14 18:48:44 +01:00
|
|
|
Notification.notify(user,
|
|
|
|
summary=message,
|
|
|
|
id=notification_id,
|
|
|
|
url=items_page_url,
|
2020-01-31 10:55:19 +01:00
|
|
|
end_timestamp=make_aware(payment_limit_date))
|
2017-11-14 18:48:44 +01:00
|
|
|
return notification_id
|
|
|
|
|
|
|
|
def notify_new_remote_invoices(self):
|
2017-11-14 18:48:44 +01:00
|
|
|
if UserSAMLIdentifier is None:
|
|
|
|
# remote invoices retrieval requires SAML
|
|
|
|
return
|
2017-11-14 18:48:44 +01:00
|
|
|
pending_invoices = self.get_remote_pending_invoices()
|
|
|
|
notification_ids = []
|
2018-07-25 14:28:05 +02:00
|
|
|
for uuid, items in pending_invoices.items():
|
2017-11-14 18:48:44 +01:00
|
|
|
try:
|
2017-11-14 18:48:44 +01:00
|
|
|
user = UserSAMLIdentifier.objects.get(name_id=uuid).user
|
|
|
|
except UserSAMLIdentifier.DoesNotExist:
|
2017-11-14 18:48:44 +01:00
|
|
|
continue
|
|
|
|
for invoice in items['invoices']:
|
2018-04-03 11:33:37 +02:00
|
|
|
remote_invoice = build_remote_item(invoice, self)
|
|
|
|
if remote_invoice.total_amount >= self.payment_min_amount:
|
2017-11-14 18:48:44 +01:00
|
|
|
notification_ids.append(
|
2018-04-03 11:33:37 +02:00
|
|
|
self.notify_invoice(user, remote_invoice))
|
2017-11-14 18:48:44 +01:00
|
|
|
# clear old notifications for invoice not in the source anymore
|
|
|
|
Notification.objects.namespace(self.get_notification_namespace())\
|
|
|
|
.exclude(external_id__in=notification_ids) \
|
|
|
|
.forget()
|
|
|
|
|
2018-03-07 19:20:31 +01:00
|
|
|
def notify_remote_invoice_by_email(self, user, invoice):
|
|
|
|
|
|
|
|
subject_template = 'lingo/combo/invoice_email_notification_subject.txt'
|
|
|
|
text_body_template = 'lingo/combo/invoice_email_notification_body.txt'
|
|
|
|
html_body_template = 'lingo/combo/invoice_email_notification_body.html'
|
|
|
|
|
|
|
|
payment_url = reverse('view-item', kwargs={'regie_id': self.id,
|
2018-04-03 11:33:37 +02:00
|
|
|
'item_crypto_id': invoice.crypto_id})
|
2018-04-06 08:02:01 +02:00
|
|
|
ctx = settings.TEMPLATE_VARS.copy()
|
|
|
|
ctx['invoice'] = invoice
|
|
|
|
ctx['payment_url'] = urlparse.urljoin(settings.SITE_BASE_URL, payment_url)
|
|
|
|
ctx['portal_url'] = settings.SITE_BASE_URL
|
2018-03-07 19:20:31 +01:00
|
|
|
subject = render_to_string([subject_template], ctx).strip()
|
|
|
|
text_body = render_to_string([text_body_template], ctx)
|
|
|
|
html_body = render_to_string([html_body_template], ctx)
|
|
|
|
message = EmailMultiAlternatives(subject, text_body, to=[user.email])
|
|
|
|
message.attach_alternative(html_body, 'text/html')
|
2018-04-03 11:33:37 +02:00
|
|
|
if invoice.has_pdf:
|
|
|
|
invoice_pdf = self.get_invoice_pdf(user, invoice.id)
|
|
|
|
message.attach('%s.pdf' % invoice.id, invoice_pdf.content, 'application/pdf')
|
2018-03-07 19:20:31 +01:00
|
|
|
message.send()
|
|
|
|
|
2015-02-08 15:34:49 +01:00
|
|
|
|
|
|
|
class BasketItem(models.Model):
|
2019-10-14 13:33:00 +02:00
|
|
|
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
|
|
|
|
regie = models.ForeignKey(Regie, on_delete=models.CASCADE)
|
2016-03-09 21:51:01 +01:00
|
|
|
subject = models.CharField(verbose_name=_('Subject'), max_length=200)
|
2016-12-15 15:32:16 +01:00
|
|
|
source_url = models.URLField(_('Source URL'), blank=True)
|
2015-02-08 15:34:49 +01:00
|
|
|
details = models.TextField(verbose_name=_('Details'), blank=True)
|
|
|
|
amount = models.DecimalField(verbose_name=_('Amount'),
|
|
|
|
decimal_places=2, max_digits=8)
|
2017-05-28 12:47:24 +02:00
|
|
|
request_data = JSONField(blank=True)
|
|
|
|
extra_fee = models.BooleanField(default=False)
|
2016-05-31 15:40:31 +02:00
|
|
|
user_cancellable = models.BooleanField(default=True)
|
2015-02-08 15:34:49 +01:00
|
|
|
creation_date = models.DateTimeField(auto_now_add=True)
|
|
|
|
cancellation_date = models.DateTimeField(null=True)
|
2018-01-31 15:25:13 +01:00
|
|
|
waiting_date = models.DateTimeField(null=True)
|
2015-02-08 15:34:49 +01:00
|
|
|
payment_date = models.DateTimeField(null=True)
|
2015-03-06 12:04:41 +01:00
|
|
|
notification_date = models.DateTimeField(null=True)
|
2018-10-05 18:36:45 +02:00
|
|
|
capture_date = models.DateField(null=True)
|
2020-06-04 14:28:47 +02:00
|
|
|
email = models.EmailField(null=True)
|
|
|
|
reference_id = models.CharField(max_length=200)
|
2015-03-06 12:04:41 +01:00
|
|
|
|
2017-05-28 12:47:24 +02:00
|
|
|
class Meta:
|
|
|
|
ordering = ['regie', 'extra_fee', 'subject']
|
|
|
|
|
2017-10-11 17:20:56 +02:00
|
|
|
@classmethod
|
|
|
|
def get_items_to_be_paid(cls, user):
|
|
|
|
return cls.objects.filter(
|
|
|
|
user=user,
|
|
|
|
payment_date__isnull=True,
|
2018-01-31 15:25:13 +01:00
|
|
|
waiting_date__isnull=True,
|
2017-10-11 17:20:56 +02:00
|
|
|
cancellation_date__isnull=True)
|
|
|
|
|
2016-03-08 15:35:55 +01:00
|
|
|
def notify(self, status):
|
2017-05-28 12:47:24 +02:00
|
|
|
if not self.source_url:
|
|
|
|
return
|
2016-10-21 14:06:51 +02:00
|
|
|
url = self.source_url + 'jump/trigger/%s' % status
|
2015-03-06 12:04:41 +01:00
|
|
|
message = {'result': 'ok'}
|
2016-06-06 19:48:38 +02:00
|
|
|
if status == 'paid':
|
2017-11-15 07:42:01 +01:00
|
|
|
transaction = self.transaction_set.filter(
|
|
|
|
status__in=(eopayment.ACCEPTED, eopayment.PAID))[0]
|
2016-08-21 12:53:03 +02:00
|
|
|
message['transaction_id'] = transaction.id
|
2016-06-06 19:48:38 +02:00
|
|
|
message['order_id'] = transaction.order_id
|
2016-08-21 12:53:03 +02:00
|
|
|
message['bank_transaction_id'] = transaction.bank_transaction_id
|
2020-04-07 12:21:15 +02:00
|
|
|
bank_transaction_date = transaction.bank_transaction_date or transaction.end_date
|
|
|
|
bank_transaction_date = bank_transaction_date.astimezone(utc)
|
|
|
|
message['bank_transaction_date'] = bank_transaction_date.strftime('%Y-%m-%dT%H:%M:%S')
|
2016-06-06 19:48:38 +02:00
|
|
|
message['bank_data'] = transaction.bank_data
|
2016-06-28 14:49:38 +02:00
|
|
|
headers = {'content-type': 'application/json'}
|
2016-10-21 14:06:51 +02:00
|
|
|
r = requests.post(url, remote_service='auto',
|
2017-09-11 10:49:32 +02:00
|
|
|
data=json.dumps(message), headers=headers, timeout=15)
|
2016-03-08 15:35:55 +01:00
|
|
|
r.raise_for_status()
|
|
|
|
|
2019-12-02 10:25:03 +01:00
|
|
|
def notify_payment(self, notify_origin=True):
|
|
|
|
if notify_origin:
|
|
|
|
self.notify('paid')
|
2015-03-07 14:01:24 +01:00
|
|
|
self.notification_date = timezone.now()
|
2015-03-06 12:04:41 +01:00
|
|
|
self.save()
|
2017-05-28 12:47:24 +02:00
|
|
|
self.regie.compute_extra_fees(user=self.user)
|
2015-02-08 16:39:02 +01:00
|
|
|
|
2017-04-07 17:44:42 +02:00
|
|
|
def notify_cancellation(self, notify_origin=False):
|
|
|
|
if notify_origin:
|
2016-05-26 13:04:47 +02:00
|
|
|
self.notify('cancelled')
|
2016-03-08 15:35:55 +01:00
|
|
|
self.cancellation_date = timezone.now()
|
|
|
|
self.save()
|
2017-05-28 12:47:24 +02:00
|
|
|
self.regie.compute_extra_fees(user=self.user)
|
2016-03-08 15:35:55 +01:00
|
|
|
|
2016-10-11 10:15:19 +02:00
|
|
|
@property
|
|
|
|
def total_amount(self):
|
|
|
|
return self.amount
|
|
|
|
|
2015-02-08 16:39:02 +01:00
|
|
|
|
2015-09-04 11:39:20 +02:00
|
|
|
class RemoteItem(object):
|
2016-03-29 10:58:21 +02:00
|
|
|
payment_date = None
|
|
|
|
|
2015-09-30 16:09:18 +02:00
|
|
|
def __init__(self, id, regie, creation_date, payment_limit_date,
|
2020-02-25 14:05:28 +01:00
|
|
|
total_amount, amount, amount_paid, display_id, subject, has_pdf,
|
2020-06-04 14:28:47 +02:00
|
|
|
online_payment, paid, payment_date, no_online_payment_reason,
|
|
|
|
reference_id):
|
2015-09-04 11:39:20 +02:00
|
|
|
self.id = id
|
|
|
|
self.regie = regie
|
2018-04-03 11:33:37 +02:00
|
|
|
self.creation_date = dateparse.parse_date(creation_date)
|
|
|
|
self.payment_limit_date = dateparse.parse_date(payment_limit_date)
|
2015-09-04 10:41:57 +02:00
|
|
|
self.total_amount = Decimal(total_amount)
|
|
|
|
self.amount = Decimal(amount)
|
2020-02-25 14:05:28 +01:00
|
|
|
if amount_paid:
|
|
|
|
self.amount_paid = Decimal(amount_paid)
|
2016-10-20 10:04:59 +02:00
|
|
|
self.display_id = display_id or self.id
|
2015-09-04 11:39:20 +02:00
|
|
|
self.subject = subject
|
2015-09-03 16:03:44 +02:00
|
|
|
self.has_pdf = has_pdf
|
2015-09-23 10:49:01 +02:00
|
|
|
self.online_payment = online_payment
|
2016-03-30 18:10:17 +02:00
|
|
|
self.paid = paid
|
|
|
|
self.no_online_payment_reason = no_online_payment_reason
|
2020-06-04 14:28:47 +02:00
|
|
|
self.reference_id = reference_id
|
2016-03-29 10:58:21 +02:00
|
|
|
if payment_date:
|
|
|
|
self.payment_date = parser.parse(payment_date)
|
2015-09-04 11:39:20 +02:00
|
|
|
|
2016-03-30 18:10:17 +02:00
|
|
|
@property
|
|
|
|
def no_online_payment_reason_details(self):
|
2016-10-20 11:38:35 +02:00
|
|
|
reasons = {'litigation': _('This invoice is in litigation.'),
|
2016-10-25 14:07:33 +02:00
|
|
|
'autobilling': _('Autobilling has been set for this invoice.'),
|
|
|
|
'past-due-date': _('Due date is over.'),
|
|
|
|
}
|
2016-03-30 18:10:17 +02:00
|
|
|
return settings.LINGO_NO_ONLINE_PAYMENT_REASONS.get(self.no_online_payment_reason,
|
|
|
|
reasons.get(self.no_online_payment_reason))
|
|
|
|
|
2016-07-20 18:20:41 +02:00
|
|
|
@property
|
|
|
|
def crypto_id(self):
|
2020-06-03 11:27:09 +02:00
|
|
|
return aes_hex_encrypt(settings.SECRET_KEY, force_bytes(str(self.id)))
|
2016-07-20 18:20:41 +02:00
|
|
|
|
2015-09-04 11:39:20 +02:00
|
|
|
|
2015-03-05 17:02:52 +01:00
|
|
|
class Transaction(models.Model):
|
2019-10-14 13:33:00 +02:00
|
|
|
regie = models.ForeignKey(Regie, on_delete=models.CASCADE, null=True)
|
2015-03-05 17:02:52 +01:00
|
|
|
items = models.ManyToManyField(BasketItem, blank=True)
|
2015-09-17 16:20:38 +02:00
|
|
|
remote_items = models.CharField(max_length=512)
|
2017-01-17 21:05:23 +01:00
|
|
|
to_be_paid_remote_items = models.CharField(max_length=512, null=True)
|
2015-03-05 17:02:52 +01:00
|
|
|
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)
|
2016-06-06 19:48:38 +02:00
|
|
|
bank_transaction_id = models.CharField(max_length=200, null=True)
|
2020-04-03 19:09:57 +02:00
|
|
|
bank_transaction_date = models.DateTimeField(blank=True, null=True)
|
2019-10-14 13:33:00 +02:00
|
|
|
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
|
2015-04-21 16:40:46 +02:00
|
|
|
status = models.IntegerField(null=True)
|
2015-12-08 15:30:41 +01:00
|
|
|
amount = models.DecimalField(default=0, max_digits=7, decimal_places=2)
|
2015-04-21 16:40:46 +02:00
|
|
|
|
2015-09-17 16:20:38 +02:00
|
|
|
def is_remote(self):
|
|
|
|
return self.remote_items != ''
|
|
|
|
|
2016-12-01 11:48:38 +01:00
|
|
|
def get_user_name(self):
|
|
|
|
if self.user:
|
|
|
|
return self.user.get_full_name()
|
|
|
|
return _('Anonymous User')
|
|
|
|
|
2015-04-21 16:40:46 +02:00
|
|
|
def is_paid(self):
|
2017-11-15 07:42:01 +01:00
|
|
|
return self.status in (eopayment.PAID, eopayment.ACCEPTED)
|
2015-04-21 16:40:46 +02:00
|
|
|
|
|
|
|
def get_status_label(self):
|
|
|
|
return {
|
|
|
|
0: _('Running'),
|
|
|
|
eopayment.PAID: _('Paid'),
|
2017-11-15 07:42:01 +01:00
|
|
|
eopayment.ACCEPTED: _('Paid (accepted)'),
|
2015-04-21 16:40:46 +02:00
|
|
|
eopayment.CANCELLED: _('Cancelled'),
|
2016-02-16 18:30:39 +01:00
|
|
|
EXPIRED: _('Expired')
|
2015-04-21 16:40:46 +02:00
|
|
|
}.get(self.status) or _('Unknown')
|
2015-03-05 17:02:52 +01:00
|
|
|
|
2017-01-17 21:05:23 +01:00
|
|
|
def first_notify_remote_items_of_payments(self):
|
|
|
|
self.notify_remote_items_of_payments(self.remote_items)
|
|
|
|
|
|
|
|
def retry_notify_remote_items_of_payments(self):
|
|
|
|
self.notify_remote_items_of_payments(self.to_be_paid_remote_items)
|
|
|
|
|
|
|
|
def notify_remote_items_of_payments(self, items):
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
if not items:
|
|
|
|
return
|
2017-10-11 16:59:09 +02:00
|
|
|
if not self.is_paid():
|
|
|
|
return
|
2017-01-17 21:05:23 +01:00
|
|
|
|
|
|
|
regie = self.regie
|
|
|
|
to_be_paid_remote_items = []
|
|
|
|
for item_id in items.split(','):
|
|
|
|
try:
|
|
|
|
remote_item = regie.get_invoice(user=self.user, invoice_id=item_id)
|
2020-04-03 20:09:01 +02:00
|
|
|
regie.pay_invoice(item_id, self.order_id, self.bank_transaction_date or self.end_date)
|
2017-01-17 21:05:23 +01:00
|
|
|
except Exception:
|
|
|
|
to_be_paid_remote_items.append(item_id)
|
|
|
|
logger.exception(u'unable to notify payment for remote item %s from transaction %s',
|
|
|
|
item_id, self)
|
|
|
|
else:
|
|
|
|
logger.info(u'notified payment for remote item %s from transaction %s',
|
|
|
|
item_id, self)
|
|
|
|
subject = _('Invoice #%s') % remote_item.display_id
|
|
|
|
local_item = BasketItem.objects.create(user=self.user,
|
|
|
|
regie=regie,
|
|
|
|
source_url='',
|
|
|
|
subject=subject,
|
|
|
|
amount=remote_item.amount,
|
|
|
|
payment_date=self.end_date)
|
|
|
|
self.items.add(local_item)
|
|
|
|
|
|
|
|
self.to_be_paid_remote_items = ','.join(to_be_paid_remote_items) or None
|
|
|
|
self.save(update_fields=['to_be_paid_remote_items'])
|
|
|
|
|
2016-08-21 12:53:03 +02:00
|
|
|
|
|
|
|
class TransactionOperation(models.Model):
|
|
|
|
OPERATIONS = [
|
|
|
|
('validation', _('Validation')),
|
|
|
|
('cancellation', _('Cancellation')),
|
|
|
|
]
|
2019-10-14 13:33:00 +02:00
|
|
|
transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE)
|
2016-08-21 12:53:03 +02:00
|
|
|
kind = models.CharField(max_length=65, choices=OPERATIONS)
|
|
|
|
amount = models.DecimalField(decimal_places=2, max_digits=8)
|
|
|
|
creation_date = models.DateTimeField(auto_now_add=True)
|
|
|
|
bank_result = JSONField(blank=True)
|
|
|
|
|
|
|
|
|
2015-02-08 16:39:02 +01:00
|
|
|
@register_cell_class
|
|
|
|
class LingoBasketCell(CellBase):
|
2017-03-16 08:29:52 +01:00
|
|
|
user_dependant = True
|
2015-02-08 16:39:02 +01:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
verbose_name = _('Basket')
|
|
|
|
|
2016-03-08 15:35:55 +01:00
|
|
|
class Media:
|
|
|
|
js = ('xstatic/jquery-ui.min.js', 'js/gadjo.js',)
|
|
|
|
|
2015-03-09 16:03:24 +01:00
|
|
|
@classmethod
|
|
|
|
def is_enabled(cls):
|
2020-02-11 21:26:12 +01:00
|
|
|
return Regie.objects.exists()
|
2015-03-09 16:03:24 +01:00
|
|
|
|
2015-02-16 17:11:54 +01:00
|
|
|
def is_relevant(self, context):
|
2019-10-14 13:43:08 +02:00
|
|
|
if not (getattr(context['request'], 'user', None) and context['request'].user.is_authenticated):
|
2015-05-11 16:24:40 +02:00
|
|
|
return False
|
2020-02-11 21:26:12 +01:00
|
|
|
return BasketItem.get_items_to_be_paid(context['request'].user).exists()
|
2015-02-16 17:11:54 +01:00
|
|
|
|
2016-05-28 19:25:19 +02:00
|
|
|
def get_badge(self, context):
|
2019-10-14 13:43:08 +02:00
|
|
|
if not (getattr(context['request'], 'user', None) and context['request'].user.is_authenticated):
|
2016-05-28 19:25:19 +02:00
|
|
|
return
|
2017-10-11 17:20:56 +02:00
|
|
|
items = BasketItem.get_items_to_be_paid(context['request'].user)
|
2016-05-28 19:25:19 +02:00
|
|
|
if not items:
|
|
|
|
return
|
|
|
|
total = sum([x.amount for x in items])
|
2018-05-14 13:47:26 +02:00
|
|
|
if total == int(total):
|
|
|
|
total = int(total)
|
|
|
|
return {'badge': _(u'%s€') % localize(total)}
|
2016-05-28 19:25:19 +02:00
|
|
|
|
2015-02-08 16:39:02 +01:00
|
|
|
def render(self, context):
|
|
|
|
basket_template = template.loader.get_template('lingo/combo/basket.html')
|
2017-10-11 17:20:56 +02:00
|
|
|
items = BasketItem.get_items_to_be_paid(context['request'].user)
|
2016-05-31 15:59:31 +02:00
|
|
|
regies = {}
|
|
|
|
for item in items:
|
|
|
|
if not item.regie_id in regies:
|
|
|
|
regies[item.regie_id] = {'items': [], 'regie': item.regie}
|
|
|
|
regies[item.regie_id]['items'].append(item)
|
|
|
|
|
|
|
|
for items in regies.values():
|
|
|
|
items['total'] = sum([x.amount for x in items['items']])
|
|
|
|
|
2018-07-25 14:28:05 +02:00
|
|
|
context['regies'] = sorted(regies.values(), key=lambda x: x['regie'].label)
|
2015-02-08 16:39:02 +01:00
|
|
|
return basket_template.render(context)
|
2015-03-07 14:02:13 +01:00
|
|
|
|
|
|
|
|
|
|
|
@register_cell_class
|
|
|
|
class LingoRecentTransactionsCell(CellBase):
|
2017-03-16 08:29:52 +01:00
|
|
|
user_dependant = True
|
2015-03-07 14:02:13 +01:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
verbose_name = _('Recent Transactions')
|
|
|
|
|
2015-03-09 16:03:24 +01:00
|
|
|
@classmethod
|
|
|
|
def is_enabled(cls):
|
2020-02-11 21:26:12 +01:00
|
|
|
return Regie.objects.exists()
|
2015-03-09 16:03:24 +01:00
|
|
|
|
2015-03-07 14:02:13 +01:00
|
|
|
def is_relevant(self, context):
|
2019-10-14 13:43:08 +02:00
|
|
|
if not (getattr(context['request'], 'user', None) and context['request'].user.is_authenticated):
|
2015-05-11 16:24:40 +02:00
|
|
|
return False
|
2020-02-11 21:26:12 +01:00
|
|
|
return (
|
|
|
|
Transaction.objects.filter(
|
2015-03-07 14:02:13 +01:00
|
|
|
user=context['request'].user,
|
|
|
|
start_date__gte=timezone.now()-datetime.timedelta(days=7))
|
2020-02-11 21:26:12 +01:00
|
|
|
.exists())
|
2015-03-07 14:02:13 +01:00
|
|
|
|
|
|
|
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)
|
2015-05-12 16:39:03 +02:00
|
|
|
|
|
|
|
|
|
|
|
@register_cell_class
|
|
|
|
class LingoBasketLinkCell(CellBase):
|
|
|
|
user_dependant = True
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
verbose_name = _('Basket Link')
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def is_enabled(cls):
|
2020-02-11 21:26:12 +01:00
|
|
|
return Regie.objects.exists()
|
2015-05-12 16:39:03 +02:00
|
|
|
|
|
|
|
def is_relevant(self, context):
|
2019-10-14 13:43:08 +02:00
|
|
|
if not (getattr(context['request'], 'user', None) and context['request'].user.is_authenticated):
|
2015-05-12 16:39:03 +02:00
|
|
|
return False
|
2020-02-11 21:26:12 +01:00
|
|
|
return BasketItem.get_items_to_be_paid(context['request'].user).exists()
|
2015-05-12 16:39:03 +02:00
|
|
|
|
|
|
|
def render(self, context):
|
2019-10-14 13:43:08 +02:00
|
|
|
if not (getattr(context['request'], 'user', None) and context['request'].user.is_authenticated):
|
2015-11-19 15:59:07 +01:00
|
|
|
return ''
|
2016-03-09 15:21:23 +01:00
|
|
|
try:
|
|
|
|
context['basket_url'] = LingoBasketCell.objects.all()[0].page.get_online_url()
|
|
|
|
except IndexError:
|
|
|
|
return ''
|
2015-05-12 16:39:03 +02:00
|
|
|
basket_template = template.loader.get_template('lingo/combo/basket_link.html')
|
2017-10-11 17:20:56 +02:00
|
|
|
context['items'] = BasketItem.get_items_to_be_paid(user=context['request'].user)
|
2015-05-12 16:39:03 +02:00
|
|
|
context['total'] = sum([x.amount for x in context['items']])
|
|
|
|
return basket_template.render(context)
|
2015-09-04 11:39:20 +02:00
|
|
|
|
|
|
|
|
2016-04-06 20:09:20 +02:00
|
|
|
class Items(CellBase):
|
|
|
|
regie = models.CharField(_('Regie'), max_length=50, blank=True)
|
|
|
|
title = models.CharField(_('Title'), max_length=200, blank=True)
|
|
|
|
text = RichTextField(_('Text'), blank=True, null=True)
|
|
|
|
|
|
|
|
user_dependant = True
|
|
|
|
template_name = 'lingo/combo/items.html'
|
2018-02-22 14:25:56 +01:00
|
|
|
loading_message = _('Loading invoices...')
|
2016-04-06 20:09:20 +02:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
abstract = True
|
|
|
|
|
|
|
|
class Media:
|
|
|
|
js = ('xstatic/jquery-ui.min.js', 'js/gadjo.js',)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def is_enabled(cls):
|
2020-02-11 21:26:12 +01:00
|
|
|
return Regie.objects.exclude(webservice_url='').exists()
|
2016-04-06 20:09:20 +02:00
|
|
|
|
2016-05-29 08:43:23 +02:00
|
|
|
def is_relevant(self, context):
|
2019-10-14 13:43:08 +02:00
|
|
|
return (getattr(context['request'], 'user', None) and context['request'].user.is_authenticated)
|
2016-05-29 08:43:23 +02:00
|
|
|
|
2016-04-06 20:09:20 +02:00
|
|
|
def get_default_form_class(self):
|
|
|
|
fields = ['title', 'text']
|
2020-03-31 15:48:28 +02:00
|
|
|
if hasattr(self, 'hide_if_empty'):
|
|
|
|
fields.append('hide_if_empty')
|
2016-04-06 20:09:20 +02:00
|
|
|
widgets = {}
|
2020-02-11 21:26:12 +01:00
|
|
|
regie_qs = Regie.objects.exclude(webservice_url='')
|
|
|
|
if len(regie_qs) > 1:
|
2016-04-06 20:09:20 +02:00
|
|
|
regies = [('', _('All'))]
|
2020-02-11 21:26:12 +01:00
|
|
|
regies.extend([(r.slug, r.label) for r in regie_qs])
|
2016-04-06 20:09:20 +02:00
|
|
|
widgets['regie'] = Select(choices=regies)
|
|
|
|
fields.insert(0, 'regie')
|
|
|
|
return model_forms.modelform_factory(self.__class__, fields=fields, widgets=widgets)
|
|
|
|
|
|
|
|
def get_regies(self):
|
|
|
|
if self.regie:
|
|
|
|
return [Regie.objects.get(slug=self.regie)]
|
|
|
|
return Regie.objects.all()
|
|
|
|
|
2016-10-20 10:04:59 +02:00
|
|
|
def get_invoices(self, user):
|
2020-06-12 10:35:26 +02:00
|
|
|
return [], []
|
2016-10-20 10:04:59 +02:00
|
|
|
|
2016-04-06 20:09:20 +02:00
|
|
|
def get_cell_extra_context(self, context):
|
2016-10-20 10:04:59 +02:00
|
|
|
ctx = super(Items, self).get_cell_extra_context(context)
|
2017-10-14 22:08:21 +02:00
|
|
|
if context.get('placeholder_search_mode'):
|
|
|
|
# don't call webservices when we're just looking for placeholders
|
|
|
|
return ctx
|
2016-10-20 10:04:59 +02:00
|
|
|
ctx.update({'title': self.title, 'text': self.text})
|
2020-06-12 10:35:26 +02:00
|
|
|
items, errors = self.get_invoices(user=context['user'])
|
2019-10-25 09:49:57 +02:00
|
|
|
none_date = datetime.datetime(1900, 1, 1) # to avoid None-None comparison errors
|
|
|
|
items.sort(key=lambda i: i.creation_date or none_date, reverse=True)
|
2020-02-25 14:47:20 +01:00
|
|
|
ctx.update({
|
|
|
|
'items': items,
|
2020-06-12 10:35:26 +02:00
|
|
|
'errors': errors,
|
2020-02-25 14:47:20 +01:00
|
|
|
'with_payment_limit_date': any(i.payment_limit_date for i in items),
|
2020-03-03 10:25:03 +01:00
|
|
|
'with_amount_paid': any(getattr(i, 'amount_paid', None) for i in items),
|
2020-02-25 14:47:20 +01:00
|
|
|
})
|
2016-04-06 20:09:20 +02:00
|
|
|
return ctx
|
|
|
|
|
|
|
|
def render(self, context):
|
|
|
|
self.context = context
|
|
|
|
if not context.get('synchronous'):
|
|
|
|
raise NothingInCacheException()
|
|
|
|
return super(Items, self).render(context)
|
|
|
|
|
|
|
|
|
|
|
|
@register_cell_class
|
|
|
|
class ItemsHistory(Items):
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
verbose_name = _('Items History Cell')
|
|
|
|
|
2016-10-21 14:06:20 +02:00
|
|
|
def get_invoices(self, user):
|
2016-04-06 20:09:20 +02:00
|
|
|
items = []
|
2020-06-12 10:35:26 +02:00
|
|
|
errors = []
|
2016-04-06 20:09:20 +02:00
|
|
|
for r in self.get_regies():
|
2020-06-12 10:35:26 +02:00
|
|
|
try:
|
|
|
|
items.extend(r.get_invoices(user, history=True))
|
|
|
|
except RegieException as e:
|
|
|
|
errors.append(e)
|
|
|
|
return items, errors
|
2016-04-06 20:09:20 +02:00
|
|
|
|
|
|
|
|
|
|
|
@register_cell_class
|
|
|
|
class ActiveItems(Items):
|
2020-03-31 15:48:28 +02:00
|
|
|
hide_if_empty = models.BooleanField(_('Hide if no items'), default=False)
|
2016-04-06 20:09:20 +02:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
verbose_name = _('Active Items Cell')
|
|
|
|
|
2016-10-21 14:06:20 +02:00
|
|
|
def get_invoices(self, user):
|
2016-04-06 20:09:20 +02:00
|
|
|
items = []
|
2020-06-12 10:35:26 +02:00
|
|
|
errors = []
|
2016-04-06 20:09:20 +02:00
|
|
|
for r in self.get_regies():
|
2020-06-12 10:35:26 +02:00
|
|
|
try:
|
|
|
|
items.extend(r.get_invoices(user))
|
|
|
|
except RegieException as e:
|
|
|
|
errors.append(e)
|
|
|
|
return items, errors
|
2016-10-20 10:04:59 +02:00
|
|
|
|
|
|
|
|
|
|
|
@register_cell_class
|
|
|
|
class SelfDeclaredInvoicePayment(Items):
|
|
|
|
user_dependant = False
|
|
|
|
template_name = 'lingo/combo/self-declared-invoice-payment.html'
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
verbose_name = _('Self declared invoice payment')
|
|
|
|
|
|
|
|
def is_relevant(self, context):
|
|
|
|
return self.is_enabled()
|
|
|
|
|
|
|
|
def render(self, context):
|
|
|
|
context['synchronous'] = True
|
|
|
|
context['page_path'] = context['request'].path
|
2017-03-17 08:20:03 +01:00
|
|
|
return super(SelfDeclaredInvoicePayment, self).render(context)
|
2017-02-28 11:59:36 +01:00
|
|
|
|
|
|
|
|
|
|
|
TIPI_CONTROL_PROCOTOLS = (
|
|
|
|
('pesv2', _('Indigo/PES v2')),
|
|
|
|
('rolmre', _('ROLMRE')),
|
|
|
|
)
|
|
|
|
|
2019-07-23 12:06:12 +02:00
|
|
|
|
2017-02-28 11:59:36 +01:00
|
|
|
@register_cell_class
|
|
|
|
class TipiPaymentFormCell(CellBase):
|
|
|
|
title = models.CharField(_('Title'), max_length=150, blank=True)
|
|
|
|
url = models.URLField(_('TIPI payment service URL'), default='https://www.tipi.budget.gouv.fr/tpa/paiement.web')
|
2020-01-24 10:20:24 +01:00
|
|
|
regies = models.CharField(
|
|
|
|
_('Regies'),
|
|
|
|
help_text=_('Values separated by commas. It is possible to add a label after a regie identifier. '
|
|
|
|
'Example: "1234 - Regie A,5678 - Regie B"'),
|
|
|
|
max_length=256)
|
2019-07-23 12:06:12 +02:00
|
|
|
control_protocol = models.CharField(_('Control protocol'), max_length=8, choices=TIPI_CONTROL_PROCOTOLS,
|
|
|
|
default='pesv2')
|
2018-11-25 20:09:25 +01:00
|
|
|
exer = models.CharField('Exer', max_length=4, blank=True, help_text=_('Default value to be used in form'))
|
|
|
|
idpce = models.CharField('IDPCE', max_length=8, blank=True, help_text=_('Default value to be used in form'))
|
|
|
|
idligne = models.CharField('IDLIGNE', max_length=6, blank=True, help_text=_('Default value to be used in form'))
|
|
|
|
rolrec = models.CharField('ROLREC', max_length=2, blank=True, help_text=_('Default value to be used in form'))
|
|
|
|
roldeb = models.CharField('ROLDEB', max_length=2, blank=True, help_text=_('Default value to be used in form'))
|
|
|
|
roldet = models.CharField('ROLDET', max_length=13, blank=True, help_text=_('Default value to be used in form'))
|
2017-02-28 11:59:36 +01:00
|
|
|
test_mode = models.BooleanField(_('Test mode'), default=False)
|
|
|
|
template_name = 'lingo/tipi_form.html'
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
verbose_name = _('TIPI Payment Form')
|
|
|
|
|
|
|
|
class Media:
|
|
|
|
js = ('js/tipi.js',)
|
|
|
|
|
|
|
|
def get_cell_extra_context(self, context):
|
|
|
|
extra_context = super(TipiPaymentFormCell, self).get_cell_extra_context(context)
|
2018-11-25 20:09:25 +01:00
|
|
|
form_fields = self.get_default_form_class().base_fields
|
2019-07-23 12:05:25 +02:00
|
|
|
field_definitions = (
|
|
|
|
{
|
|
|
|
'protocol': 'any',
|
|
|
|
'fields': ['exer']
|
|
|
|
},
|
|
|
|
{
|
|
|
|
'protocol': 'pesv2',
|
|
|
|
'fields': ['idpce', 'idligne']
|
|
|
|
},
|
|
|
|
{
|
|
|
|
'protocol': 'rolmre',
|
|
|
|
'fields': ['rolrec', 'roldeb', 'roldet']
|
|
|
|
},
|
2018-11-25 20:09:25 +01:00
|
|
|
)
|
|
|
|
reference_fields = []
|
|
|
|
for definition in field_definitions:
|
|
|
|
for field in definition['fields']:
|
|
|
|
field_pattern = '[0-9]+'
|
|
|
|
# special pattern for rolrec
|
|
|
|
if field == 'rolrec':
|
|
|
|
field_pattern = '[A-Z0-9]+'
|
2019-07-23 12:06:12 +02:00
|
|
|
reference_fields.append({
|
|
|
|
'name': field,
|
|
|
|
'length': form_fields[field].max_length,
|
|
|
|
'placeholder': '0' * form_fields[field].max_length,
|
|
|
|
'pattern': field_pattern,
|
|
|
|
'protocol': definition['protocol']
|
|
|
|
})
|
2017-02-28 11:59:36 +01:00
|
|
|
context['title'] = self.title
|
|
|
|
context['url'] = self.url
|
|
|
|
context['mode'] = 'T' if self.test_mode else 'M'
|
2018-11-25 20:09:25 +01:00
|
|
|
context['control_protocol'] = self.control_protocol
|
2017-02-28 11:59:36 +01:00
|
|
|
context['regies'] = []
|
2019-06-18 14:49:14 +02:00
|
|
|
context['pesv2'] = self.control_protocol == 'pesv2'
|
2018-11-25 20:09:25 +01:00
|
|
|
for field in reference_fields:
|
|
|
|
if getattr(self, field['name']):
|
|
|
|
field['default'] = getattr(self, field['name'])
|
|
|
|
context['reference_fields'] = reference_fields
|
2017-02-28 11:59:36 +01:00
|
|
|
for regie in self.regies.split(','):
|
2020-01-24 10:20:24 +01:00
|
|
|
regie = regie.strip()
|
|
|
|
id_search = re.search(r'(\d+)', regie)
|
|
|
|
if not id_search:
|
2017-02-28 11:59:36 +01:00
|
|
|
continue
|
2020-01-24 10:20:24 +01:00
|
|
|
regie_id = id_search.group(1)
|
|
|
|
context['regies'].append((regie_id, regie))
|
2017-02-28 11:59:36 +01:00
|
|
|
return extra_context
|