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 payed_at = models.DateTimeField(_('payed at'), null=True, blank=True)
74 started_at = models.DateTimeField(_('started at'), auto_now_add=True)
75 expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
76 email_sent = models.BooleanField(default=False)
79 verbose_name = _('schedule')
80 verbose_name_plural = _('schedules')
85 def save(self, *args, **kwargs):
87 self.key = get_random_hash(self.email)
88 return super(Schedule, self).save(*args, **kwargs)
90 def initiate_payment(self, request):
91 return self.get_payment_method().initiate(request, self)
93 def pay(self, request):
94 return self.get_payment_method().pay(request, self)
96 def get_absolute_url(self):
97 return reverse('club_schedule', args=[self.key])
99 def get_thanks_url(self):
100 return reverse('club_thanks', args=[self.key])
102 def get_payment_method(self):
103 return method_by_slug[self.method]
105 def is_expired(self):
106 return self.expires_at is not None and self.expires_at <= now()
109 return self.payed_at is not None and (self.expires_at is None or self.expires_at > now())
111 def send_email(self):
112 ctx = {'schedule': self}
114 template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
115 template.loader.render_to_string('club/email/thanks.txt', ctx),
116 settings.CONTACT_EMAIL, [self.email], fail_silently=False)
117 self.email_sent = True
121 class Membership(models.Model):
122 """ Represents a user being recognized as a member of the club. """
123 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
124 created_at = models.DateTimeField(_('created at'), auto_now_add=True)
125 name = models.CharField(max_length=255, blank=True)
126 honorary = models.BooleanField(default=False)
129 verbose_name = _('membership')
130 verbose_name_plural = _('memberships')
133 return str(self.user)
136 def is_active_for(cls, user):
137 if user.is_anonymous:
140 membership = user.membership
141 except cls.DoesNotExist:
143 if membership.honorary:
145 return Schedule.objects.filter(
146 expires_at__gt=now(),
147 membership__user=user,
151 class ReminderEmail(models.Model):
152 days_before = models.SmallIntegerField(_('days before'))
153 subject = models.CharField(_('subject'), max_length=1024)
154 body = models.TextField(_('body'))
157 verbose_name = _('reminder email')
158 verbose_name_plural = _('reminder emails')
159 ordering = ['days_before']
162 if self.days_before >= 0:
163 return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
165 return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
174 class PayUOrder(payu_models.Order):
175 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
177 def get_amount(self):
178 return self.schedule.amount
182 "email": self.schedule.email,
183 "language": get_language(),
186 def get_continue_url(self):
187 return "https://{}{}".format(
188 Site.objects.get_current().domain,
189 self.schedule.get_thanks_url())
191 def get_description(self):
192 return ugettext('Towarzystwo Wolnych Lektur')
194 def is_recurring(self):
195 return self.schedule.get_payment_method().is_recurring
197 def get_card_token(self):
198 return self.schedule.payucardtoken_set.order_by('-created_at').first()
200 def get_notify_url(self):
201 return "https://{}{}".format(
202 Site.objects.get_current().domain,
203 reverse('club_payu_notify', args=[self.pk]))
205 def status_updated(self):
206 if self.status == 'COMPLETED':
207 since = self.schedule.expires_at
209 if since is None or since < n:
211 new_exp = self.schedule.plan.get_next_installment(since)
212 if self.schedule.payed_at is None:
213 self.schedule.payed_at = n
214 if self.schedule.expires_at is None or self.schedule.expires_at < new_exp:
215 self.schedule.expires_at = new_exp
218 if not self.schedule.email_sent:
219 self.schedule.send_email()
222 class PayUCardToken(payu_models.CardToken):
223 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
226 class PayUNotification(payu_models.Notification):
227 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')