1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from datetime import datetime, timedelta
5 from django.apps import apps
6 from django.conf import settings
7 from django.contrib.sites.models import Site
8 from django.core.mail import send_mail
9 from django.urls import reverse
10 from django.db import models
11 from django import template
12 from django.utils.timezone import now
13 from django.utils.translation import ugettext_lazy as _, ungettext, ugettext, get_language
14 from catalogue.utils import get_random_hash
15 from .payment_methods import recurring_payment_method, single_payment_method
16 from .payu import models as payu_models
20 class Club(models.Model):
21 min_amount = models.IntegerField(_('minimum amount'))
22 min_for_year = models.IntegerField(_('minimum amount for year'))
23 single_amounts = models.CharField(_('proposed amounts for single payment'), max_length=255)
24 default_single_amount = models.IntegerField(_('default single amount'))
25 monthly_amounts = models.CharField(_('proposed amounts for monthly payments'), max_length=255)
26 default_monthly_amount = models.IntegerField(_('default monthly amount'))
29 verbose_name = _('club')
30 verbose_name_plural = _('clubs')
35 def proposed_single_amounts(self):
36 return [int(x) for x in self.single_amounts.split(',')]
38 def proposed_monthly_amounts(self):
39 return [int(x) for x in self.monthly_amounts.split(',')]
42 class Schedule(models.Model):
43 """ Represents someone taking up a plan. """
44 key = models.CharField(_('key'), max_length=255, unique=True)
45 email = models.EmailField(_('email'))
46 membership = models.ForeignKey('Membership', verbose_name=_('membership'), null=True, blank=True, on_delete=models.PROTECT)
47 amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2)
48 monthly = models.BooleanField(_('monthly'), default=True)
49 yearly = models.BooleanField(_('yearly'), default=False)
51 is_cancelled = models.BooleanField(_('cancelled'), default=False)
52 payed_at = models.DateTimeField(_('payed at'), null=True, blank=True)
53 started_at = models.DateTimeField(_('started at'), auto_now_add=True)
54 expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
55 email_sent = models.BooleanField(default=False)
58 verbose_name = _('schedule')
59 verbose_name_plural = _('schedules')
64 def save(self, *args, **kwargs):
66 self.key = get_random_hash(self.email)
67 super(Schedule, self).save(*args, **kwargs)
70 def initiate_payment(self, request):
71 return self.get_payment_method().initiate(request, self)
73 def pay(self, request):
74 return self.get_payment_method().pay(request, self)
76 def get_absolute_url(self):
77 return reverse('club_schedule', args=[self.key])
79 def get_thanks_url(self):
80 return reverse('club_thanks', args=[self.key])
82 def get_payment_method(self):
83 return recurring_payment_method if self.monthly or self.yearly else single_payment_method
86 return self.expires_at is not None and self.expires_at <= now()
89 return self.payed_at is not None and (self.expires_at is None or self.expires_at > now())
91 def is_recurring(self):
92 return self.monthly or self.yearly
94 def get_next_installment(self, date):
96 return utils.add_year(date)
98 return utils.add_month(date)
99 club = Club.objects.first()
100 if club is not None and self.amount >= club.min_for_year:
101 return utils.add_year(date)
102 return utils.add_month(date)
104 def send_email(self):
105 ctx = {'schedule': self}
107 template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
108 template.loader.render_to_string('club/email/thanks.txt', ctx),
109 settings.CONTACT_EMAIL, [self.email], fail_silently=False)
110 self.email_sent = True
113 def update_contact(self):
114 Contact = apps.get_model('messaging', 'Contact')
115 if not self.payed_at:
116 level = Contact.TRIED
117 since = self.started_at
119 since = self.payed_at
120 if self.is_recurring():
121 level = Contact.RECURRING
123 level = Contact.SINGLE
124 Contact.update(self.email, level, since, self.expires_at)
127 class Membership(models.Model):
128 """ Represents a user being recognized as a member of the club. """
129 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
130 created_at = models.DateTimeField(_('created at'), auto_now_add=True)
131 name = models.CharField(max_length=255, blank=True)
132 honorary = models.BooleanField(default=False)
135 verbose_name = _('membership')
136 verbose_name_plural = _('memberships')
139 return str(self.user)
142 def is_active_for(cls, user):
143 if user.is_anonymous:
146 membership = user.membership
147 except cls.DoesNotExist:
149 if membership.honorary:
151 return Schedule.objects.filter(
152 expires_at__gt=now(),
153 membership__user=user,
157 class ReminderEmail(models.Model):
158 days_before = models.SmallIntegerField(_('days before'))
159 subject = models.CharField(_('subject'), max_length=1024)
160 body = models.TextField(_('body'))
163 verbose_name = _('reminder email')
164 verbose_name_plural = _('reminder emails')
165 ordering = ['days_before']
168 if self.days_before >= 0:
169 return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
171 return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
174 class Ambassador(models.Model):
175 name = models.CharField(_('name'), max_length=255)
176 photo = models.ImageField(_('photo'), blank=True)
177 text = models.CharField(_('text'), max_length=1024)
180 verbose_name = _('ambassador')
181 verbose_name_plural = _('ambassadors')
194 class PayUOrder(payu_models.Order):
195 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
197 def get_amount(self):
198 return self.schedule.amount
202 "email": self.schedule.email,
203 "language": get_language(),
206 def get_continue_url(self):
207 return "https://{}{}".format(
208 Site.objects.get_current().domain,
209 self.schedule.get_thanks_url())
211 def get_description(self):
212 return ugettext('Towarzystwo Wolnych Lektur')
214 def is_recurring(self):
215 return self.schedule.get_payment_method().is_recurring
217 def get_card_token(self):
218 return self.schedule.payucardtoken_set.order_by('-created_at').first()
220 def get_notify_url(self):
221 return "https://{}{}".format(
222 Site.objects.get_current().domain,
223 reverse('club_payu_notify', args=[self.pk]))
225 def status_updated(self):
226 if self.status == 'COMPLETED':
227 since = self.schedule.expires_at
229 if since is None or since < n:
231 new_exp = self.schedule.get_next_installment(since)
232 if self.schedule.payed_at is None:
233 self.schedule.payed_at = n
234 if self.schedule.expires_at is None or self.schedule.expires_at < new_exp:
235 self.schedule.expires_at = new_exp
238 if not self.schedule.email_sent:
239 self.schedule.send_email()
242 class PayUCardToken(payu_models.CardToken):
243 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
246 class PayUNotification(payu_models.Notification):
247 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')