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 self.send(contact, verbose=verbose, dry_run=dry_run)
48 def get_state(self, time=None, test=False):
50 if s.slug == self.state:
53 min_days_since=self.min_days_since,
54 max_days_since=self.max_days_since,
57 raise ValueError('Unknown state', s.state)
59 def send(self, contact, verbose=False, dry_run=False, test=False):
60 state = self.get_state(test=test)
61 ctx = state.get_context(contact)
62 ctx['contact'] = contact
65 subject = Template(self.subject).render(ctx)
67 subject = "[test] " + subject
69 body_template = '{% extends "messaging/email_body.html" %}{% block body %}' + self.body + '{% endblock %}'
70 body = Template(body_template).render(ctx)
73 print(contact.email, subject)
76 send_mail(subject, body, settings.CONTACT_EMAIL, [contact.email], fail_silently=False)
81 self.emailsent_set.create(
87 def send_test_email(self, email):
92 self.send(contact, test=True)
95 class Contact(models.Model):
96 email = models.EmailField(unique=True)
97 level = models.PositiveSmallIntegerField(
99 (Level.COLD, _('Cold')),
100 (Level.TRIED, _('Would-be donor')),
101 (Level.SINGLE, _('One-time donor')),
102 (Level.RECURRING, _('Recurring donor')),
103 (Level.OPT_OUT, _('Opt out')),
105 since = models.DateTimeField()
106 expires_at = models.DateTimeField(null=True, blank=True)
107 key = models.CharField(max_length=64, blank=True)
110 verbose_name = _('contact')
111 verbose_name_plural = _('contacts')
113 def save(self, *args, **kwargs):
115 self.key = get_random_hash(self.email)
116 super().save(*args, **kwargs)
118 def get_optout_url(self):
119 return reverse('messaging_optout', args=[self.key])
122 def update(cls, email, level, since, expires_at=None):
123 obj, created = cls.objects.get_or_create(email=email, defaults={
126 "expires_at": expires_at
129 obj.ascend(level, since, expires_at)
131 def ascend(self, level, since=None, expires_at=None):
134 if level < self.level:
136 if level == self.level:
137 self.since = min(since, self.since)
139 if expires_at and self.expires_at:
140 self.expires_at = max(expires_at, self.expires_at)
142 self.expires_at = expires_at
146 self.expires_at = expires_at
150 class EmailSent(models.Model):
151 template = models.ForeignKey(EmailTemplate, models.CASCADE)
152 contact = models.ForeignKey(Contact, models.CASCADE)
153 timestamp = models.DateTimeField(auto_now_add=True)
154 subject = models.CharField(_('subject'), max_length=1024)
155 body = models.TextField(_('body'))
158 verbose_name = _('email sent')
159 verbose_name_plural = _('emails sent')
160 ordering = ('-timestamp',)
163 return '%s %s' % (self.email, self.timestamp)