Projet

Général

Profil

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

Serghei Mihai (congés, retour 15/05), 14 novembre 2017 18:52

Télécharger (9,21 ko)

Voir les différences:

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

 .../lingo/migrations/0031_auto_20171114_1702.py    | 36 +++++++++++
 combo/apps/lingo/models.py                         | 69 +++++++++++++++++++++-
 .../combo/invoice_email_notification_body.html     | 23 ++++++++
 .../combo/invoice_email_notification_body.txt      |  6 ++
 .../combo/invoice_email_notification_subject.txt   |  4 ++
 5 files changed, 137 insertions(+), 1 deletion(-)
 create mode 100644 combo/apps/lingo/migrations/0031_auto_20171114_1702.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_20171114_1702.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=0, help_text='In days'),
29
            preserve_default=False,
30
        ),
31
        migrations.AddField(
32
            model_name='invoiceemailnotification',
33
            name='regie',
34
            field=models.ForeignKey(to='lingo.Regie'),
35
        ),
36
    ]
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(help_text=_('In days'))
94 99

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

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

  
219
        url = self.webservice_url + '/pending_invoices_by_nameid/'
220
        response = requests.get(url, remote_service=None, cache_duration=0, log_errors=True)
221
        data = response.json()['data']
222
        if not data:
223
            return
224
        for uuid, items in data.iteritems():
225
            user_get_kwargs = {}
226
            try:
227
                user = User.objects.get(saml_identifiers__name_id=uuid)
228
            except User.DoesNotExist:
229
                logger.warning('Invoices available for unknown user: %s', uuid)
230
                continue
231
            if items['invoices']:
232
                for item in items['invoices']:
233
                    try:
234
                        notification = InvoiceEmailNotification.objects.filter(regie=self, invoice_id=item['id']).latest()
235
                        if notification.last_notification_datetime > timezone.now()-timezone.timedelta(days=self.invoice_email_notifications_delay):
236
                            continue
237
                    except InvoiceEmailNotification.DoesNotExist:
238
                        pass
239
                    remote_item = build_remote_item(item, self)
240
                    # get host url in order to build payment url
241
                    base_url = getattr(settings, 'SITE_BASE_URL', '')
242
                    payment_url = reverse('view-item', kwargs={'regie_id': self.id,
243
                                        'item_crypto_id': remote_item.crypto_id})
244
                    ctx = {'payment_url': urlparse.urljoin(base_url, payment_url),
245
                           'item': remote_item}
246
                    if base_url:
247
                        ctx.update({'portal_url': base_url})
248

  
249
                    subject = render_to_string([subject_template], ctx).strip()
250
                    text_body = render_to_string([text_body_template], ctx)
251
                    html_body = render_to_string([html_body_template], ctx)
252
                    message = EmailMultiAlternatives(subject, text_body,
253
                                settings.DEFAULT_FROM_EMAIL, [user.email])
254
                    message.attach_alternative(html_body, 'text/html')
255
                    if item['has_pdf']:
256
                        invoice_pdf = self.get_invoice_pdf(user, item['id'])
257
                        message.attach('%s.pdf' % item['id'], invoice_pdf.content)
258
                    message.send()
259
                    InvoiceEmailNotification.objects.create(regie=self, invoice_id=item['id'])
260

  
206 261

  
207 262
class BasketItem(models.Model):
208 263
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True)
......
619 674
                continue
620 675
            context['regies'].append(regie_id)
621 676
        return extra_context
677

  
678

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

  
684
    class Meta:
685
        get_latest_by = 'last_notification_datetime'
686

  
687
    def __unicode__(self):
688
        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: 80em">
5
    <p>{% blocktrans with id=item.id %}
6
      A new invoice nr. {{ id }} is available.
7
      {% endblocktrans %}
8
    </p>
9
    {% if portal_url %}
10
    <p>
11
      {% blocktrans %}
12
      To view it please go to <a href="{{ portal_url }}">portal</a> or <a href="{{ payment_url }}">pay it directly</a>.
13
      {% endblocktrans %}
14
    </p>
15
    {% else %}
16
    <p>
17
      {% blocktrans %}
18
      <a href="{{ payment_url }}">Pay it</a>.
19
      {% endblocktrans %}
20
    </p>
21
    {% endif %}
22
  </body>
23
</html>
combo/apps/lingo/templates/lingo/combo/invoice_email_notification_body.txt
1
{% load i18n %}
2
{% blocktrans with id=item.id %}A new invoice nr. {{ id }} is available.{% endblocktrans %}
3
{% if portal_url %}
4
{% blocktrans %}To view it please go to {{ portal_url }} or pay it directly on {{ payment_url }}.{% endblocktrans %}
5
{% else %}{% blocktrans %}Pay it on {{ payment_url }}.{% endblocktrans %}
6
{% endif %}
combo/apps/lingo/templates/lingo/combo/invoice_email_notification_subject.txt
1
{% load i18n %}
2
{% blocktrans with invoice_id=item.id %}
3
Your new invoice nr. {{ invoice_id }}
4
{% endblocktrans %}
0
-