+class Contact(models.Model):
+ email = models.EmailField(unique=True)
+ level = models.PositiveSmallIntegerField(
+ choices=[
+ (Level.COLD, 'Lodówka'),
+ (Level.TRIED, 'Niedoszły darczyńca'),
+ (Level.SINGLE, 'Darczyńca z jednorazową wpłatą'),
+ (Level.RECURRING, 'Darczyńca z wpłatą cykliczną'),
+ (Level.MANUAL_MEMBER, 'Członkostwo ustawione ręcznie'),
+ (Level.OPT_OUT, 'Opt out'),
+ ])
+ since = models.DateTimeField()
+ expires_at = models.DateTimeField(null=True, blank=True)
+ key = models.CharField(max_length=64, blank=True)
+
+ class Meta:
+ verbose_name = 'kontakt'
+ verbose_name_plural = 'kontakty'
+
+ def save(self, *args, **kwargs):
+ if not self.key:
+ self.key = get_random_hash(self.email)
+ super().save(*args, **kwargs)
+
+ @property
+ def is_annoyed(self):
+ cutoff = now() - timedelta(settings.MESSAGING_MIN_DAYS)
+ return self.emailsent_set.filter(timestamp__gte=cutoff).exists()
+
+ def get_optout_url(self):
+ return reverse('messaging_optout', args=[self.key])
+
+ @classmethod
+ def update(cls, email, level, since, expires_at=None):
+ obj, created = cls.objects.get_or_create(email=email, defaults={
+ "level": level,
+ "since": since,
+ "expires_at": expires_at
+ })
+ if not created:
+ obj.ascend(level, since, expires_at)
+
+ def ascend(self, level, since=None, expires_at=None):
+ if since is None:
+ since = now()
+ if level < self.level:
+ return
+ if level == self.level:
+ self.since = min(since, self.since)
+
+ if expires_at and self.expires_at:
+ self.expires_at = max(expires_at, self.expires_at)
+ else:
+ self.expires_at = expires_at
+ else:
+ self.level = level
+ self.since = since
+ self.expires_at = expires_at
+ self.save()
+
+ @classmethod
+ def reset(cls, email):
+ cls.objects.filter(email=email).delete()
+ Schedule = apps.get_model('club', 'Schedule')
+ Membership = apps.get_model('club', 'Membership')
+ for schedule in Schedule.objects.filter(email=email):
+ schedule.update_contact()
+ for membership in Membership.objects.filter(manual=True, user__email=email):
+ membership.update_contact()
+
+ def wl_optout_url(self):
+ return 'https://wolnelektury.pl' + self.get_optout_url()