Parcourir la source

Add first draft to send a welcome email to a member

Fabs il y a 10 ans
Parent
commit
e1dcf2da90

coin/templates/admin/billing/invoice/change_form.html → coin/billing/templates/admin/billing/invoice/change_form.html


+ 33 - 0
coin/members/admin.py

@@ -1,9 +1,15 @@
 # -*- coding: utf-8 -*-
 from __future__ import unicode_literals
 
+from django.shortcuts import render, get_object_or_404
 from django.contrib import admin
+from django.contrib import messages
 from django.contrib.auth.admin import UserAdmin
 from django.contrib.auth.models import Group
+from django.http import HttpResponseRedirect
+from django.conf.urls import url
+from django.contrib import messages
+
 from coin.members.models import Member, CryptoKey, LdapUser, MembershipFee
 from coin.members.membershipfee_filter import MembershipFeeFilter
 from coin.members.forms import MemberChangeForm, MemberCreationForm
@@ -99,6 +105,33 @@ class MemberAdmin(UserAdmin):
     set_as_non_member.short_description = "Définir comme non adhérent"
 
 
+    def get_urls(self):
+        """Custom admin urls"""
+        urls = super(MemberAdmin, self).get_urls()
+        my_urls = [
+            url(r'^send_welcome_email/(?P<id>\d+)$',
+                self.admin_site.admin_view(self.send_welcome_email),
+                name='send_welcome_email'),
+        ]
+        return my_urls + urls
+
+    def send_welcome_email(self, request, id):
+        """
+        Vue appelée lorsque l'admin souhaite envoyer l'email de bienvenue à un 
+        membre
+        """
+        # TODO : Add better perm here
+        if request.user.is_superuser:
+            member = get_object_or_404(Member, pk=id)
+            member.send_welcome_email()
+            messages.success(request, 'Le courriel de bienvenue a été envoyé à %s' % member.email)
+        else:
+            messages.error(
+                request, 'Vous n\'avez pas l\'autorisation d\'envoyer le '
+                         'courriel de bienvenue.')
+
+        return HttpResponseRedirect(request.META["HTTP_REFERER"])
+
 class MembershipFeeAdmin(admin.ModelAdmin):
     list_display = ('member', 'end_date', 'amount', 'payment_method',
                     'payment_date')

+ 8 - 0
coin/members/models.py

@@ -207,6 +207,14 @@ class Member(CoinLdapSyncMixin, AbstractUser):
         #     ldap_group.members.remove(self.username)
         #     ldap_group.save()
 
+    def send_welcome_email(self):
+        """ Envoie le courriel de bienvenue à ce membre """
+        utils.send_templated_email(to=self.email,
+                                   subject_template='members/emails/welcome_email_subject.txt',
+                                   body_template='members/emails/welcome_email.html',
+                                   context={'member': self})
+
+
     class Meta:
         verbose_name = 'membre'
 

+ 6 - 0
coin/members/templates/admin/members/member/change_form.html

@@ -0,0 +1,6 @@
+{% extends "admin/change_form.html" %}
+{% load url from future %}
+{% block object-tools-items %}
+    <li><a href="{% url 'admin:send_welcome_email' id=object_id %}">Envoyer le courriel de bienvenue</a></li>
+    {{ block.super }}
+{% endblock %}

+ 16 - 0
coin/members/templates/members/emails/welcome_email.html

@@ -0,0 +1,16 @@
+<p>Bonjour {{ member.first_name }},</p>
+
+<p>Ce courriel, confime que tu es bien adhérent à l'association ILLYSE. Bienvenue à toi !</p>
+
+<p>Avant toute chose, il faut initialiser le mot de passe de ton compte sur COIN, 
+notre système d'informations. Pour cela il faut suivre le lien suivant et renseigner son 
+adresse email :<br />
+{{ domain }}{% url 'members:password_reset' %}</p>
+
+<p>Une fois cela fait tu pourras accéder à ton compte adhérent sur COIN depuis cette 
+adresse :<br />
+{{ domain }}{% url 'home' %}</p>
+
+<p>Par ailleurs, nous disposons de plusieurs listes de discussions dont tu peux gérer 
+tes abonnements depuis cette interface :<br />
+https://listes.illyse.org/wws/</p>

+ 1 - 0
coin/members/templates/members/emails/welcome_email_subject.txt

@@ -0,0 +1 @@
+Bienvenue chez ILLYSE !

+ 1 - 1
coin/settings.py

@@ -158,7 +158,7 @@ INSTALLED_APPS = (
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
-    #'django.contrib.sites',
+    'django.contrib.sites',
     'ldapdb',  # LDAP as database backend
     'django.contrib.messages',
     'django.contrib.staticfiles',

+ 19 - 12
coin/utils.py

@@ -7,10 +7,13 @@ import binascii
 import base64
 import html2text
 from datetime import date, timedelta
+
 from django.core.mail import EmailMultiAlternatives
-from django.template import TemplateDoesNotExist
 from django.core.files.storage import FileSystemStorage
 from django.conf import settings
+from django.template.loader import get_template
+from django.template import Context, TemplateDoesNotExist
+from django.contrib.sites.models import Site
 
 
 # Stockage des fichiers privés (comme les factures par exemple)
@@ -31,38 +34,42 @@ def ldap_hash(password):
         return password
 
 
-def send_templated_email(subject, to, template_to_use, context, attachements, from_email=None):
+def send_templated_email(to, subject_template, body_template, context={}, attachements=[]):
     """
     Send a multialternative email based on html and optional txt template.
     """
     
-    # Get default sender if not specified
-    from_email = from_email if from_email else 'coin@illyse.org'
-    
     # Ensure arrays when needed
     if not isinstance(to, list):
         to = [to] 
     if not isinstance(attachements, list):
         attachements = [attachements]
 
-    # If .html is specified in template name remove it
-    if template_to_use.endswith('.html'):
-        template_to_use = template_to_use[:-5]
+    # Add domain in context
+    context['domain'] = Site.objects.get_current()
 
-    # Get html template, fail if not exists
-    template_html = get_template('%s.html' % (template_to_use,))
+    # If .html/.txt is specified in template name remove it
+    body_template = body_template.split('.')[0]
+    subject_template = subject_template.split('.')[0]
+
+    # Get html template for body, fail if not exists
+    template_html = get_template('%s.html' % (body_template,))
     html_content = template_html.render(Context(context))
 
+    # Get txt template for subject, fail if not exists
+    subject_template = get_template('%s.txt' % (subject_template,))
+    subject = subject_template.render(Context(context))
+
     # Try to get a txt version, convert from html to markdown style
     # (using html2text) if fail
     try:
-        template_txt = get_template('%s.txt' % (template_to_use,))
+        template_txt = get_template('%s.txt' % (body_template,))
         text_content = template_txt.render_to_string(Context(context))
     except TemplateDoesNotExist:
         text_content = html2text.html2text(html_content)
     
     # make multipart email default : text, alternative : html
-    msg = EmailMultiAlternatives(subject, text_content, from_email, to)
+    msg = EmailMultiAlternatives(subject=subject, body=text_content, to=to)
     msg.attach_alternative(html_content, "text/html")
     
     # Set attachements