Search.
[wolnelektury.git] / src / messaging / models.py
index 8ef6c4c..e1b26a8 100644 (file)
@@ -1,10 +1,12 @@
+from datetime import timedelta
 from django.apps import apps
 from django.conf import settings
 from django.core.mail import send_mail
 from django.db import models
 from django.template import Template, Context
 from django.urls import reverse
 from django.apps import apps
 from django.conf import settings
 from django.core.mail import send_mail
 from django.db import models
 from django.template import Template, Context
 from django.urls import reverse
-from django.utils.translation import ugettext_lazy as _
+from django.utils.timezone import now, get_current_timezone
+from django.utils.translation import gettext_lazy as _
 from sentry_sdk import capture_exception
 from catalogue.utils import get_random_hash
 from .states import Level, states
 from sentry_sdk import capture_exception
 from catalogue.utils import get_random_hash
 from .states import Level, states
@@ -36,13 +38,24 @@ class EmailTemplate(models.Model):
     def __str__(self):
         return '%s (%+d)' % (self.get_state_display(), self.min_days_since or 0)
 
     def __str__(self):
         return '%s (%+d)' % (self.get_state_display(), self.min_days_since or 0)
 
+    @classmethod
+    def get_current(cls, time=None):
+        time = (time or now()).astimezone(get_current_timezone())
+        weekday = time.isoweekday()
+        qs = cls.objects.filter(is_active=True)
+        qs = qs.exclude(min_hour__gt=time.hour).exclude(max_hour__lte=time.hour)
+        qs = qs.exclude(min_day_of_month__gt=time.day).exclude(max_day_of_month__lte=time.day)
+        qs = qs.exclude(**{f'dow_{weekday}': False})
+        return qs
+
     def run(self, time=None, verbose=False, dry_run=False):
         state = self.get_state(time=time)
         contacts = state.get_contacts()
     
     def run(self, time=None, verbose=False, dry_run=False):
         state = self.get_state(time=time)
         contacts = state.get_contacts()
     
-        contacts = contacts.exclude(emailsent_set__template=self)
+        contacts = contacts.exclude(emailsent__template=self)
         for contact in contacts:
         for contact in contacts:
-            self.send(contact, verbose=verbose, dry_run=dry_run)
+            if not contact.is_annoyed:
+                self.send(contact, verbose=verbose, dry_run=dry_run)
 
     def get_state(self, time=None, test=False):
         for s in states:
 
     def get_state(self, time=None, test=False):
         for s in states:
@@ -69,7 +82,7 @@ class EmailTemplate(models.Model):
         body = Template(body_template).render(ctx)
 
         if verbose:
         body = Template(body_template).render(ctx)
 
         if verbose:
-            print(contact.email, subject)
+            print(self.pk, subject, contact.email)
         if not dry_run:
             try:
                 send_mail(subject, body, settings.CONTACT_EMAIL, [contact.email], fail_silently=False)
         if not dry_run:
             try:
                 send_mail(subject, body, settings.CONTACT_EMAIL, [contact.email], fail_silently=False)
@@ -99,6 +112,7 @@ class Contact(models.Model):
             (Level.TRIED, _('Would-be donor')),
             (Level.SINGLE, _('One-time donor')),
             (Level.RECURRING, _('Recurring donor')),
             (Level.TRIED, _('Would-be donor')),
             (Level.SINGLE, _('One-time donor')),
             (Level.RECURRING, _('Recurring donor')),
+            (Level.MANUAL_MEMBER, _('Manually set as member')),
             (Level.OPT_OUT, _('Opt out')),
         ])
     since = models.DateTimeField()
             (Level.OPT_OUT, _('Opt out')),
         ])
     since = models.DateTimeField()
@@ -114,6 +128,11 @@ class Contact(models.Model):
             self.key = get_random_hash(self.email)
         super().save(*args, **kwargs)
 
             self.key = get_random_hash(self.email)
         super().save(*args, **kwargs)
 
+    @property
+    def is_annoyed(self):
+        cutoff = now() - timedelta(settings.MESSAGING_MIN_DAYS)
+        return self.emailsent_set.filter(timestamp__gte=cutoff).exists()
+
     def get_optout_url(self):
         return reverse('messaging_optout', args=[self.key])
 
     def get_optout_url(self):
         return reverse('messaging_optout', args=[self.key])
 
@@ -127,7 +146,9 @@ class Contact(models.Model):
         if not created:
             obj.ascend(level, since, expires_at)
 
         if not created:
             obj.ascend(level, since, expires_at)
 
-    def ascend(self, level, since, expires_at=None):
+    def ascend(self, level, since=None, expires_at=None):
+        if since is None:
+            since = now()
         if level < self.level:
             return
         if level == self.level:
         if level < self.level:
             return
         if level == self.level:
@@ -143,6 +164,19 @@ class Contact(models.Model):
             self.expires_at = expires_at
         self.save()
 
             self.expires_at = expires_at
         self.save()
 
+    @classmethod
+    def reset(cls, email):
+        cls.objects.filter(email=email).delete()
+        Schedule = apps.get_model('club', 'Schedule')
+        Membership = apps.get_model('club', 'Membership')
+        for schedule in Schedule.objects.filter(email=email):
+            schedule.update_contact()
+        for membership in Membership.objects.filter(manual=True, user__email=email):
+            membership.update_contact()
+
+    def wl_optout_url(self):
+        return 'https://wolnelektury.pl' + self.get_optout_url()
+
 
 class EmailSent(models.Model):
     template = models.ForeignKey(EmailTemplate, models.CASCADE)
 
 class EmailSent(models.Model):
     template = models.ForeignKey(EmailTemplate, models.CASCADE)
@@ -157,5 +191,5 @@ class EmailSent(models.Model):
         ordering = ('-timestamp',)
 
     def __str__(self):
         ordering = ('-timestamp',)
 
     def __str__(self):
-        return '%s %s' % (self.email, self.timestamp)
+        return '%s %s' % (self.contact.email, self.timestamp)