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.conf import settings
6 from django.contrib.sites.models import Site
7 from django.core.mail import send_mail
8 from django.urls import reverse
9 from django.db import models
10 from django import template
11 from django.utils.timezone import now
12 from django.utils.translation import ugettext_lazy as _, ungettext, ugettext, get_language
13 from catalogue.utils import get_random_hash
14 from .payment_methods import methods, method_by_slug
15 from .payu import models as payu_models
18 class Plan(models.Model):
19 """ Plans are set up by administrators. """
24 (MONTH, _('a month')),
26 (PERPETUAL, _('in perpetuity')),
29 interval = models.SmallIntegerField(_('inteval'), choices=intervals)
30 min_amount = models.DecimalField(_('min amount'), max_digits=10, decimal_places=2)
31 default_amount = models.DecimalField(_('default amount'), max_digits=10, decimal_places=2)
32 allow_recurring = models.BooleanField(_('allow recurring'))
33 allow_one_time = models.BooleanField(_('allow one time'))
34 active = models.BooleanField(_('active'), default=True)
37 verbose_name = _('plan')
38 verbose_name_plural = _('plans')
41 return "%s %s" % (self.min_amount, self.get_interval_display())
44 ordering = ('interval',)
46 def payment_methods(self):
47 for method in methods:
48 if self.allow_recurring and method.is_recurring or self.allow_one_time and not method.is_recurring:
51 def get_next_installment(self, date):
52 if self.interval == self.PERPETUAL:
53 return datetime.max - timedelta(1)
54 elif self.interval == self.YEAR:
55 return date.replace(year=date.year + 1)
56 elif self.interval == self.MONTH:
58 date = (date.replace(day=1) + timedelta(31)).replace(day=1) + timedelta(day - 1)
60 date = date.replace(day=1)
64 class Schedule(models.Model):
65 """ Represents someone taking up a plan. """
66 key = models.CharField(_('key'), max_length=255, unique=True)
67 email = models.EmailField(_('email'))
68 membership = models.ForeignKey('Membership', verbose_name=_('membership'), null=True, blank=True, on_delete=models.PROTECT)
69 plan = models.ForeignKey(Plan, verbose_name=_('plan'), on_delete=models.PROTECT)
70 amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2)
71 method = models.CharField(_('method'), max_length=255, choices=[(method.slug, method.name) for method in methods])
72 is_cancelled = models.BooleanField(_('cancelled'), default=False)
73 started_at = models.DateTimeField(_('started at'), auto_now_add=True)
74 expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
75 email_sent = models.BooleanField(default=False)
78 verbose_name = _('schedule')
79 verbose_name_plural = _('schedules')
84 def save(self, *args, **kwargs):
86 self.key = get_random_hash(self.email)
87 return super(Schedule, self).save(*args, **kwargs)
89 def initiate_payment(self, request):
90 return self.get_payment_method().initiate(request, self)
92 def pay(self, request):
93 return self.get_payment_method().pay(request, self)
95 def get_absolute_url(self):
96 return reverse('club_schedule', args=[self.key])
98 def get_thanks_url(self):
99 return reverse('club_thanks', args=[self.key])
101 def get_payment_method(self):
102 return method_by_slug[self.method]
104 def is_expired(self):
105 return self.expires_at is not None and self.expires_at <= now()
108 return self.expires_at is not None and self.expires_at > now()
110 def send_email(self):
111 ctx = {'schedule': self}
113 template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
114 template.loader.render_to_string('club/email/thanks.txt', ctx),
115 settings.CONTACT_EMAIL, [self.email], fail_silently=False)
116 self.email_sent = True
120 class Membership(models.Model):
121 """ Represents a user being recognized as a member of the club. """
122 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
123 created_at = models.DateTimeField(_('created at'), auto_now_add=True)
124 name = models.CharField(max_length=255, blank=True)
125 honorary = models.BooleanField(default=False)
128 verbose_name = _('membership')
129 verbose_name_plural = _('memberships')
132 return str(self.user)
135 def is_active_for(cls, user):
136 if user.is_anonymous:
139 membership = user.membership
140 except cls.DoesNotExist:
142 if membership.honorary:
144 return Schedule.objects.filter(
145 expires_at__gt=now(),
146 membership__user=user,
150 class ReminderEmail(models.Model):
151 days_before = models.SmallIntegerField(_('days before'))
152 subject = models.CharField(_('subject'), max_length=1024)
153 body = models.TextField(_('body'))
156 verbose_name = _('reminder email')
157 verbose_name_plural = _('reminder emails')
158 ordering = ['days_before']
161 if self.days_before >= 0:
162 return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
164 return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
173 class PayUOrder(payu_models.Order):
174 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
176 def get_amount(self):
177 return self.schedule.amount
181 "email": self.schedule.email,
182 "language": get_language(),
185 def get_continue_url(self):
186 return "https://{}{}".format(
187 Site.objects.get_current().domain,
188 self.schedule.get_thanks_url())
190 def get_description(self):
191 return ugettext('Towarzystwo Wolnych Lektur')
193 def is_recurring(self):
194 return self.schedule.get_payment_method().is_recurring
196 def get_card_token(self):
197 return self.schedule.payucardtoken_set.order_by('-created_at').first()
199 def get_notify_url(self):
200 return "https://{}{}".format(
201 Site.objects.get_current().domain,
202 reverse('club_payu_notify', args=[self.pk]))
204 def status_updated(self):
205 if self.status == 'COMPLETED':
206 since = self.schedule.expires_at or now()
207 new_exp = self.schedule.plan.get_next_installment(since)
208 if self.schedule.expires_at is None or self.schedule.expires_at < new_exp:
209 self.schedule.expires_at = new_exp
212 if not self.schedule.email_sent:
213 self.schedule.send_email()
216 class PayUCardToken(payu_models.CardToken):
217 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
220 class PayUNotification(payu_models.Notification):
221 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')