1 from django.apps import apps
2 from django.conf import settings
3 from django.core.mail import send_mail
4 from django.db import models
5 from django.template import Template, Context
6 from django.urls import reverse
7 from django.utils.timezone import now
8 from django.utils.translation import ugettext_lazy as _
9 from sentry_sdk import capture_exception
10 from catalogue.utils import get_random_hash
11 from .states import Level, states
14 class EmailTemplate(models.Model):
15 state = models.CharField(_('state'), max_length=128, choices=[(s.slug, s.name) for s in states], help_text='?')
16 subject = models.CharField(_('subject'), max_length=1024)
17 body = models.TextField(_('body'))
18 min_days_since = models.SmallIntegerField(_('min days since'), null=True, blank=True)
19 max_days_since = models.SmallIntegerField(_('max days since'), null=True, blank=True)
20 min_hour = models.PositiveSmallIntegerField(_('min hour'), null=True, blank=True)
21 max_hour = models.PositiveSmallIntegerField(_('max hour'), null=True, blank=True)
22 min_day_of_month = models.PositiveSmallIntegerField(_('min day of month'), null=True, blank=True)
23 max_day_of_month = models.PositiveSmallIntegerField(_('max day of month'), null=True, blank=True)
24 dow_1 = models.BooleanField(_('Monday'), default=True)
25 dow_2 = models.BooleanField(_('Tuesday'), default=True)
26 dow_3 = models.BooleanField(_('Wednesday'), default=True)
27 dow_4 = models.BooleanField(_('Thursday'), default=True)
28 dow_5 = models.BooleanField(_('Friday'), default=True)
29 dow_6 = models.BooleanField(_('Saturday'), default=True)
30 dow_7 = models.BooleanField(_('Sunday'), default=True)
31 is_active = models.BooleanField(_('active'), default=False)
34 verbose_name = _('email template')
35 verbose_name_plural = _('email templates')
38 return '%s (%+d)' % (self.get_state_display(), self.min_days_since or 0)
40 def run(self, time=None, verbose=False, dry_run=False):
41 state = self.get_state(time=time)
42 contacts = state.get_contacts()
44 contacts = contacts.exclude(emailsent__template=self)
45 for contact in contacts:
46 if not contact.is_annoyed:
47 self.send(contact, verbose=verbose, dry_run=dry_run)
49 def get_state(self, time=None, test=False):
51 if s.slug == self.state:
54 min_days_since=self.min_days_since,
55 max_days_since=self.max_days_since,
58 raise ValueError('Unknown state', s.state)
60 def send(self, contact, verbose=False, dry_run=False, test=False):
61 state = self.get_state(test=test)
62 ctx = state.get_context(contact)
63 ctx['contact'] = contact
66 subject = Template(self.subject).render(ctx)
68 subject = "[test] " + subject
70 body_template = '{% extends "messaging/email_body.html" %}{% block body %}' + self.body + '{% endblock %}'
71 body = Template(body_template).render(ctx)
74 print(contact.email, subject)
77 send_mail(subject, body, settings.CONTACT_EMAIL, [contact.email], fail_silently=False)
82 self.emailsent_set.create(
88 def send_test_email(self, email):
93 self.send(contact, test=True)
96 class Contact(models.Model):
97 email = models.EmailField(unique=True)
98 level = models.PositiveSmallIntegerField(
100 (Level.COLD, _('Cold')),
101 (Level.TRIED, _('Would-be donor')),
102 (Level.SINGLE, _('One-time donor')),
103 (Level.RECURRING, _('Recurring donor')),
104 (Level.OPT_OUT, _('Opt out')),
106 since = models.DateTimeField()
107 expires_at = models.DateTimeField(null=True, blank=True)
108 key = models.CharField(max_length=64, blank=True)
111 verbose_name = _('contact')
112 verbose_name_plural = _('contacts')
114 def save(self, *args, **kwargs):
116 self.key = get_random_hash(self.email)
117 super().save(*args, **kwargs)
120 def is_annoyed(self):
121 cutoff = now() - timedelta(settings.MESSAGING_MIN_DAYS)
122 return self.emailsent_set.filter(timestamp__gte=cutoff).exists()
124 def get_optout_url(self):
125 return reverse('messaging_optout', args=[self.key])
128 def update(cls, email, level, since, expires_at=None):
129 obj, created = cls.objects.get_or_create(email=email, defaults={
132 "expires_at": expires_at
135 obj.ascend(level, since, expires_at)
137 def ascend(self, level, since=None, expires_at=None):
140 if level < self.level:
142 if level == self.level:
143 self.since = min(since, self.since)
145 if expires_at and self.expires_at:
146 self.expires_at = max(expires_at, self.expires_at)
148 self.expires_at = expires_at
152 self.expires_at = expires_at
156 class EmailSent(models.Model):
157 template = models.ForeignKey(EmailTemplate, models.CASCADE)
158 contact = models.ForeignKey(Contact, models.CASCADE)
159 timestamp = models.DateTimeField(auto_now_add=True)
160 subject = models.CharField(_('subject'), max_length=1024)
161 body = models.TextField(_('body'))
164 verbose_name = _('email sent')
165 verbose_name_plural = _('emails sent')
166 ordering = ('-timestamp',)
169 return '%s %s' % (self.email, self.timestamp)