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 .recipient import Recipient
11 from .states import 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()
42 recipients = state(time=time, offset=self.days).get_recipients()
43 hash_values = set(recipient.hash_value for recipient in recipients)
44 sent = set(EmailSent.objects.filter(
45 template=self, hash_value__in=hash_values
46 ).values_list('hash_value', flat=True))
47 for recipient in recipients:
48 if recipient.hash_value in sent:
50 self.send(recipient, verbose=verbose, dry_run=dry_run)
54 if s.slug == self.state:
56 raise ValueError('Unknown state', s.state)
58 def send(self, recipient, verbose=False, dry_run=False, test=False):
59 ctx = Context(recipient.context)
62 contact = Contact(email=recipient.email, key='test')
64 # TODO: actually, we should just use Contacts instead of recipients.
65 contact = Contact.objects.get(email=recipient.email)
67 ctx['contact'] = contact
69 subject = Template(self.subject).render(ctx)
72 subject = "[test] " + subject
74 body_template = '{% extends "messaging/email_body.html" %}{% block body %}' + self.body + '{% endblock %}'
76 body = Template(body_template).render(ctx)
78 print(recipient.email, subject)
81 send_mail(subject, body, settings.CONTACT_EMAIL, [recipient.email], fail_silently=False)
86 self.emailsent_set.create(
87 hash_value=recipient.hash_value,
88 email=recipient.email,
93 def send_test_email(self, email):
94 state = self.get_state()()
95 recipient = state.get_example_recipient(email)
96 self.send(recipient, test=True)
99 class EmailSent(models.Model):
100 template = models.ForeignKey(EmailTemplate, models.CASCADE)
101 hash_value = models.CharField(max_length=1024)
102 timestamp = models.DateTimeField(auto_now_add=True)
103 email = models.CharField(_('e-mail'), max_length=1024)
104 subject = models.CharField(_('subject'), max_length=1024)
105 body = models.TextField(_('body'))
108 verbose_name = _('email sent')
109 verbose_name_plural = _('emails sent')
110 ordering = ('-timestamp',)
113 return '%s %s' % (self.email, self.timestamp)
116 class Contact(models.Model):
123 email = models.EmailField(unique=True)
124 level = models.PositiveSmallIntegerField(
126 (TRIED, _('Would-be donor')),
127 (SINGLE, _('One-time donor')),
128 (RECURRING, _('Recurring donor')),
130 (OPT_OUT, _('Opt out')),
132 since = models.DateTimeField()
133 expires_at = models.DateTimeField(null=True, blank=True)
134 key = models.CharField(max_length=64, blank=True)
136 def save(self, *args, **kwargs):
138 self.key = get_random_hash(self.email)
139 super().save(*args, **kwargs)
141 def get_optout_url(self):
142 return reverse('messaging_optout', args=[self.key])
145 def update(cls, email, level, since, expires_at=None):
146 obj, created = cls.objects.get_or_create(email=email, defaults={
149 "expires_at": expires_at
152 obj.ascend(level, since, expires_at)
154 def ascend(self, level, since, expires_at=None):
155 if level < self.level:
157 if level == self.level:
158 self.since = min(since, self.since)
160 if expires_at and self.expires_at:
161 self.expires_at = max(expires_at, self.expires_at)
163 self.expires_at = expires_at
167 self.expires_at = expires_at