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.MANUAL_MEMBER, _('Manually set as member')),
116 (Level.OPT_OUT, _('Opt out')),
118 since = models.DateTimeField()
119 expires_at = models.DateTimeField(null=True, blank=True)
120 key = models.CharField(max_length=64, blank=True)
123 verbose_name = _('contact')
124 verbose_name_plural = _('contacts')
126 def save(self, *args, **kwargs):
128 self.key = get_random_hash(self.email)
129 super().save(*args, **kwargs)
132 def is_annoyed(self):
133 cutoff = now() - timedelta(settings.MESSAGING_MIN_DAYS)
134 return self.emailsent_set.filter(timestamp__gte=cutoff).exists()
136 def get_optout_url(self):
137 return reverse('messaging_optout', args=[self.key])
140 def update(cls, email, level, since, expires_at=None):
141 obj, created = cls.objects.get_or_create(email=email, defaults={
144 "expires_at": expires_at
147 obj.ascend(level, since, expires_at)
149 def ascend(self, level, since=None, expires_at=None):
152 if level < self.level:
154 if level == self.level:
155 self.since = min(since, self.since)
157 if expires_at and self.expires_at:
158 self.expires_at = max(expires_at, self.expires_at)
160 self.expires_at = expires_at
164 self.expires_at = expires_at
168 def reset(cls, email):
169 cls.objects.filter(email=email).delete()
170 Schedule = apps.get_model('club', 'Schedule')
171 Membership = apps.get_model('club', 'Membership')
172 for schedule in Schedule.objects.filter(email=email):
173 schedule.update_contact()
174 for membership in Membership.objects.filter(manual=True, user__email=email):
175 membership.update_contact()
177 def wl_optout_url(self):
178 return 'https://wolnelektury.pl' + self.get_optout_url()
181 class EmailSent(models.Model):
182 template = models.ForeignKey(EmailTemplate, models.CASCADE)
183 contact = models.ForeignKey(Contact, models.CASCADE)
184 timestamp = models.DateTimeField(auto_now_add=True)
185 subject = models.CharField(_('subject'), max_length=1024)
186 body = models.TextField(_('body'))
189 verbose_name = _('email sent')
190 verbose_name_plural = _('emails sent')
191 ordering = ('-timestamp',)
194 return '%s %s' % (self.contact.email, self.timestamp)