Projet

Général

Profil

0001-lingo-send-new-remote-invoices-by-email-13122.patch

Serghei Mihai (congés, retour 15/05), 15 novembre 2017 16:23

Télécharger (10,4 ko)

Voir les différences:

Subject: [PATCH] lingo: send new remote invoices by email (#13122)

 .../lingo/migrations/0031_auto_20171115_1059.py    | 35 +++++++++++
 combo/apps/lingo/models.py                         | 70 +++++++++++++++++++++-
 .../combo/invoice_email_notification_body.html     | 20 +++++++
 .../combo/invoice_email_notification_body.txt      | 12 ++++
 .../combo/invoice_email_notification_subject.txt   |  4 ++
 5 files changed, 139 insertions(+), 2 deletions(-)
 create mode 100644 combo/apps/lingo/migrations/0031_auto_20171115_1059.py
 create mode 100644 combo/apps/lingo/templates/lingo/combo/invoice_email_notification_body.html
 create mode 100644 combo/apps/lingo/templates/lingo/combo/invoice_email_notification_body.txt
 create mode 100644 combo/apps/lingo/templates/lingo/combo/invoice_email_notification_subject.txt
combo/apps/lingo/migrations/0031_auto_20171115_1059.py
1
# -*- coding: utf-8 -*-
2
from __future__ import unicode_literals
3

  
4
from django.db import migrations, models
5

  
6

  
7
class Migration(migrations.Migration):
8

  
9
    dependencies = [
10
        ('lingo', '0030_transaction_to_be_paid_remote_items'),
11
    ]
12

  
13
    operations = [
14
        migrations.CreateModel(
15
            name='InvoiceEmailNotification',
16
            fields=[
17
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
18
                ('invoice_id', models.CharField(max_length=128)),
19
                ('last_notification_datetime', models.DateTimeField(auto_now_add=True)),
20
            ],
21
            options={
22
                'get_latest_by': 'last_notification_datetime',
23
            },
24
        ),
25
        migrations.AddField(
26
            model_name='regie',
27
            name='invoice_email_notifications_delay',
28
            field=models.IntegerField(default=10, help_text='in days', verbose_name='Delay after which email notifications will be resent'),
29
        ),
30
        migrations.AddField(
31
            model_name='invoiceemailnotification',
32
            name='regie',
33
            field=models.ForeignKey(to='lingo.Regie'),
34
        ),
35
    ]
combo/apps/lingo/models.py
27 27
import eopayment
28 28
from jsonfield import JSONField
29 29

  
30
from django import template
31 30
from django.conf import settings
32 31
from django.db import models
33 32
from django.forms import models as model_forms, Select
34 33
from django.utils.translation import ugettext_lazy as _
35 34
from django.utils import timezone
36 35
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
36
from django.core.mail import EmailMultiAlternatives
37
from django.core.urlresolvers import reverse
37 38
from django.utils.http import urlencode
38 39

  
40
from django.contrib.auth.models import User
41
from django.template.loader import render_to_string
42

  
39 43
from combo.data.fields import RichTextField
40 44
from combo.data.models import CellBase
41 45
from combo.data.library import register_cell_class
......
91 95
    text_on_success = models.TextField(
92 96
            verbose_name=_('Custom text displayed on success'),
93 97
            blank=True, null=True)
98
    invoice_email_notifications_delay = models.IntegerField(verbose_name=_('Delay after which email notifications will be resent'),
99
                                                            help_text=_('in days'), default=10)
94 100

  
95 101
    def is_remote(self):
96 102
        return self.webservice_url != ''
......
203 209
                    extra_fee=True,
204 210
                    user_cancellable=False).save()
205 211

  
212
    def notify_new_remote_invoices_by_email(self):
213
        logger = logging.getLogger(__name__)
214
        subject_template = 'lingo/combo/invoice_email_notification_subject.txt'
215
        text_body_template = 'lingo/combo/invoice_email_notification_body.txt'
216
        html_body_template = 'lingo/combo/invoice_email_notification_body.html'
217
        if not self.is_remote():
218
            return
219

  
220
        url = self.webservice_url + '/pending_invoices_by_nameid/'
221
        response = requests.get(url, remote_service=None, cache_duration=0, log_errors=True)
222
        data = response.json()['data']
223
        if not data:
224
            return
225
        for uuid, items in data.iteritems():
226
            user_get_kwargs = {}
227
            try:
228
                user = User.objects.get(saml_identifiers__name_id=uuid)
229
            except User.DoesNotExist:
230
                logger.warning('Invoices available for unknown user: %s', uuid)
231
                continue
232

  
233
            for item in items['invoices']:
234
                try:
235
                    notification = InvoiceEmailNotification.objects.filter(regie=self, invoice_id=item['id']).latest()
236
                    if notification.last_notification_datetime > timezone.now()-timezone.timedelta(days=self.invoice_email_notifications_delay):
