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 recurring_payment_method, single_payment_method
15 from .payu import models as payu_models
19 class Club(models.Model):
20 min_amount = models.IntegerField(_('minimum amount'))
21 min_for_year = models.IntegerField(_('minimum amount for year'))
22 single_amounts = models.CharField(_('proposed amounts for single payment'), max_length=255)
23 default_single_amount = models.IntegerField(_('default single amount'))
24 monthly_amounts = models.CharField(_('proposed amounts for monthly payments'), max_length=255)
25 default_monthly_amount = models.IntegerField(_('default monthly amount'))
28 verbose_name = _('club')
29 verbose_name_plural = _('clubs')
34 def proposed_single_amounts(self):
35 return [int(x) for x in self.single_amounts.split(',')]
37 def proposed_monthly_amounts(self):
38 return [int(x) for x in self.monthly_amounts.split(',')]
41 class Schedule(models.Model):
42 """ Represents someone taking up a plan. """
43 key = models.CharField(_('key'), max_length=255, unique=True)
44 email = models.EmailField(_('email'))
45 membership = models.ForeignKey('Membership', verbose_name=_('membership'), null=True, blank=True, on_delete=models.PROTECT)
46 amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2)
47 monthly = models.BooleanField(_('monthly'), default=True)
48 yearly = models.BooleanField(_('yearly'), default=False)
50 is_cancelled = models.BooleanField(_('cancelled'), default=False)
51 payed_at = models.DateTimeField(_('payed at'), null=True, blank=True)
52 started_at = models.DateTimeField(_('started at'), auto_now_add=True)
53 expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
54 email_sent = models.BooleanField(default=False)
57 verbose_name = _('schedule')
58 verbose_name_plural = _('schedules')
63 def save(self, *args, **kwargs):
65 self.key = get_random_hash(self.email)
66 return super(Schedule, self).save(*args, **kwargs)
68 def initiate_payment(self, request):
69 return self.get_payment_method().initiate(request, self)
71 def pay(self, request):
72 return self.get_payment_method().pay(request, self)
74 def get_absolute_url(self):
75 return reverse('club_schedule', args=[self.key])
77 def get_thanks_url(self):
78 return reverse('club_thanks', args=[self.key])
80 def get_payment_method(self):
81 return recurring_payment_method if self.monthly or self.yearly else single_payment_method
84 return self.expires_at is not None and self.expires_at <= now()
87 return self.payed_at is not None and (self.expires_at is None or self.expires_at > now())
89 def is_recurring(self):
90 return self.monthly or self.yearly
92 def get_next_installment(self, date):
94 return utils.add_year(date)
96 return utils.add_month(date)
97 club = Club.objects.first()
98 if club is not None and self.amount >= club.min_for_year:
99 return utils.add_year(date)
100 return utils.add_month(date)
102 def send_email(self):
103 ctx = {'schedule': self}
105 template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
106 template.loader.render_to_string('club/email/thanks.txt', ctx),
107 settings.CONTACT_EMAIL, [self.email], fail_silently=False)
108 self.email_sent = True
112 class Membership(models.Model):
113 """ Represents a user being recognized as a member of the club. """
114 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
115 created_at = models.DateTimeField(_('created at'), auto_now_add=True)
116 name = models.CharField(max_length=255, blank=True)
117 honorary = models.BooleanField(default=False)
120 verbose_name = _('membership')
121 verbose_name_plural = _('memberships')
124 return str(self.user)
127 def is_active_for(cls, user):
128 if user.is_anonymous:
131 membership = user.membership
132 except cls.DoesNotExist:
134 if membership.honorary:
136 return Schedule.objects.filter(
137 expires_at__gt=now(),
138 membership__user=user,
142 class ReminderEmail(models.Model):
143 days_before = models.SmallIntegerField(_('days before'))
144 subject = models.CharField(_('subject'), max_length=1024)
145 body = models.TextField(_('body'))
148 verbose_name = _('reminder email')
149 verbose_name_plural = _('reminder emails')
150 ordering = ['days_before']
153 if self.days_before >= 0:
154 return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
156 return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
159 class Ambassador(models.Model):
160 name = models.CharField(_('name'), max_length=255)
161 photo = models.ImageField(_('photo'), blank=True)
162 text = models.CharField(_('text'), max_length=1024)
165 verbose_name = _('ambassador')
166 verbose_name_plural = _('ambassadors')
179 class PayUOrder(payu_models.Order):
180 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
182 def get_amount(self):
183 return self.schedule.amount
187 "email": self.schedule.email,
188 "language": get_language(),
191 def get_continue_url(self):
192 return "https://{}{}".format(
193 Site.objects.get_current().domain,
194 self.schedule.get_thanks_url())
196 def get_description(self):
197 return ugettext('Towarzystwo Wolnych Lektur')
199 def is_recurring(self):
200 return self.schedule.get_payment_method().is_recurring
202 def get_card_token(self):
203 return self.schedule.payucardtoken_set.order_by('-created_at').first()
205 def get_notify_url(self):
206 return "https://{}{}".format(
207 Site.objects.get_current().domain,
208 reverse('club_payu_notify', args=[self.pk]))
210 def status_updated(self):
211 if self.status == 'COMPLETED':
212 since = self.schedule.expires_at
214 if since is None or since < n:
216 new_exp = self.schedule.get_next_installment(since)
217 if self.schedule.payed_at is None:
218 self.schedule.payed_at = n
219 if self.schedule.expires_at is None or self.schedule.expires_at < new_exp:
220 self.schedule.expires_at = new_exp
223 if not self.schedule.email_sent:
224 self.schedule.send_email()
227 class PayUCardToken(payu_models.CardToken):
228 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
231 class PayUNotification(payu_models.Notification):
232 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')