Browse Source

Push updated MaillingList when member email change

Jocelyn Delalande 6 years ago
parent
commit
ddd6995ca5
1 changed files with 34 additions and 1 deletions
  1. 34 1
      maillists/models.py

+ 34 - 1
maillists/models.py

@@ -6,7 +6,7 @@ import subprocess
 
 from django.conf import settings
 from django.db import models
-from django.db.models.signals import m2m_changed
+from django.db.models.signals import pre_save, post_save, m2m_changed
 from django.dispatch import receiver
 
 from coin.members.models import Member
@@ -91,3 +91,36 @@ def push_updated_list(sender, instance, action, reverse, model, pk_set, **kwargs
             ml.sync_to_list_server(force_clear=True)
         else:
             ml.sync_to_list_server()
+
+
+@receiver(pre_save, sender=Member)
+def store_previous_email(sender, instance, *args, **kwargs):
+    """Record the email address for post_save handler
+
+    update_an_email_address needs the old email address for comparison, but
+    this information is not available at post_save stage.
+    """
+    member = instance
+
+    # if not, this is a user creation, nothing to do
+    if member.pk:
+        old_member = Member.objects.get(pk=member.pk)
+        member._previous_email = old_member.email
+
+
+@receiver(post_save, sender=Member)
+def update_an_email_address(sender, instance, *args, **kwargs):
+    """Check if the member email has changed and sync mail lists if so.
+
+    We do that at post_save stage because we need the new information to be
+    recorded in database, otherwise, sync_list_to_server() would use the old
+    email.
+    """
+    member = instance
+    old_email = getattr(member, '_previous_email', None)
+
+    if old_email and (old_email != member.email):
+        for maillist in member.subscribed_maillinglists.all():
+            maillist.sync_to_list_server()
+
+            # Error handling