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 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('stan', max_length=128, choices=[(s.slug, s.name) for s in states], help_text='?')
16 subject = models.CharField('temat', max_length=1024)
17 body = models.TextField('treść')
18 min_days_since = models.SmallIntegerField('dni po, od', null=True, blank=True)
19 max_days_since = models.SmallIntegerField('dni po, do', null=True, blank=True)
20 min_hour = models.PositiveSmallIntegerField('od godziny', null=True, blank=True)
21 max_hour = models.PositiveSmallIntegerField('do godziny', null=True, blank=True)
22 min_day_of_month = models.PositiveSmallIntegerField('od dnia miesiąca', null=True, blank=True)
23 max_day_of_month = models.PositiveSmallIntegerField('do dnia miesiąca', null=True, blank=True)
24 dow_1 = models.BooleanField('poniedziałek', default=True)
25 dow_2 = models.BooleanField('wtorek', default=True)
26 dow_3 = models.BooleanField('środa', default=True)
27 dow_4 = models.BooleanField('czwartek', default=True)
28 dow_5 = models.BooleanField('piątek', default=True)
29 dow_6 = models.BooleanField('sobota', default=True)
30 dow_7 = models.BooleanField('niedziela', default=True)
31 is_active = models.BooleanField('aktywny', default=False)
34 verbose_name = 'szablon e-maila'
35 verbose_name_plural = 'szablony e-maili'
38 return '%s (%+d)' % (self.get_state_display(), self.min_days_since or 0)
41 def get_current(cls, time=None):
42 time = (time or now()).astimezone(get_current_timezone())
43 weekday = time.isoweekday()
44 qs = cls.objects.filter(is_active=True)
45 qs = qs.exclude(min_hour__gt=time.hour).exclude(max_hour__lte=time.hour)
46 qs = qs.exclude(min_day_of_month__gt=time.day).exclude(max_day_of_month__lte=time.day)
47 qs = qs.exclude(**{f'dow_{weekday}': False})
50 def run(self, time=None, verbose=False, dry_run=False):
51 state = self.get_state(time=time)
52 contacts = state.get_contacts()
54 contacts = contacts.exclude(emailsent__template=self)
55 for contact in contacts:
56 if not contact.is_annoyed:
57 self.send(contact, verbose=verbose, dry_run=dry_run)
59 def get_state(self, time=None, test=False):
61 if s.slug == self.state:
64 min_days_since=self.min_days_since,
65 max_days_since=self.max_days_since,
68 raise ValueError('Unknown state', s.state)
70 def send(self, contact, verbose=False, dry_run=False, test=False):
71 state = self.get_state(test=test)
72 ctx = state.get_context(contact)
73 ctx['contact'] = contact
76 subject = Template(self.subject).render(ctx)
78 subject = "[test] " + subject
80 body_template = '{% extends "messaging/email_body.html" %}{% block body %}' + self.body + '{% endblock %}'
81 body = Template(body_template).render(ctx)
84 print(self.pk, subject, contact.email)
87 send_mail(subject, body, settings.CONTACT_EMAIL, [contact.email], fail_silently=False)
92 self.emailsent_set.create(
98 def send_test_email(self, email):
103 self.send(contact, test=True)
106 class Contact(models.Model):
107 email = models.EmailField(unique=True)
108 level = models.PositiveSmallIntegerField(
110 (Level.COLD, 'Lodówka'),
111 (Level.TRIED, 'Niedoszły darczyńca'),
112 (Level.SINGLE, 'Darczyńca z jednorazową wpłatą'),
113 (Level.RECURRING, 'Darczyńca z wpłatą cykliczną'),
114 (Level.MANUAL_MEMBER, 'Członkostwo ustawione ręcznie'),
115 (Level.OPT_OUT, 'Opt out'),
117 since = models.DateTimeField()
118 expires_at = models.DateTimeField(null=True, blank=True)
119 key = models.CharField(max_length=64, blank=True)
122 verbose_name = 'kontakt'
123 verbose_name_plural = 'kontakty'
125 def save(self, *args, **kwargs):
127 self.key = get_random_hash(self.email)
128 super().save(*args, **kwargs)
131 def is_annoyed(self):
132 cutoff = now() - timedelta(settings.MESSAGING_MIN_DAYS)
133 return self.emailsent_set.filter(timestamp__gte=cutoff).exists()
135 def get_optout_url(self):
136 return reverse('messaging_optout', args=[self.key])
139 def update(cls, email, level, since, expires_at=None):
140 obj, created = cls.objects.get_or_create(email=email, defaults={
143 "expires_at": expires_at
146 obj.ascend(level, since, expires_at)
148 def ascend(self, level, since=None, expires_at=None):
151 if level < self.level:
153 if level == self.level:
154 self.since = min(since, self.since)
156 if expires_at and self.expires_at:
157 self.expires_at = max(expires_at, self.expires_at)
159 self.expires_at = expires_at
163 self.expires_at = expires_at
167 def reset(cls, email):
168 cls.objects.filter(email=email).delete()
169 Schedule = apps.get_model('club', 'Schedule')
170 Membership = apps.get_model('club', 'Membership')
171 for schedule in Schedule.objects.filter(email=email):
172 schedule.update_contact()
173 for membership in Membership.objects.filter(manual=True, user__email=email):
174 membership.update_contact()
176 def wl_optout_url(self):
177 return 'https://wolnelektury.pl' + self.get_optout_url()
180 class EmailSent(models.Model):
181 template = models.ForeignKey(EmailTemplate, models.CASCADE)
182 contact = models.ForeignKey(Contact, models.CASCADE)
183 timestamp = models.DateTimeField(auto_now_add=True)
184 subject = models.CharField('temat', max_length=1024)
185 body = models.TextField('treść')
188 verbose_name = 'wysłany e-mail'
189 verbose_name_plural = 'wysłane e-maile'
190 ordering = ('-timestamp',)
193 return '%s %s' % (self.contact.email, self.timestamp)