1 from datetime import timedelta
2 from django.apps import apps
3 from django.conf import settings
4 from django.core.mail import send_mail
5 from django.db import models
6 from django.template import Template, Context
7 from django.urls import reverse
8 from django.utils.timezone import now, get_current_timezone
9 from django.utils.translation import ugettext_lazy as _
10 from sentry_sdk import capture_exception
11 from catalogue.utils import get_random_hash
12 from .states import Level, states
15 class EmailTemplate(models.Model):
16 state = models.CharField(_('state'), max_length=128, choices=[(s.slug, s.name) for s in states], help_text='?')
17 subject = models.CharField(_('subject'), max_length=1024)
18 body = models.TextField(_('body'))
19 min_days_since = models.SmallIntegerField(_('min days since'), null=True, blank=True)
20 max_days_since = models.SmallIntegerField(_('max days since'), null=True, blank=True)
21 min_hour = models.PositiveSmallIntegerField(_('min hour'), null=True, blank=True)
22 max_hour = models.PositiveSmallIntegerField(_('max hour'), null=True, blank=True)
23 min_day_of_month = models.PositiveSmallIntegerField(_('min day of month'), null=True, blank=True)
24 max_day_of_month = models.PositiveSmallIntegerField(_('max day of month'), null=True, blank=True)
25 dow_1 = models.BooleanField(_('Monday'), default=True)
26 dow_2 = models.BooleanField(_('Tuesday'), default=True)
27 dow_3 = models.BooleanField(_('Wednesday'), default=True)
28 dow_4 = models.BooleanField(_('Thursday'), default=True)
29 dow_5 = models.BooleanField(_('Friday'), default=True)
30 dow_6 = models.BooleanField(_('Saturday'), default=True)
31 dow_7 = models.BooleanField(_('Sunday'), default=True)
32 is_active = models.BooleanField(_('active'), default=False)
35 verbose_name = _('email template')
36 verbose_name_plural = _('email templates')
39 return '%s (%+d)' % (self.get_state_display(), self.min_days_since or 0)
42 def get_current(cls, time=None):
43 time = (time or now()).astimezone(get_current_timezone())
44 weekday = time.isoweekday()
45 qs = cls.objects.filter(is_active=True)
46 qs = qs.exclude(min_hour__gt=time.hour).exclude(max_hour__lte=time.hour)
47 qs = qs.exclude(min_day_of_month__gt=time.day).exclude(max_day_of_month__lte=time.day)
48 qs = qs.exclude(**{f'dow_{weekday}': False})
51 def run(self, time=None, verbose=False, dry_run=False):
52 state = self.get_state(time=time)
53 contacts = state.get_contacts()
55 contacts = contacts.exclude(emailsent__template=self)
56 for contact in contacts:
57 if not contact.is_annoyed:
58 self.send(contact, verbose=verbose, dry_run=dry_run)
60 def get_state(self, time=None, test=False):
62 if s.slug == self.state:
65 min_days_since=self.min_days_since,
66 max_days_since=self.max_days_since,
69 raise ValueError('Unknown state', s.state)
71 def send(self, contact, verbose=False, dry_run=False, test=False):
72 state = self.get_state(test=test)
73 ctx = state.get_context(contact)
74 ctx['contact'] = contact
77 subject = Template(self.subject).render(ctx)
79 subject = "[test] " + subject
81 body_template = '{% extends "messaging/email_body.html" %}{% block body %}' + self.body + '{% endblock %}'
82 body = Template(body_template).render(ctx)
85 print(self.pk, subject, contact.email)
88 send_mail(subject, body, settings.CONTACT_EMAIL, [contact.email], fail_silently=False)
93 self.emailsent_set.create(
99 def send_test_email(self, email):
104 self.send(contact, test=True)
107 class Contact(models.Model):
108 email = models.EmailField(unique=True)
109 level = models.PositiveSmallIntegerField(
111 (Level.COLD, _('Cold')),
112 (Level.TRIED, _('Would-be donor')),
113 (Level.SINGLE, _('One-time donor')),
114 (Level.RECURRING, _('Recurring donor')),
115 (Level.OPT_OUT, _('Opt out')),
117 since = models.DateTimeField()
118 expires_at = models.DateTimeField(null=True, blank=True)
119 key = models.CharField(max_length=64, blank=True)
122 verbose_name = _('contact')
123 verbose_name_plural = _('contacts')
125 def save(self, *args, **kwargs):
127 self.key = get_random_hash(self.email)
128 super().save(*args, **kwargs)
131 def is_annoyed(self):
132 cutoff = now() - timedelta(settings.MESSAGING_MIN_DAYS)
133 return self.emailsent_set.filter(timestamp__gte=cutoff).exists()
135 def get_optout_url(self):
136 return reverse('messaging_optout', args=[self.key])
139 def update(cls, email, level, since, expires_at=None):
140 obj, created = cls.objects.get_or_create(email=email, defaults={
143 "expires_at": expires_at
146 obj.ascend(level, since, expires_at)
148 def ascend(self, level, since=None, expires_at=None):
151 if level < self.level:
153 if level == self.level:
154 self.since = min(since, self.since)
156 if expires_at and self.expires_at:
157 self.expires_at = max(expires_at, self.expires_at)
159 self.expires_at = expires_at
163 self.expires_at = expires_at
167 class EmailSent(models.Model):
168 template = models.ForeignKey(EmailTemplate, models.CASCADE)
169 contact = models.ForeignKey(Contact, models.CASCADE)
170 timestamp = models.DateTimeField(auto_now_add=True)
171 subject = models.CharField(_('subject'), max_length=1024)
172 body = models.TextField(_('body'))
175 verbose_name = _('email sent')
176 verbose_name_plural = _('emails sent')
177 ordering = ('-timestamp',)
180 return '%s %s' % (self.contact.email, self.timestamp)