1 from datetime import datetime, timedelta
2 from django.conf import settings
3 from django.contrib.sites.models import Site
4 from django.core.mail import send_mail
5 from django.urls import reverse
6 from django.db import models
7 from django import template
8 from django.utils.timezone import now
9 from django.utils.translation import ugettext_lazy as _, ungettext, ugettext, get_language
10 from catalogue.utils import get_random_hash
11 from .payment_methods import methods, method_by_slug
12 from .payu import models as payu_models
15 class Plan(models.Model):
16 """ Plans are set up by administrators. """
21 (MONTH, _('a month')),
23 (PERPETUAL, _('in perpetuity')),
26 interval = models.SmallIntegerField(_('inteval'), choices=intervals)
27 min_amount = models.DecimalField(_('min amount'), max_digits=10, decimal_places=2)
28 default_amount = models.DecimalField(_('default amount'), max_digits=10, decimal_places=2)
29 allow_recurring = models.BooleanField(_('allow recurring'))
30 allow_one_time = models.BooleanField(_('allow one time'))
31 active = models.BooleanField(_('active'), default=True)
34 verbose_name = _('plan')
35 verbose_name_plural = _('plans')
38 return "%s %s" % (self.min_amount, self.get_interval_display())
41 ordering = ('interval',)
43 def payment_methods(self):
44 for method in methods:
45 if self.allow_recurring and method.is_recurring or self.allow_one_time and not method.is_recurring:
48 def get_next_installment(self, date):
49 if self.interval == self.PERPETUAL:
50 return datetime.max - timedelta(1)
51 elif self.interval == self.YEAR:
52 return date.replace(year=date.year + 1)
53 elif self.interval == self.MONTH:
55 date = (date.replace(day=1) + timedelta(31)).replace(day=1) + timedelta(day - 1)
57 date = date.replace(day=1)
61 class Schedule(models.Model):
62 """ Represents someone taking up a plan. """
63 key = models.CharField(_('key'), max_length=255, unique=True)
64 email = models.EmailField(_('email'))
65 membership = models.ForeignKey('Membership', verbose_name=_('membership'), null=True, blank=True, on_delete=models.PROTECT)
66 plan = models.ForeignKey(Plan, verbose_name=_('plan'), on_delete=models.PROTECT)
67 amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2)
68 method = models.CharField(_('method'), max_length=255, choices=[(method.slug, method.name) for method in methods])
69 is_cancelled = models.BooleanField(_('cancelled'), default=False)
70 started_at = models.DateTimeField(_('started at'), auto_now_add=True)
71 expires_at = models.DateTimeField(_('expires_at'), null=True, blank=True)
72 email_sent = models.BooleanField(default=False)
75 verbose_name = _('schedule')
76 verbose_name_plural = _('schedules')
81 def save(self, *args, **kwargs):
83 self.key = get_random_hash(self.email)
84 return super(Schedule, self).save(*args, **kwargs)
86 def initiate_payment(self, request):
87 return self.get_payment_method().initiate(request, self)
89 def pay(self, request):
90 return self.get_payment_method().pay(request, self)
92 def get_absolute_url(self):
93 return reverse('club_schedule', args=[self.key])
95 def get_thanks_url(self):
96 return reverse('club_thanks', args=[self.key])
98 def get_payment_method(self):
99 return method_by_slug[self.method]
101 def is_expired(self):
102 return self.expires_at is not None and self.expires_at <= now()
105 return self.expires_at is not None and self.expires_at > now()
107 def send_email(self):
108 ctx = {'schedule': self}
110 template.loader.render_to_string('club/email/thanks_subject.txt', ctx).strip(),
111 template.loader.render_to_string('club/email/thanks.txt', ctx),
112 settings.CONTACT_EMAIL, [self.email], fail_silently=False)
113 self.email_sent = True
117 class Membership(models.Model):
118 """ Represents a user being recognized as a member of the club. """
119 user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
120 created_at = models.DateTimeField(_('created at'), auto_now_add=True)
121 name = models.CharField(max_length=255, blank=True)
122 honorary = models.BooleanField(default=False)
125 verbose_name = _('membership')
126 verbose_name_plural = _('memberships')
129 return u'tow. ' + str(self.user)
132 def is_active_for(cls, user):
133 if user.is_anonymous:
136 membership = user.membership
137 except cls.DoesNotExist:
139 if membership.honorary:
141 return Schedule.objects.filter(
142 expires_at__gt=now(),
143 membership__user=user,
147 class ReminderEmail(models.Model):
148 days_before = models.SmallIntegerField(_('days before'))
149 subject = models.CharField(_('subject'), max_length=1024)
150 body = models.TextField(_('body'))
153 verbose_name = _('reminder email')
154 verbose_name_plural = _('reminder emails')
155 ordering = ['days_before']
158 if self.days_before >= 0:
159 return ungettext('a day before expiration', '%d days before expiration', n=self.days_before)
161 return ungettext('a day after expiration', '%d days after expiration', n=-self.days_before)
170 class PayUOrder(payu_models.Order):
171 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
173 def get_amount(self):
174 return self.schedule.amount
178 "email": self.schedule.email,
179 "language": get_language(),
182 def get_continue_url(self):
183 return "https://{}{}".format(
184 Site.objects.get_current().domain,
185 self.schedule.get_thanks_url())
187 def get_description(self):
188 return ugettext('Towarzystwo Wolnych Lektur')
190 def is_recurring(self):
191 return self.schedule.get_payment_method().is_recurring
193 def get_card_token(self):
194 return self.schedule.payucardtoken_set.order_by('-created_at').first()
196 def get_notify_url(self):
197 return "https://{}{}".format(
198 Site.objects.get_current().domain,
199 reverse('club_payu_notify', args=[self.pk]))
201 def status_updated(self):
202 if self.status == 'COMPLETED':
203 since = self.schedule.expires_at or now()
204 new_exp = self.schedule.plan.get_next_installment(since)
205 if self.schedule.expires_at is None or self.schedule.expires_at < new_exp:
206 self.schedule.expires_at = new_exp
209 if not self.schedule.email_sent:
210 self.schedule.send_email()
213 class PayUCardToken(payu_models.CardToken):
214 schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
217 class PayUNotification(payu_models.Notification):
218 order = models.ForeignKey(PayUOrder, models.CASCADE, related_name='notification_set')