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.translation import ugettext_lazy as _
8 from sentry_sdk import capture_exception
9 from catalogue.utils import get_random_hash
10 from .states import Level, states
13 class EmailTemplate(models.Model):
14 state = models.CharField(_('state'), max_length=128, choices=[(s.slug, s.name) for s in states], help_text='?')
15 subject = models.CharField(_('subject'), max_length=1024)
16 body = models.TextField(_('body'))
17 min_days_since = models.SmallIntegerField(_('min days since'), null=True, blank=True)
18 max_days_since = models.SmallIntegerField(_('max days since'), null=True, blank=True)
19 min_hour = models.PositiveSmallIntegerField(_('min hour'), null=True, blank=True)
20 max_hour = models.PositiveSmallIntegerField(_('max hour'), null=True, blank=True)
21 min_day_of_month = models.PositiveSmallIntegerField(_('min day of month'), null=True, blank=True)
22 max_day_of_month = models.PositiveSmallIntegerField(_('max day of month'), null=True, blank=True)
23 dow_1 = models.BooleanField(_('Monday'), default=True)
24 dow_2 = models.BooleanField(_('Tuesday'), default=True)
25 dow_3 = models.BooleanField(_('Wednesday'), default=True)
26 dow_4 = models.BooleanField(_('Thursday'), default=True)
27 dow_5 = models.BooleanField(_('Friday'), default=True)
28 dow_6 = models.BooleanField(_('Saturday'), default=True)
29 dow_7 = models.BooleanField(_('Sunday'), default=True)
30 is_active = models.BooleanField(_('active'), default=False)
33 verbose_name = _('email template')
34 verbose_name_plural = _('email templates')
37 return '%s (%+d)' % (self.get_state_display(), self.min_days_since or 0)
39 def run(self, time=None, verbose=False, dry_run=False):
40 state = self.get_state(time=time)
41 contacts = state.get_contacts()
43 contacts = contacts.exclude(emailsent__template=self)
44 for contact in contacts:
45 self.send(contact, verbose=verbose, dry_run=dry_run)
47 def get_state(self, time=None, test=False):
49 if s.slug == self.state:
52 min_days_since=self.min_days_since,
53 max_days_since=self.max_days_since,
56 raise ValueError('Unknown state', s.state)
58 def send(self, contact, verbose=False, dry_run=False, test=False):
59 state = self.get_state(test=test)
60 ctx = state.get_context(contact)
61 ctx['contact'] = contact
64 subject = Template(self.subject).render(ctx)
66 subject = "[test] " + subject
68 body_template = '{% extends "messaging/email_body.html" %}{% block body %}' + self.body + '{% endblock %}'
69 body = Template(body_template).render(ctx)
72 print(contact.email, subject)
75 send_mail(subject, body, settings.CONTACT_EMAIL, [contact.email], fail_silently=False)
80 self.emailsent_set.create(
86 def send_test_email(self, email):
91 self.send(contact, test=True)
94 class Contact(models.Model):
95 email = models.EmailField(unique=True)
96 level = models.PositiveSmallIntegerField(
98 (Level.COLD, _('Cold')),
99 (Level.TRIED, _('Would-be donor')),
100 (Level.SINGLE, _('One-time donor')),
101 (Level.RECURRING, _('Recurring donor')),
102 (Level.OPT_OUT, _('Opt out')),
104 since = models.DateTimeField()
105 expires_at = models.DateTimeField(null=True, blank=True)
106 key = models.CharField(max_length=64, blank=True)
109 verbose_name = _('contact')
110 verbose_name_plural = _('contacts')
112 def save(self, *args, **kwargs):
114 self.key = get_random_hash(self.email)
115 super().save(*args, **kwargs)
117 def get_optout_url(self):
118 return reverse('messaging_optout', args=[self.key])
121 def update(cls, email, level, since, expires_at=None):
122 obj, created = cls.objects.get_or_create(email=email, defaults={
125 "expires_at": expires_at
128 obj.ascend(level, since, expires_at)
130 def ascend(self, level, since, expires_at=None):
131 if level < self.level:
133 if level == self.level:
134 self.since = min(since, self.since)
136 if expires_at and self.expires_at:
137 self.expires_at = max(expires_at, self.expires_at)
139 self.expires_at = expires_at
143 self.expires_at = expires_at
147 class EmailSent(models.Model):
148 template = models.ForeignKey(EmailTemplate, models.CASCADE)
149 contact = models.ForeignKey(Contact, models.CASCADE)
150 timestamp = models.DateTimeField(auto_now_add=True)
151 subject = models.CharField(_('subject'), max_length=1024)
152 body = models.TextField(_('body'))
155 verbose_name = _('email sent')
156 verbose_name_plural = _('emails sent')
157 ordering = ('-timestamp',)
160 return '%s %s' % (self.email, self.timestamp)