From 364f89fe756d2a53d9a2b16e30b4bcece018af52 Mon Sep 17 00:00:00 2001 From: Serghei Mihai Date: Tue, 14 Nov 2017 18:48:44 +0100 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 diff --git a/combo/apps/lingo/migrations/0031_auto_20171115_1059.py b/combo/apps/lingo/migrations/0031_auto_20171115_1059.py new file mode 100644 index 0000000..ad9c966 --- /dev/null +++ b/combo/apps/lingo/migrations/0031_auto_20171115_1059.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('lingo', '0030_transaction_to_be_paid_remote_items'), + ] + + operations = [ + migrations.CreateModel( + name='InvoiceEmailNotification', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('invoice_id', models.CharField(max_length=128)), + ('last_notification_datetime', models.DateTimeField(auto_now_add=True)), + ], + options={ + 'get_latest_by': 'last_notification_datetime', + }, + ), + migrations.AddField( + model_name='regie', + name='invoice_email_notifications_delay', + field=models.IntegerField(default=10, help_text='in days', verbose_name='Delay after which email notifications will be resent'), + ), + migrations.AddField( + model_name='invoiceemailnotification', + name='regie', + field=models.ForeignKey(to='lingo.Regie'), + ), + ] diff --git a/combo/apps/lingo/models.py b/combo/apps/lingo/models.py index b8b75a5..2e95e48 100644 --- a/combo/apps/lingo/models.py +++ b/combo/apps/lingo/models.py @@ -27,15 +27,19 @@ from decimal import Decimal import eopayment from jsonfield import JSONField -from django import template from django.conf import settings from django.db import models from django.forms import models as model_forms, Select from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.core.exceptions import ObjectDoesNotExist, PermissionDenied +from django.core.mail import EmailMultiAlternatives +from django.core.urlresolvers import reverse from django.utils.http import urlencode +from django.contrib.auth.models import User +from django.template.loader import render_to_string + from combo.data.fields import RichTextField from combo.data.models import CellBase from combo.data.library import register_cell_class @@ -91,6 +95,8 @@ class Regie(models.Model): text_on_success = models.TextField( verbose_name=_('Custom text displayed on success'), blank=True, null=True) + invoice_email_notifications_delay = models.IntegerField(verbose_name=_('Delay after which email notifications will be resent'), + help_text=_('in days'), default=10) def is_remote(self): return self.webservice_url != '' @@ -203,6 +209,54 @@ class Regie(models.Model): extra_fee=True, user_cancellable=False).save() + def notify_new_remote_invoices_by_email(self): + logger = logging.getLogger(__name__) + 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' + if not self.is_remote(): + return + + url = self.webservice_url + '/pending_invoices_by_nameid/' + response = requests.get(url, remote_service=None, cache_duration=0, log_errors=True) + data = response.json()['data'] + if not data: + return + for uuid, items in data.iteritems(): + user_get_kwargs = {} + try: + user = User.objects.get(saml_identifiers__name_id=uuid) + except User.DoesNotExist: + logger.warning('Invoices available for unknown user: %s', uuid) + continue + + for item in items['invoices']: + try: + notification = InvoiceEmailNotification.objects.filter(regie=self, invoice_id=item['id']).latest() + if notification.last_notification_datetime > timezone.now()-timezone.timedelta(days=self.invoice_email_notifications_delay): + continue + except InvoiceEmailNotification.DoesNotExist: + pass + remote_item = build_remote_item(item, self) + payment_url = reverse('view-item', kwargs={'regie_id': self.id, + 'item_crypto_id': remote_item.crypto_id}) + ctx = {'item': remote_item} + # update context with template vars in order to get things such + # portal title and url + ctx.update(settings.TEMPLATE_VARS) + ctx.update({'payment_url': urlparse.urljoin(ctx['portal_url'], payment_url)}) + 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, + settings.DEFAULT_FROM_EMAIL, [user.email]) + message.attach_alternative(html_body, 'text/html') + if item['has_pdf']: + invoice_pdf = self.get_invoice_pdf(user, item['id']) + message.attach('%s.pdf' % item['id'], invoice_pdf.content) + message.send() + InvoiceEmailNotification.objects.create(regie=self, invoice_id=item['id']) + class BasketItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True) @@ -279,7 +333,7 @@ class RemoteItem(object): self.display_id = display_id or self.id self.subject = subject self.has_pdf = has_pdf - self.online_payment = online_payment + self.online_payment = online_payment and self.amount >= regie.payment_min_amount self.paid = paid self.no_online_payment_reason = no_online_payment_reason if payment_date: @@ -619,3 +673,15 @@ class TipiPaymentFormCell(CellBase): continue context['regies'].append(regie_id) return extra_context + + +class InvoiceEmailNotification(models.Model): + regie = models.ForeignKey(Regie) + invoice_id = models.CharField(max_length=128) + last_notification_datetime = models.DateTimeField(auto_now_add=True) + + class Meta: + get_latest_by = 'last_notification_datetime' + + def __unicode__(self): + return _(u'notification for %s at %s') % (invoice_id, last_notification_datetime) diff --git a/combo/apps/lingo/templates/lingo/combo/invoice_email_notification_body.html b/combo/apps/lingo/templates/lingo/combo/invoice_email_notification_body.html new file mode 100644 index 0000000..16bb059 --- /dev/null +++ b/combo/apps/lingo/templates/lingo/combo/invoice_email_notification_body.html @@ -0,0 +1,20 @@ +{% load i18n %} + + + +

{% 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 %}

+ {% if item.online_payment %} +

{% blocktrans %}You can view and pay it online.{% endblocktrans %}

+ {% else %} +

{% blocktrans %}You can view it by going on your {{ site_title }}.{% endblocktrans %}

+ {% if item.no_online_payment_reason == 'autobilling' %} +

{% 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 %} +

+ {% endif %} + {% endif %} + + diff --git a/combo/apps/lingo/templates/lingo/combo/invoice_email_notification_body.txt b/combo/apps/lingo/templates/lingo/combo/invoice_email_notification_body.txt new file mode 100644 index 0000000..e40f191 --- /dev/null +++ b/combo/apps/lingo/templates/lingo/combo/invoice_email_notification_body.txt @@ -0,0 +1,12 @@ +{% load i18n %} +{% 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 %} + +{% if item.online_payment %} +{% blocktrans %}You can view and pay it online on {{ payment_url }}.{% endblocktrans %} +{% else %}{% blocktrans %}You can view it by going on {{ portal_url }}.{% endblocktrans %} + +{% if item.no_online_payment_reason == 'autobilling' %} +{% 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 %} +{% endif %} +{% endif %} + diff --git a/combo/apps/lingo/templates/lingo/combo/invoice_email_notification_subject.txt b/combo/apps/lingo/templates/lingo/combo/invoice_email_notification_subject.txt new file mode 100644 index 0000000..1434cd2 --- /dev/null +++ b/combo/apps/lingo/templates/lingo/combo/invoice_email_notification_subject.txt @@ -0,0 +1,4 @@ +{% load i18n %} +{% blocktrans with invoice_id=item.id %} +{{ site_title }}: new invoice nr. {{ invoice_id }} is available +{% endblocktrans %} -- 2.15.0