237
                        continue
238
                except InvoiceEmailNotification.DoesNotExist:
239
                    pass
240
                remote_item = build_remote_item(item, self)
241
                payment_url = reverse('view-item', kwargs={'regie_id': self.id,
242
                                    'item_crypto_id': remote_item.crypto_id})
243
                ctx = {'item': remote_item}
244
                # update context with template vars in order to get things such
245
                # portal title and url
246
                ctx.update(settings.TEMPLATE_VARS)
247
                ctx.update({'payment_url': urlparse.urljoin(ctx['portal_url'], payment_url)})
248
                subject = render_to_string([subject_template], ctx).strip()
249
                text_body = render_to_string([text_body_template], ctx)
250
                html_body = render_to_string([html_body_template], ctx)
251
                message = EmailMultiAlternatives(subject, text_body,
252
                            settings.DEFAULT_FROM_EMAIL, [user.email])
253
                message.attach_alternative(html_body, 'text/html')
254
                if item['has_pdf']:
255
                    invoice_pdf = self.get_invoice_pdf(user, item['id'])
256
                    message.attach('%s.pdf' % item['id'], invoice_pdf.content)
257
                message.send()
258
                InvoiceEmailNotification.objects.create(regie=self, invoice_id=item['id'])
259

  
206 260

  
207 261
class BasketItem(models.Model):
208 262
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True)
......
279 333
        self.display_id = display_id or self.id
280 334
        self.subject = subject
281 335
        self.has_pdf = has_pdf
282
        self.online_payment = online_payment
336
        self.online_payment = online_payment and self.amount >= regie.payment_min_amount
283 337
        self.paid = paid
284 338
        self.no_online_payment_reason = no_online_payment_reason
285 339
        if payment_date:
......
619 673
                continue
620 674
            context['regies'].append(regie_id)
621 675
        return extra_context
676

  
677

  
678
class InvoiceEmailNotification(models.Model):
679
    regie = models.ForeignKey(Regie)
680
    invoice_id = models.CharField(max_length=128)
681
    last_notification_datetime = models.DateTimeField(auto_now_add=True)
682

  
683
    class Meta:
684
        get_latest_by = 'last_notification_datetime'
685

  
686
    def __unicode__(self):
687
        return _(u'notification for %s at %s') % (invoice_id, last_notification_datetime)
combo/apps/lingo/templates/lingo/combo/invoice_email_notification_body.html
1
{% load i18n %}
2

  
3
<html>
4
  <body style="max-width: 60em">
5
    <p>{% blocktrans with id=item.id creation_date=item.creation_date|date:"DATE_FORMAT" amount=item.amount %}
6
      We inform you that your invoice nr. {{ id }} issued on {{ creation_date }} of amount of {{ amount }}€ is available on {{ site_title }}.
7
      {% endblocktrans %}</p>
8
    {% if item.online_payment %}
9
    <p>{% blocktrans %}You can <a href="{{ payment_url }}">view and pay it online</a>.{% endblocktrans %}</p>
10
    {% else %}
11
    <p>{% blocktrans %}You can view it by going on your <a href="{{ portal_url }}">{{ site_title }}</a>.{% endblocktrans %}</p>
12
    {% if item.no_online_payment_reason == 'autobilling' %}
13
    <p>{% blocktrans with debit_date=item.payment_limit_date|date:"DATE_FORMAT" %}
14
      The amount of this invoice will be debited from your account at {{ debit_date }}.
15
      {% endblocktrans %}
16
    </p>
17
    {% endif %}
18
    {% endif %}
19
  </body>
20
</html>
combo/apps/lingo/templates/lingo/combo/invoice_email_notification_body.txt
1
{% load i18n %}
2
{% blocktrans with id=item.id creation_date=item.creation_date|date:"DATE_FORMAT" amount=item.amount %}We inform you that your invoice nr. {{ id }} issued on {{ creation_date }} of amount of {{ amount }}€ is available on {{ site_title }}.{% endblocktrans %}
3

  
4
{% if item.online_payment %}
5
{% blocktrans %}You can view and pay it online on {{ payment_url }}.{% endblocktrans %}
6
{% else %}{% blocktrans %}You can view it by going on {{ portal_url }}.{% endblocktrans %}
7

  
8
{% if item.no_online_payment_reason == 'autobilling' %}
9
{% blocktrans with debit_date=item.payment_limit_date|date:"DATE_FORMAT" %}The amount of this invoice will be debited from your account at {{ debit_date }}.{% endblocktrans %}
10
{% endif %}
11
{% endif %}
12

  
combo/apps/lingo/templates/lingo/combo/invoice_email_notification_subject.txt
1
{% load i18n %}
2
{% blocktrans with invoice_id=item.id %}
3
{{ site_title }}: new invoice nr. {{ invoice_id }} is available
4
{% endblocktrans %}
0
-